Fix: relayd: failure to open chunk files concurrently with session clear
[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>
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;
aaabc543 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 */
9edaf114
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;
9edaf114 282 struct relay_stream *relay_stream = NULL;
2f8f53af 283
a0377dfe 284 LTTNG_ASSERT(relay_session);
9edaf114 285 ASSERT_LOCKED(relay_session->lock);
2f8f53af 286
9edaf114 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();
9edaf114
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 */
9edaf114
JG
310 cds_list_for_each_entry_rcu(relay_stream,
311 &ctf_trace->stream_list, stream_node)
123ed7c2 312 {
9edaf114
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
9edaf114
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
9edaf114
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
9edaf114 343 if (!stream_get(relay_stream)) {
2a174661
DG
344 continue;
345 }
9edaf114
JG
346
347 pthread_mutex_lock(&relay_stream->lock);
7591bab1 348 /*
d812ecb9 349 * stream published is protected by the session lock.
7591bab1 350 */
9edaf114 351 if (!relay_stream->published) {
7591bab1
MD
352 goto next;
353 }
9edaf114
JG
354 viewer_stream = viewer_stream_get_by_id(
355 relay_stream->stream_handle);
356 if (!viewer_stream) {
80516611 357 struct lttng_trace_chunk *viewer_stream_trace_chunk = NULL;
9edaf114 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 */
9edaf114
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 {
80516611
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 }
9edaf114 402
87250ba1
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 LTTNG_ASSERT(reference_acquired);
420 viewer_stream_trace_chunk =
421 viewer_session->current_trace_chunk;
422 }
123ed7c2 423 }
9edaf114
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 */
9edaf114 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 {
9edaf114 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) {
9edaf114
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 {
9edaf114
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. */
9edaf114 473 viewer_stream_put(viewer_stream);
7591bab1 474 next:
9edaf114
JG
475 pthread_mutex_unlock(&relay_stream->lock);
476 stream_put(relay_stream);
2f8f53af 477 }
9edaf114 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();
80516611 486
9edaf114
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);
ad36f3a7
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;
ac497a37 555 struct lttcomm_sock *sock = (lttcomm_sock *) data;
8855795d
JG
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{
ac497a37 570 struct lttcomm_sock *sock = (lttcomm_sock *) data;
8855795d
JG
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. */
ac497a37 579 struct lttcomm_sock **socks = (lttcomm_sock **) data;
29555a78
JG
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);
d546eeec
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
d546eeec 664 free(formated_name);
d3e2ba59
JD
665 return sock;
666
667error:
668 if (sock) {
669 lttcomm_destroy_sock(sock);
670 }
d546eeec 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. */
ac497a37
SM
787 cds_wfcq_head_ptr_t head;
788 head.h = &viewer_conn_queue.head;
789 cds_wfcq_enqueue(head, &viewer_conn_queue.tail,
8bdee6e2 790 &new_conn->qnode);
d3e2ba59
JD
791
792 /*
7591bab1
MD
793 * Wake the dispatch queue futex.
794 * Implicit memory barrier with the
795 * exchange in cds_wfcq_enqueue.
d3e2ba59 796 */
58eb9381 797 futex_nto1_wake(&viewer_conn_queue.futex);
03e43155
MD
798 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
799 ERR("socket poll error");
800 goto error;
801 } else {
802 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
803 goto error;
d3e2ba59
JD
804 }
805 }
806 }
807
808exit:
809error:
810error_poll_add:
9b5e0863 811error_testpoint:
23f940ff 812 (void) fd_tracker_util_poll_clean(the_fd_tracker, &events);
d3e2ba59
JD
813error_create_poll:
814 if (live_control_sock->fd >= 0) {
8855795d
JG
815 int sock_fd = live_control_sock->fd;
816
817 ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker,
818 &sock_fd, 1, close_sock,
819 live_control_sock);
d3e2ba59
JD
820 if (ret) {
821 PERROR("close");
822 }
8855795d 823 live_control_sock->fd = -1;
d3e2ba59
JD
824 }
825 lttcomm_destroy_sock(live_control_sock);
826error_sock_control:
827 if (err) {
eea7556c 828 health_error();
d3e2ba59
JD
829 DBG("Live viewer listener thread exited with error");
830 }
eea7556c 831 health_unregister(health_relayd);
8fba2b8d 832 rcu_unregister_thread();
d3e2ba59 833 DBG("Live viewer listener thread cleanup complete");
b4aacfdc
MD
834 if (lttng_relay_stop_threads()) {
835 ERR("Error stopping threads");
178a0557 836 }
d3e2ba59
JD
837 return NULL;
838}
839
840/*
841 * This thread manages the dispatching of the requests to worker threads
842 */
843static
844void *thread_dispatcher(void *data)
845{
6cd525e8
MD
846 int err = -1;
847 ssize_t ret;
8bdee6e2 848 struct cds_wfcq_node *node;
58eb9381 849 struct relay_connection *conn = NULL;
d3e2ba59
JD
850
851 DBG("[thread] Live viewer relay dispatcher started");
852
eea7556c
MD
853 health_register(health_relayd, HEALTH_RELAYD_TYPE_LIVE_DISPATCHER);
854
9b5e0863
MD
855 if (testpoint(relayd_thread_live_dispatcher)) {
856 goto error_testpoint;
857 }
858
eea7556c
MD
859 health_code_update();
860
0ed3b1a8 861 for (;;) {
eea7556c
MD
862 health_code_update();
863
d3e2ba59 864 /* Atomically prepare the queue futex */
58eb9381 865 futex_nto1_prepare(&viewer_conn_queue.futex);
d3e2ba59 866
0ed3b1a8
MD
867 if (CMM_LOAD_SHARED(live_dispatch_thread_exit)) {
868 break;
869 }
870
d3e2ba59 871 do {
eea7556c
MD
872 health_code_update();
873
d3e2ba59 874 /* Dequeue commands */
8bdee6e2
SM
875 node = cds_wfcq_dequeue_blocking(&viewer_conn_queue.head,
876 &viewer_conn_queue.tail);
d3e2ba59
JD
877 if (node == NULL) {
878 DBG("Woken up but nothing in the live-viewer "
879 "relay command queue");
880 /* Continue thread execution */
881 break;
882 }
58eb9381 883 conn = caa_container_of(node, struct relay_connection, qnode);
d3e2ba59 884 DBG("Dispatching viewer request waiting on sock %d",
58eb9381 885 conn->sock->fd);
d3e2ba59
JD
886
887 /*
7591bab1
MD
888 * Inform worker thread of the new request. This
889 * call is blocking so we can be assured that
890 * the data will be read at some point in time
891 * or wait to the end of the world :)
d3e2ba59 892 */
58eb9381
DG
893 ret = lttng_write(live_conn_pipe[1], &conn, sizeof(conn));
894 if (ret < 0) {
895 PERROR("write conn pipe");
7591bab1 896 connection_put(conn);
d3e2ba59
JD
897 goto error;
898 }
899 } while (node != NULL);
900
901 /* Futex wait on queue. Blocking call on futex() */
eea7556c 902 health_poll_entry();
58eb9381 903 futex_nto1_wait(&viewer_conn_queue.futex);
eea7556c 904 health_poll_exit();
d3e2ba59
JD
905 }
906
eea7556c
MD
907 /* Normal exit, no error */
908 err = 0;
909
d3e2ba59 910error:
9b5e0863 911error_testpoint:
eea7556c
MD
912 if (err) {
913 health_error();
914 ERR("Health error occurred in %s", __func__);
915 }
916 health_unregister(health_relayd);
d3e2ba59 917 DBG("Live viewer dispatch thread dying");
b4aacfdc
MD
918 if (lttng_relay_stop_threads()) {
919 ERR("Error stopping threads");
178a0557 920 }
d3e2ba59
JD
921 return NULL;
922}
923
924/*
925 * Establish connection with the viewer and check the versions.
926 *
927 * Return 0 on success or else negative value.
928 */
929static
58eb9381 930int viewer_connect(struct relay_connection *conn)
d3e2ba59
JD
931{
932 int ret;
933 struct lttng_viewer_connect reply, msg;
934
58eb9381 935 conn->version_check_done = 1;
d3e2ba59 936
eea7556c
MD
937 health_code_update();
938
2f8f53af
DG
939 DBG("Viewer is establishing a connection to the relayd.");
940
58eb9381 941 ret = recv_request(conn->sock, &msg, sizeof(msg));
2f8f53af 942 if (ret < 0) {
d3e2ba59
JD
943 goto end;
944 }
945
eea7556c
MD
946 health_code_update();
947
f46b2ce6 948 memset(&reply, 0, sizeof(reply));
d3e2ba59
JD
949 reply.major = RELAYD_VERSION_COMM_MAJOR;
950 reply.minor = RELAYD_VERSION_COMM_MINOR;
951
952 /* Major versions must be the same */
953 if (reply.major != be32toh(msg.major)) {
2f8f53af
DG
954 DBG("Incompatible major versions ([relayd] %u vs [client] %u)",
955 reply.major, be32toh(msg.major));
72180669 956 ret = -1;
d3e2ba59
JD
957 goto end;
958 }
959
58eb9381 960 conn->major = reply.major;
d3e2ba59
JD
961 /* We adapt to the lowest compatible version */
962 if (reply.minor <= be32toh(msg.minor)) {
58eb9381 963 conn->minor = reply.minor;
d3e2ba59 964 } else {
58eb9381 965 conn->minor = be32toh(msg.minor);
d3e2ba59
JD
966 }
967
c4e361a4 968 if (be32toh(msg.type) == LTTNG_VIEWER_CLIENT_COMMAND) {
58eb9381 969 conn->type = RELAY_VIEWER_COMMAND;
c4e361a4 970 } else if (be32toh(msg.type) == LTTNG_VIEWER_CLIENT_NOTIFICATION) {
58eb9381 971 conn->type = RELAY_VIEWER_NOTIFICATION;
d3e2ba59
JD
972 } else {
973 ERR("Unknown connection type : %u", be32toh(msg.type));
974 ret = -1;
975 goto end;
976 }
977
978 reply.major = htobe32(reply.major);
979 reply.minor = htobe32(reply.minor);
58eb9381 980 if (conn->type == RELAY_VIEWER_COMMAND) {
93b4787b 981 /*
7591bab1
MD
982 * Increment outside of htobe64 macro, because the argument can
983 * be used more than once within the macro, and thus the
984 * operation may be undefined.
93b4787b 985 */
7591bab1 986 pthread_mutex_lock(&last_relay_viewer_session_id_lock);
93b4787b 987 last_relay_viewer_session_id++;
7591bab1 988 pthread_mutex_unlock(&last_relay_viewer_session_id_lock);
93b4787b 989 reply.viewer_session_id = htobe64(last_relay_viewer_session_id);
d3e2ba59 990 }
eea7556c
MD
991
992 health_code_update();
993
58eb9381 994 ret = send_response(conn->sock, &reply, sizeof(reply));
d3e2ba59 995 if (ret < 0) {
2f8f53af 996 goto end;
d3e2ba59
JD
997 }
998
eea7556c
MD
999 health_code_update();
1000
58eb9381 1001 DBG("Version check done using protocol %u.%u", conn->major, conn->minor);
d3e2ba59
JD
1002 ret = 0;
1003
1004end:
1005 return ret;
1006}
1007
1008/*
1009 * Send the viewer the list of current sessions.
7591bab1
MD
1010 * We need to create a copy of the hash table content because otherwise
1011 * we cannot assume the number of entries stays the same between getting
1012 * the number of HT elements and iteration over the HT.
d3e2ba59
JD
1013 *
1014 * Return 0 on success or else a negative value.
1015 */
1016static
58eb9381 1017int viewer_list_sessions(struct relay_connection *conn)
d3e2ba59 1018{
5f10c6b1 1019 int ret = 0;
d3e2ba59 1020 struct lttng_viewer_list_sessions session_list;
d3e2ba59 1021 struct lttng_ht_iter iter;
d3e2ba59 1022 struct relay_session *session;
7591bab1
MD
1023 struct lttng_viewer_session *send_session_buf = NULL;
1024 uint32_t buf_count = SESSION_BUF_DEFAULT_COUNT;
1025 uint32_t count = 0;
d3e2ba59
JD
1026
1027 DBG("List sessions received");
1028
ac497a37 1029 send_session_buf = (lttng_viewer_session *) zmalloc(SESSION_BUF_DEFAULT_COUNT * sizeof(*send_session_buf));
7591bab1
MD
1030 if (!send_session_buf) {
1031 return -1;
d3e2ba59
JD
1032 }
1033
7591bab1
MD
1034 rcu_read_lock();
1035 cds_lfht_for_each_entry(sessions_ht->ht, &iter.iter, session,
2f8f53af 1036 session_n.node) {
7591bab1 1037 struct lttng_viewer_session *send_session;
d3e2ba59 1038
eea7556c
MD
1039 health_code_update();
1040
d995f382 1041 pthread_mutex_lock(&session->lock);
7e0a4379
JR
1042 if (session->connection_closed) {
1043 /* Skip closed session */
d995f382
JG
1044 goto next_session;
1045 }
7e0a4379 1046
7591bab1
MD
1047 if (count >= buf_count) {
1048 struct lttng_viewer_session *newbuf;
1049 uint32_t new_buf_count = buf_count << 1;
eea7556c 1050
ac497a37 1051 newbuf = (lttng_viewer_session *) realloc(send_session_buf,
7591bab1
MD
1052 new_buf_count * sizeof(*send_session_buf));
1053 if (!newbuf) {
1054 ret = -1;
d995f382 1055 goto break_loop;
7591bab1
MD
1056 }
1057 send_session_buf = newbuf;
1058 buf_count = new_buf_count;
6763619c 1059 }
7591bab1 1060 send_session = &send_session_buf[count];
bfc3fb17
MD
1061 if (lttng_strncpy(send_session->session_name,
1062 session->session_name,
1063 sizeof(send_session->session_name))) {
1064 ret = -1;
d995f382 1065 goto break_loop;
bfc3fb17
MD
1066 }
1067 if (lttng_strncpy(send_session->hostname, session->hostname,
1068 sizeof(send_session->hostname))) {
1069 ret = -1;
d995f382 1070 goto break_loop;
bfc3fb17 1071 }
7591bab1
MD
1072 send_session->id = htobe64(session->id);
1073 send_session->live_timer = htobe32(session->live_timer);
1074 if (session->viewer_attached) {
1075 send_session->clients = htobe32(1);
1076 } else {
1077 send_session->clients = htobe32(0);
d227d5bd 1078 }
7591bab1
MD
1079 send_session->streams = htobe32(session->stream_count);
1080 count++;
d995f382
JG
1081 next_session:
1082 pthread_mutex_unlock(&session->lock);
1083 continue;
1084 break_loop:
1085 pthread_mutex_unlock(&session->lock);
1086 break;
7591bab1
MD
1087 }
1088 rcu_read_unlock();
5f10c6b1
JG
1089 if (ret < 0) {
1090 goto end_free;
1091 }
d227d5bd 1092
7591bab1 1093 session_list.sessions_count = htobe32(count);
d227d5bd 1094
7591bab1 1095 health_code_update();
d227d5bd 1096
7591bab1
MD
1097 ret = send_response(conn->sock, &session_list, sizeof(session_list));
1098 if (ret < 0) {
1099 goto end_free;
d227d5bd 1100 }
d227d5bd 1101
7591bab1 1102 health_code_update();
d227d5bd 1103
7591bab1
MD
1104 ret = send_response(conn->sock, send_session_buf,
1105 count * sizeof(*send_session_buf));
1106 if (ret < 0) {
1107 goto end_free;
d227d5bd 1108 }
7591bab1 1109 health_code_update();
d227d5bd 1110
7591bab1
MD
1111 ret = 0;
1112end_free:
1113 free(send_session_buf);
1114 return ret;
d227d5bd
JD
1115}
1116
80e8027a 1117/*
7591bab1 1118 * Send the viewer the list of current streams.
80e8027a
JD
1119 */
1120static
58eb9381 1121int viewer_get_new_streams(struct relay_connection *conn)
80e8027a
JD
1122{
1123 int ret, send_streams = 0;
7591bab1 1124 uint32_t nb_created = 0, nb_unsent = 0, nb_streams = 0, nb_total = 0;
80e8027a
JD
1125 struct lttng_viewer_new_streams_request request;
1126 struct lttng_viewer_new_streams_response response;
b66a15d1 1127 struct relay_session *session = NULL;
6763619c 1128 uint64_t session_id;
bddf80e4 1129 bool closed = false;
80e8027a 1130
a0377dfe 1131 LTTNG_ASSERT(conn);
80e8027a
JD
1132
1133 DBG("Get new streams received");
1134
80e8027a
JD
1135 health_code_update();
1136
2f8f53af 1137 /* Receive the request from the connected client. */
58eb9381 1138 ret = recv_request(conn->sock, &request, sizeof(request));
2f8f53af 1139 if (ret < 0) {
80e8027a
JD
1140 goto error;
1141 }
6763619c 1142 session_id = be64toh(request.session_id);
80e8027a
JD
1143
1144 health_code_update();
1145
53efb85a
MD
1146 memset(&response, 0, sizeof(response));
1147
7591bab1 1148 session = session_get_by_id(session_id);
2f8f53af 1149 if (!session) {
6763619c 1150 DBG("Relay session %" PRIu64 " not found", session_id);
c4e361a4 1151 response.status = htobe32(LTTNG_VIEWER_NEW_STREAMS_ERR);
80e8027a
JD
1152 goto send_reply;
1153 }
1154
7591bab1 1155 if (!viewer_session_is_attached(conn->viewer_session, session)) {
c4e361a4 1156 response.status = htobe32(LTTNG_VIEWER_NEW_STREAMS_ERR);
80e8027a
JD
1157 goto send_reply;
1158 }
1159
c876d657
JR
1160 /*
1161 * For any new stream, create it with LTTNG_VIEWER_SEEK_BEGINNING since
1162 * that at this point the client is already attached to the session.Aany
1163 * initial stream will have been created with the seek type at attach
1164 * time (for now most readers use the LTTNG_VIEWER_SEEK_LAST on attach).
1165 * Otherwise any event happening in a new stream between the attach and
1166 * a call to viewer_get_new_streams will be "lost" (never received) from
1167 * the viewer's point of view.
1168 */
c06fdd95 1169 pthread_mutex_lock(&session->lock);
8cd15f6a
MD
1170 /*
1171 * If a session rotation is ongoing, do not attempt to open any
1172 * stream, because the chunk can be in an intermediate state
1173 * due to directory renaming.
1174 */
1175 if (session->ongoing_rotation) {
1176 DBG("Relay session %" PRIu64 " rotation ongoing", session_id);
1177 response.status = htobe32(LTTNG_VIEWER_NEW_STREAMS_NO_NEW);
1178 goto send_reply_unlock;
1179 }
b66a15d1 1180 ret = make_viewer_streams(session,
9edaf114 1181 conn->viewer_session,
c876d657 1182 LTTNG_VIEWER_SEEK_BEGINNING, &nb_total, &nb_unsent,
bddf80e4 1183 &nb_created, &closed);
2f8f53af 1184 if (ret < 0) {
b66a15d1 1185 goto error_unlock_session;
2f8f53af 1186 }
3d0bbd40
JG
1187 send_streams = 1;
1188 response.status = htobe32(LTTNG_VIEWER_NEW_STREAMS_OK);
b66a15d1 1189
2f8f53af
DG
1190 /* Only send back the newly created streams with the unsent ones. */
1191 nb_streams = nb_created + nb_unsent;
80e8027a
JD
1192 response.streams_count = htobe32(nb_streams);
1193
4479f682 1194 /*
2229a09c
MD
1195 * If the session is closed, HUP when there are no more streams
1196 * with data.
4479f682 1197 */
bddf80e4 1198 if (closed && nb_total == 0) {
4479f682 1199 send_streams = 0;
bddf80e4 1200 response.streams_count = 0;
4479f682 1201 response.status = htobe32(LTTNG_VIEWER_NEW_STREAMS_HUP);
3d0bbd40 1202 goto send_reply_unlock;
4479f682 1203 }
3d0bbd40
JG
1204send_reply_unlock:
1205 pthread_mutex_unlock(&session->lock);
4479f682 1206
80e8027a
JD
1207send_reply:
1208 health_code_update();
58eb9381 1209 ret = send_response(conn->sock, &response, sizeof(response));
80e8027a 1210 if (ret < 0) {
7591bab1 1211 goto end_put_session;
80e8027a
JD
1212 }
1213 health_code_update();
1214
1215 /*
7591bab1
MD
1216 * Unknown or empty session, just return gracefully, the viewer
1217 * knows what is happening.
80e8027a
JD
1218 */
1219 if (!send_streams || !nb_streams) {
1220 ret = 0;
7591bab1 1221 goto end_put_session;
80e8027a
JD
1222 }
1223
2f8f53af 1224 /*
7591bab1
MD
1225 * Send stream and *DON'T* ignore the sent flag so every viewer
1226 * streams that were not sent from that point will be sent to
1227 * the viewer.
2f8f53af 1228 */
c06fdd95 1229 ret = send_viewer_streams(conn->sock, session_id, 0);
2f8f53af 1230 if (ret < 0) {
7591bab1 1231 goto end_put_session;
80e8027a
JD
1232 }
1233
7591bab1
MD
1234end_put_session:
1235 if (session) {
1236 session_put(session);
1237 }
80e8027a
JD
1238error:
1239 return ret;
b66a15d1
JG
1240error_unlock_session:
1241 pthread_mutex_unlock(&session->lock);
1242 session_put(session);
1243 return ret;
80e8027a
JD
1244}
1245
d3e2ba59
JD
1246/*
1247 * Send the viewer the list of current sessions.
1248 */
1249static
58eb9381 1250int viewer_attach_session(struct relay_connection *conn)
d3e2ba59 1251{
2f8f53af
DG
1252 int send_streams = 0;
1253 ssize_t ret;
80e8027a 1254 uint32_t nb_streams = 0;
2f8f53af 1255 enum lttng_viewer_seek seek_type;
d3e2ba59
JD
1256 struct lttng_viewer_attach_session_request request;
1257 struct lttng_viewer_attach_session_response response;
7591bab1 1258 struct relay_session *session = NULL;
dbd6665b 1259 enum lttng_viewer_attach_return_code viewer_attach_status;
bddf80e4 1260 bool closed = false;
c06fdd95 1261 uint64_t session_id;
d3e2ba59 1262
a0377dfe 1263 LTTNG_ASSERT(conn);
d3e2ba59 1264
eea7556c
MD
1265 health_code_update();
1266
2f8f53af 1267 /* Receive the request from the connected client. */
58eb9381 1268 ret = recv_request(conn->sock, &request, sizeof(request));
2f8f53af 1269 if (ret < 0) {
d3e2ba59
JD
1270 goto error;
1271 }
1272
c06fdd95 1273 session_id = be64toh(request.session_id);
eea7556c
MD
1274 health_code_update();
1275
53efb85a
MD
1276 memset(&response, 0, sizeof(response));
1277
c3b7390b
JD
1278 if (!conn->viewer_session) {
1279 DBG("Client trying to attach before creating a live viewer session");
1280 response.status = htobe32(LTTNG_VIEWER_ATTACH_NO_SESSION);
1281 goto send_reply;
1282 }
1283
c06fdd95 1284 session = session_get_by_id(session_id);
2f8f53af 1285 if (!session) {
c06fdd95 1286 DBG("Relay session %" PRIu64 " not found", session_id);
c4e361a4 1287 response.status = htobe32(LTTNG_VIEWER_ATTACH_UNK);
d3e2ba59
JD
1288 goto send_reply;
1289 }
c06fdd95 1290 DBG("Attach session ID %" PRIu64 " received", session_id);
d3e2ba59 1291
c06fdd95 1292 pthread_mutex_lock(&session->lock);
7591bab1 1293 if (session->live_timer == 0) {
d3e2ba59 1294 DBG("Not live session");
c4e361a4 1295 response.status = htobe32(LTTNG_VIEWER_ATTACH_NOT_LIVE);
d3e2ba59 1296 goto send_reply;
7591bab1
MD
1297 }
1298
1299 send_streams = 1;
dbd6665b
JG
1300 viewer_attach_status = viewer_session_attach(conn->viewer_session,
1301 session);
1302 if (viewer_attach_status != LTTNG_VIEWER_ATTACH_OK) {
1303 response.status = htobe32(viewer_attach_status);
7591bab1 1304 goto send_reply;
d3e2ba59
JD
1305 }
1306
1307 switch (be32toh(request.seek)) {
c4e361a4
JD
1308 case LTTNG_VIEWER_SEEK_BEGINNING:
1309 case LTTNG_VIEWER_SEEK_LAST:
7591bab1 1310 response.status = htobe32(LTTNG_VIEWER_ATTACH_OK);
ac497a37 1311 seek_type = (lttng_viewer_seek) be32toh(request.seek);
d3e2ba59
JD
1312 break;
1313 default:
1314 ERR("Wrong seek parameter");
c4e361a4 1315 response.status = htobe32(LTTNG_VIEWER_ATTACH_SEEK_ERR);
d3e2ba59
JD
1316 send_streams = 0;
1317 goto send_reply;
1318 }
1319
8cd15f6a
MD
1320 /*
1321 * If a session rotation is ongoing, do not attempt to open any
1322 * stream, because the chunk can be in an intermediate state
1323 * due to directory renaming.
1324 */
1325 if (session->ongoing_rotation) {
1326 DBG("Relay session %" PRIu64 " rotation ongoing", session_id);
1327 send_streams = 0;
1328 goto send_reply;
1329 }
1330
b66a15d1 1331 ret = make_viewer_streams(session,
9edaf114 1332 conn->viewer_session, seek_type,
b66a15d1 1333 &nb_streams, NULL, NULL, &closed);
2f8f53af 1334 if (ret < 0) {
7591bab1 1335 goto end_put_session;
d3e2ba59 1336 }
c06fdd95
JG
1337 pthread_mutex_unlock(&session->lock);
1338 session_put(session);
1339 session = NULL;
1340
1341 response.streams_count = htobe32(nb_streams);
bddf80e4
MD
1342 /*
1343 * If the session is closed when the viewer is attaching, it
1344 * means some of the streams may have been concurrently removed,
1345 * so we don't allow the viewer to attach, even if there are
1346 * streams available.
1347 */
1348 if (closed) {
1349 send_streams = 0;
1350 response.streams_count = 0;
06079f15 1351 response.status = htobe32(LTTNG_VIEWER_ATTACH_UNK);
bddf80e4
MD
1352 goto send_reply;
1353 }
1354
d3e2ba59 1355send_reply:
eea7556c 1356 health_code_update();
58eb9381 1357 ret = send_response(conn->sock, &response, sizeof(response));
d3e2ba59 1358 if (ret < 0) {
7591bab1 1359 goto end_put_session;
d3e2ba59 1360 }
eea7556c 1361 health_code_update();
d3e2ba59
JD
1362
1363 /*
7591bab1
MD
1364 * Unknown or empty session, just return gracefully, the viewer
1365 * knows what is happening.
d3e2ba59 1366 */
157df586 1367 if (!send_streams || !nb_streams) {
d3e2ba59 1368 ret = 0;
7591bab1 1369 goto end_put_session;
d3e2ba59
JD
1370 }
1371
2f8f53af 1372 /* Send stream and ignore the sent flag. */
c06fdd95 1373 ret = send_viewer_streams(conn->sock, session_id, 1);
2f8f53af 1374 if (ret < 0) {
7591bab1 1375 goto end_put_session;
d3e2ba59 1376 }
d3e2ba59 1377
7591bab1
MD
1378end_put_session:
1379 if (session) {
c06fdd95 1380 pthread_mutex_unlock(&session->lock);
7591bab1
MD
1381 session_put(session);
1382 }
4a9daf17
JD
1383error:
1384 return ret;
1385}
1386
878c34cf
DG
1387/*
1388 * Open the index file if needed for the given vstream.
1389 *
f8f3885c
MD
1390 * If an index file is successfully opened, the vstream will set it as its
1391 * current index file.
878c34cf
DG
1392 *
1393 * Return 0 on success, a negative value on error (-ENOENT if not ready yet).
7591bab1
MD
1394 *
1395 * Called with rstream lock held.
878c34cf
DG
1396 */
1397static int try_open_index(struct relay_viewer_stream *vstream,
1398 struct relay_stream *rstream)
1399{
1400 int ret = 0;
ebb29c10
JG
1401 const uint32_t connection_major = rstream->trace->session->major;
1402 const uint32_t connection_minor = rstream->trace->session->minor;
3ff5c5db 1403 enum lttng_trace_chunk_status chunk_status;
878c34cf 1404
f8f3885c 1405 if (vstream->index_file) {
878c34cf
DG
1406 goto end;
1407 }
1408
1409 /*
7591bab1 1410 * First time, we open the index file and at least one index is ready.
878c34cf 1411 */
80516611
JG
1412 if (rstream->index_received_seqcount == 0 ||
1413 !vstream->stream_file.trace_chunk) {
878c34cf
DG
1414 ret = -ENOENT;
1415 goto end;
1416 }
80516611 1417
3ff5c5db 1418 chunk_status = lttng_index_file_create_from_trace_chunk_read_only(
b66a15d1 1419 vstream->stream_file.trace_chunk, rstream->path_name,
ebb29c10
JG
1420 rstream->channel_name, rstream->tracefile_size,
1421 vstream->current_tracefile_id,
1422 lttng_to_index_major(connection_major, connection_minor),
3ff5c5db
MD
1423 lttng_to_index_minor(connection_major, connection_minor),
1424 true, &vstream->index_file);
1425 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
1426 if (chunk_status == LTTNG_TRACE_CHUNK_STATUS_NO_FILE) {
1427 ret = -ENOENT;
1428 } else {
1429 ret = -1;
1430 }
878c34cf
DG
1431 }
1432
1433end:
1434 return ret;
1435}
1436
1437/*
7591bab1
MD
1438 * Check the status of the index for the given stream. This function
1439 * updates the index structure if needed and can put (close) the vstream
1440 * in the HUP situation.
1441 *
1442 * Return 0 means that we can proceed with the index. A value of 1 means
1443 * that the index has been updated and is ready to be sent to the
1444 * client. A negative value indicates an error that can't be handled.
878c34cf 1445 *
7591bab1 1446 * Called with rstream lock held.
878c34cf
DG
1447 */
1448static int check_index_status(struct relay_viewer_stream *vstream,
1449 struct relay_stream *rstream, struct ctf_trace *trace,
1450 struct lttng_viewer_index *index)
1451{
1452 int ret;
1453
68c40154
MD
1454 DBG("Check index status: index_received_seqcount %" PRIu64 " "
1455 "index_sent_seqcount %" PRIu64 " "
1456 "for stream %" PRIu64,
1457 rstream->index_received_seqcount,
1458 vstream->index_sent_seqcount,
1459 vstream->stream->stream_handle);
797bc362 1460 if ((trace->session->connection_closed || rstream->closed)
a44ca2ca
MD
1461 && rstream->index_received_seqcount
1462 == vstream->index_sent_seqcount) {
797bc362
MD
1463 /*
1464 * Last index sent and session connection or relay
1465 * stream are closed.
1466 */
7591bab1
MD
1467 index->status = htobe32(LTTNG_VIEWER_INDEX_HUP);
1468 goto hup;
1469 } else if (rstream->beacon_ts_end != -1ULL &&
b0d240a2
MD
1470 (rstream->index_received_seqcount == 0 ||
1471 (vstream->index_sent_seqcount != 0 &&
a44ca2ca 1472 rstream->index_received_seqcount
b0d240a2 1473 <= vstream->index_sent_seqcount))) {
7591bab1
MD
1474 /*
1475 * We've received a synchronization beacon and the last index
1476 * available has been sent, the index for now is inactive.
1477 *
1478 * In this case, we have received a beacon which allows us to
1479 * inform the client of a time interval during which we can
1480 * guarantee that there are no events to read (and never will
1481 * be).
b0d240a2
MD
1482 *
1483 * The sent seqcount can grow higher than receive seqcount on
1484 * clear because the rotation performed by clear will push
1485 * the index_sent_seqcount ahead (see
1486 * viewer_stream_sync_tracefile_array_tail) and skip over
1487 * packet sequence numbers.
7591bab1
MD
1488 */
1489 index->status = htobe32(LTTNG_VIEWER_INDEX_INACTIVE);
1490 index->timestamp_end = htobe64(rstream->beacon_ts_end);
1491 index->stream_id = htobe64(rstream->ctf_stream_id);
68c40154
MD
1492 DBG("Check index status: inactive with beacon, for stream %" PRIu64,
1493 vstream->stream->stream_handle);
7591bab1 1494 goto index_ready;
b0d240a2
MD
1495 } else if (rstream->index_received_seqcount == 0 ||
1496 (vstream->index_sent_seqcount != 0 &&
1497 rstream->index_received_seqcount
1498 <= vstream->index_sent_seqcount)) {
7591bab1 1499 /*
b0d240a2 1500 * This checks whether received <= sent seqcount. In
a44ca2ca
MD
1501 * this case, we have not received a beacon. Therefore,
1502 * we can only ask the client to retry later.
b0d240a2
MD
1503 *
1504 * The sent seqcount can grow higher than receive seqcount on
1505 * clear because the rotation performed by clear will push
1506 * the index_sent_seqcount ahead (see
1507 * viewer_stream_sync_tracefile_array_tail) and skip over
1508 * packet sequence numbers.
7591bab1
MD
1509 */
1510 index->status = htobe32(LTTNG_VIEWER_INDEX_RETRY);
68c40154
MD
1511 DBG("Check index status: retry for stream %" PRIu64,
1512 vstream->stream->stream_handle);
7591bab1 1513 goto index_ready;
a44ca2ca
MD
1514 } else if (!tracefile_array_seq_in_file(rstream->tfa,
1515 vstream->current_tracefile_id,
1516 vstream->index_sent_seqcount)) {
7591bab1 1517 /*
a44ca2ca
MD
1518 * The next index we want to send cannot be read either
1519 * because we need to perform a rotation, or due to
1520 * the producer having overwritten its trace file.
7591bab1 1521 */
a44ca2ca 1522 DBG("Viewer stream %" PRIu64 " rotation",
7591bab1
MD
1523 vstream->stream->stream_handle);
1524 ret = viewer_stream_rotate(vstream);
b0d240a2 1525 if (ret == 1) {
7591bab1
MD
1526 /* EOF across entire stream. */
1527 index->status = htobe32(LTTNG_VIEWER_INDEX_HUP);
1528 goto hup;
1529 }
7591bab1 1530 /*
a44ca2ca
MD
1531 * If we have been pushed due to overwrite, it
1532 * necessarily means there is data that can be read in
1533 * the stream. If we rotated because we reached the end
1534 * of a tracefile, it means the following tracefile
1535 * needs to contain at least one index, else we would
1536 * have already returned LTTNG_VIEWER_INDEX_RETRY to the
1537 * viewer. The updated index_sent_seqcount needs to
1538 * point to a readable index entry now.
1539 *
1540 * In the case where we "rotate" on a single file, we
1541 * can end up in a case where the requested index is
1542 * still unavailable.
7591bab1 1543 */
a44ca2ca
MD
1544 if (rstream->tracefile_count == 1 &&
1545 !tracefile_array_seq_in_file(
1546 rstream->tfa,
1547 vstream->current_tracefile_id,
1548 vstream->index_sent_seqcount)) {
1549 index->status = htobe32(LTTNG_VIEWER_INDEX_RETRY);
68c40154
MD
1550 DBG("Check index status: retry: "
1551 "tracefile array sequence number %" PRIu64
1552 " not in file for stream %" PRIu64,
1553 vstream->index_sent_seqcount,
1554 vstream->stream->stream_handle);
a44ca2ca 1555 goto index_ready;
878c34cf 1556 }
a0377dfe 1557 LTTNG_ASSERT(tracefile_array_seq_in_file(rstream->tfa,
a44ca2ca
MD
1558 vstream->current_tracefile_id,
1559 vstream->index_sent_seqcount));
878c34cf 1560 }
a44ca2ca
MD
1561 /* ret == 0 means successful so we continue. */
1562 ret = 0;
878c34cf
DG
1563 return ret;
1564
1565hup:
7591bab1 1566 viewer_stream_put(vstream);
878c34cf
DG
1567index_ready:
1568 return 1;
1569}
1570
80516611
JG
1571static
1572void viewer_stream_rotate_to_trace_chunk(struct relay_viewer_stream *vstream,
1573 struct lttng_trace_chunk *new_trace_chunk)
1574{
1575 lttng_trace_chunk_put(vstream->stream_file.trace_chunk);
1576
1577 if (new_trace_chunk) {
1578 const bool acquired_reference = lttng_trace_chunk_get(
1579 new_trace_chunk);
1580
a0377dfe 1581 LTTNG_ASSERT(acquired_reference);
80516611
JG
1582 }
1583
1584 vstream->stream_file.trace_chunk = new_trace_chunk;
1585 viewer_stream_sync_tracefile_array_tail(vstream);
1586 viewer_stream_close_files(vstream);
1587}
1588
d3e2ba59
JD
1589/*
1590 * Send the next index for a stream.
1591 *
1592 * Return 0 on success or else a negative value.
1593 */
1594static
58eb9381 1595int viewer_get_next_index(struct relay_connection *conn)
d3e2ba59
JD
1596{
1597 int ret;
1598 struct lttng_viewer_get_next_index request_index;
1599 struct lttng_viewer_index viewer_index;
50adc264 1600 struct ctf_packet_index packet_index;
7591bab1
MD
1601 struct relay_viewer_stream *vstream = NULL;
1602 struct relay_stream *rstream = NULL;
1603 struct ctf_trace *ctf_trace = NULL;
1604 struct relay_viewer_stream *metadata_viewer_stream = NULL;
d3e2ba59 1605
a0377dfe 1606 LTTNG_ASSERT(conn);
d3e2ba59
JD
1607
1608 DBG("Viewer get next index");
1609
7591bab1 1610 memset(&viewer_index, 0, sizeof(viewer_index));
eea7556c 1611 health_code_update();
2f8f53af 1612
58eb9381 1613 ret = recv_request(conn->sock, &request_index, sizeof(request_index));
2f8f53af 1614 if (ret < 0) {
d3e2ba59
JD
1615 goto end;
1616 }
eea7556c 1617 health_code_update();
d3e2ba59 1618
7591bab1 1619 vstream = viewer_stream_get_by_id(be64toh(request_index.stream_id));
6763619c 1620 if (!vstream) {
a44ca2ca 1621 DBG("Client requested index of unknown stream id %" PRIu64,
9b9f9f94 1622 (uint64_t) be64toh(request_index.stream_id));
f1883937
MD
1623 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_ERR);
1624 goto send_reply;
2a174661
DG
1625 }
1626
7591bab1
MD
1627 /* Use back. ref. Protected by refcounts. */
1628 rstream = vstream->stream;
1629 ctf_trace = rstream->trace;
d3e2ba59 1630
7591bab1
MD
1631 /* metadata_viewer_stream may be NULL. */
1632 metadata_viewer_stream =
1633 ctf_trace_get_viewer_metadata_stream(ctf_trace);
2a174661 1634
7591bab1 1635 pthread_mutex_lock(&rstream->lock);
d3e2ba59
JD
1636
1637 /*
1638 * The viewer should not ask for index on metadata stream.
1639 */
7591bab1 1640 if (rstream->is_metadata) {
c4e361a4 1641 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_HUP);
d3e2ba59
JD
1642 goto send_reply;
1643 }
1644
b0d240a2
MD
1645 if (rstream->ongoing_rotation.is_set) {
1646 /* Rotation is ongoing, try again later. */
1647 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_RETRY);
1648 goto send_reply;
1649 }
1650
1651 if (rstream->trace->session->ongoing_rotation) {
1652 /* Rotation is ongoing, try again later. */
1653 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_RETRY);
1654 goto send_reply;
1655 }
1656
80516611
JG
1657 /*
1658 * Transition the viewer session into the newest trace chunk available.
1659 */
1660 if (!lttng_trace_chunk_ids_equal(
ad8bec24
JG
1661 conn->viewer_session->current_trace_chunk,
1662 rstream->trace_chunk)) {
9a9c8637 1663 DBG("Relay stream and viewer chunk ids differ");
b0d240a2 1664
ad8bec24
JG
1665 ret = viewer_session_set_trace_chunk_copy(
1666 conn->viewer_session,
1667 rstream->trace_chunk);
1668 if (ret) {
b0d240a2
MD
1669 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_ERR);
1670 goto send_reply;
1671 }
b0d240a2 1672 }
b0d240a2 1673
80516611
JG
1674 /*
1675 * Transition the viewer stream into the latest trace chunk available.
1676 *
1677 * Note that the stream must _not_ rotate in one precise condition:
1678 * the relay stream has rotated to a NULL trace chunk and the viewer
1679 * stream is consuming the trace chunk that was active just before
1680 * that rotation to NULL.
1681 *
1682 * This allows clients to consume all the packets of a trace chunk
1683 * after a session's destruction.
1684 */
d8f644d9 1685 if (!lttng_trace_chunk_ids_equal(conn->viewer_session->current_trace_chunk, vstream->stream_file.trace_chunk) &&
80516611 1686 !(rstream->completed_rotation_count == vstream->last_seen_rotation_count + 1 && !rstream->trace_chunk)) {
d8f644d9 1687 DBG("Viewer session and viewer stream chunk IDs differ: "
b0d240a2
MD
1688 "vsession chunk %p vstream chunk %p",
1689 conn->viewer_session->current_trace_chunk,
1690 vstream->stream_file.trace_chunk);
80516611
JG
1691 viewer_stream_rotate_to_trace_chunk(vstream,
1692 conn->viewer_session->current_trace_chunk);
1693 vstream->last_seen_rotation_count =
1694 rstream->completed_rotation_count;
d3e2ba59
JD
1695 }
1696
878c34cf 1697 ret = check_index_status(vstream, rstream, ctf_trace, &viewer_index);
878c34cf 1698 if (ret < 0) {
7591bab1 1699 goto error_put;
878c34cf
DG
1700 } else if (ret == 1) {
1701 /*
7591bab1
MD
1702 * We have no index to send and check_index_status has populated
1703 * viewer_index's status.
878c34cf 1704 */
d3e2ba59
JD
1705 goto send_reply;
1706 }
7591bab1 1707 /* At this point, ret is 0 thus we will be able to read the index. */
a0377dfe 1708 LTTNG_ASSERT(!ret);
d3e2ba59 1709
b0d240a2
MD
1710 /* Try to open an index if one is needed for that stream. */
1711 ret = try_open_index(vstream, rstream);
1712 if (ret == -ENOENT) {
1713 if (rstream->closed) {
1714 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_HUP);
1715 goto send_reply;
1716 } else {
1717 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_RETRY);
1718 goto send_reply;
1719 }
1720 }
1721 if (ret < 0) {
1722 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_ERR);
1723 goto send_reply;
1724 }
1725
7591bab1
MD
1726 /*
1727 * vstream->stream_fd may be NULL if it has been closed by
1728 * tracefile rotation, or if we are at the beginning of the
1729 * stream. We open the data stream file here to protect against
1730 * overwrite caused by tracefile rotation (in association with
1731 * unlink performed before overwrite).
1732 */
8bb66c3c 1733 if (!vstream->stream_file.handle) {
ebb29c10
JG
1734 char file_path[LTTNG_PATH_MAX];
1735 enum lttng_trace_chunk_status status;
8bb66c3c 1736 struct fs_handle *fs_handle;
ebb29c10
JG
1737
1738 ret = utils_stream_file_path(rstream->path_name,
1739 rstream->channel_name, rstream->tracefile_size,
1740 vstream->current_tracefile_id, NULL, file_path,
1741 sizeof(file_path));
7591bab1
MD
1742 if (ret < 0) {
1743 goto error_put;
1744 }
ebb29c10 1745
3ff5c5db
MD
1746 /*
1747 * It is possible the the file we are trying to open is
1748 * missing if the stream has been closed (application exits with
1749 * per-pid buffers) and a clear command has been performed.
1750 */
8bb66c3c 1751 status = lttng_trace_chunk_open_fs_handle(
ebb29c10 1752 vstream->stream_file.trace_chunk,
8bb66c3c 1753 file_path, O_RDONLY, 0, &fs_handle, true);
ebb29c10 1754 if (status != LTTNG_TRACE_CHUNK_STATUS_OK) {
b0d240a2
MD
1755 if (status == LTTNG_TRACE_CHUNK_STATUS_NO_FILE &&
1756 rstream->closed) {
1757 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_HUP);
1758 goto send_reply;
1759 }
ebb29c10 1760 PERROR("Failed to open trace file for viewer stream");
7591bab1
MD
1761 goto error_put;
1762 }
8bb66c3c 1763 vstream->stream_file.handle = fs_handle;
d3e2ba59
JD
1764 }
1765
f04a971b 1766 ret = check_new_streams(conn);
4a9daf17 1767 if (ret < 0) {
7591bab1
MD
1768 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_ERR);
1769 goto send_reply;
4a9daf17
JD
1770 } else if (ret == 1) {
1771 viewer_index.flags |= LTTNG_VIEWER_FLAG_NEW_STREAM;
1772 }
1773
f8f3885c
MD
1774 ret = lttng_index_file_read(vstream->index_file, &packet_index);
1775 if (ret) {
8bb66c3c 1776 ERR("Relay error reading index file");
7591bab1 1777 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_ERR);
6b6b9a5a 1778 goto send_reply;
d3e2ba59 1779 } else {
c4e361a4 1780 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_OK);
a44ca2ca 1781 vstream->index_sent_seqcount++;
d3e2ba59
JD
1782 }
1783
1784 /*
1785 * Indexes are stored in big endian, no need to switch before sending.
1786 */
7591bab1
MD
1787 DBG("Sending viewer index for stream %" PRIu64 " offset %" PRIu64,
1788 rstream->stream_handle,
9b9f9f94 1789 (uint64_t) be64toh(packet_index.offset));
d3e2ba59
JD
1790 viewer_index.offset = packet_index.offset;
1791 viewer_index.packet_size = packet_index.packet_size;
1792 viewer_index.content_size = packet_index.content_size;
1793 viewer_index.timestamp_begin = packet_index.timestamp_begin;
1794 viewer_index.timestamp_end = packet_index.timestamp_end;
1795 viewer_index.events_discarded = packet_index.events_discarded;
1796 viewer_index.stream_id = packet_index.stream_id;
1797
1798send_reply:
f1883937
MD
1799 if (rstream) {
1800 pthread_mutex_unlock(&rstream->lock);
1801 }
7591bab1
MD
1802
1803 if (metadata_viewer_stream) {
1804 pthread_mutex_lock(&metadata_viewer_stream->stream->lock);
1805 DBG("get next index metadata check: recv %" PRIu64
1806 " sent %" PRIu64,
1807 metadata_viewer_stream->stream->metadata_received,
1808 metadata_viewer_stream->metadata_sent);
1809 if (!metadata_viewer_stream->stream->metadata_received ||
1810 metadata_viewer_stream->stream->metadata_received >
1811 metadata_viewer_stream->metadata_sent) {
1812 viewer_index.flags |= LTTNG_VIEWER_FLAG_NEW_METADATA;
1813 }
1814 pthread_mutex_unlock(&metadata_viewer_stream->stream->lock);
1815 }
1816
d3e2ba59 1817 viewer_index.flags = htobe32(viewer_index.flags);
eea7556c 1818 health_code_update();
2f8f53af 1819
58eb9381 1820 ret = send_response(conn->sock, &viewer_index, sizeof(viewer_index));
d3e2ba59 1821 if (ret < 0) {
7591bab1 1822 goto end;
d3e2ba59 1823 }
eea7556c 1824 health_code_update();
d3e2ba59 1825
9237e6a1
MD
1826 if (vstream) {
1827 DBG("Index %" PRIu64 " for stream %" PRIu64 " sent",
a44ca2ca 1828 vstream->index_sent_seqcount,
9237e6a1
MD
1829 vstream->stream->stream_handle);
1830 }
d3e2ba59 1831end:
7591bab1
MD
1832 if (metadata_viewer_stream) {
1833 viewer_stream_put(metadata_viewer_stream);
1834 }
1835 if (vstream) {
1836 viewer_stream_put(vstream);
1837 }
1838 return ret;
1839
1840error_put:
1841 pthread_mutex_unlock(&rstream->lock);
1842 if (metadata_viewer_stream) {
1843 viewer_stream_put(metadata_viewer_stream);
1844 }
1845 viewer_stream_put(vstream);
d3e2ba59
JD
1846 return ret;
1847}
1848
1849/*
1850 * Send the next index for a stream
1851 *
1852 * Return 0 on success or else a negative value.
1853 */
1854static
58eb9381 1855int viewer_get_packet(struct relay_connection *conn)
d3e2ba59 1856{
b6025e94 1857 int ret;
a5df8828 1858 off_t lseek_ret;
553b2adb 1859 char *reply = NULL;
d3e2ba59 1860 struct lttng_viewer_get_packet get_packet_info;
553b2adb 1861 struct lttng_viewer_trace_packet reply_header;
7591bab1 1862 struct relay_viewer_stream *vstream = NULL;
553b2adb 1863 uint32_t reply_size = sizeof(reply_header);
b6025e94
JR
1864 uint32_t packet_data_len = 0;
1865 ssize_t read_len;
8bb66c3c 1866 uint64_t stream_id;
d3e2ba59
JD
1867
1868 DBG2("Relay get data packet");
1869
eea7556c 1870 health_code_update();
2f8f53af 1871
7591bab1
MD
1872 ret = recv_request(conn->sock, &get_packet_info,
1873 sizeof(get_packet_info));
2f8f53af 1874 if (ret < 0) {
d3e2ba59
JD
1875 goto end;
1876 }
eea7556c 1877 health_code_update();
d3e2ba59 1878
0233a6a5 1879 /* From this point on, the error label can be reached. */
553b2adb 1880 memset(&reply_header, 0, sizeof(reply_header));
8bb66c3c 1881 stream_id = (uint64_t) be64toh(get_packet_info.stream_id);
0233a6a5 1882
8bb66c3c 1883 vstream = viewer_stream_get_by_id(stream_id);
7591bab1 1884 if (!vstream) {
a44ca2ca 1885 DBG("Client requested packet of unknown stream id %" PRIu64,
8bb66c3c 1886 stream_id);
553b2adb
JG
1887 reply_header.status = htobe32(LTTNG_VIEWER_GET_PACKET_ERR);
1888 goto send_reply_nolock;
b6025e94
JR
1889 } else {
1890 packet_data_len = be32toh(get_packet_info.len);
553b2adb 1891 reply_size += packet_data_len;
d3e2ba59 1892 }
2a174661 1893
ac497a37 1894 reply = (char *) zmalloc(reply_size);
553b2adb
JG
1895 if (!reply) {
1896 PERROR("packet reply zmalloc");
1897 reply_size = sizeof(reply_header);
d3e2ba59
JD
1898 goto error;
1899 }
1900
b6025e94 1901 pthread_mutex_lock(&vstream->stream->lock);
8bb66c3c 1902 lseek_ret = fs_handle_seek(vstream->stream_file.handle,
ebb29c10 1903 be64toh(get_packet_info.offset), SEEK_SET);
a5df8828 1904 if (lseek_ret < 0) {
8bb66c3c
JG
1905 PERROR("Failed to seek file system handle of viewer stream %" PRIu64
1906 " to offset %" PRIu64,
1907 stream_id,
ebb29c10 1908 (uint64_t) be64toh(get_packet_info.offset));
7591bab1 1909 goto error;
d3e2ba59 1910 }
8bb66c3c 1911 read_len = fs_handle_read(vstream->stream_file.handle,
ebb29c10 1912 reply + sizeof(reply_header), packet_data_len);
b6025e94 1913 if (read_len < packet_data_len) {
8bb66c3c
JG
1914 PERROR("Failed to read from file system handle of viewer stream id %" PRIu64
1915 ", offset: %" PRIu64,
1916 stream_id,
9b9f9f94 1917 (uint64_t) be64toh(get_packet_info.offset));
7591bab1 1918 goto error;
d3e2ba59 1919 }
553b2adb
JG
1920 reply_header.status = htobe32(LTTNG_VIEWER_GET_PACKET_OK);
1921 reply_header.len = htobe32(packet_data_len);
d3e2ba59
JD
1922 goto send_reply;
1923
1924error:
f28ecb10
JG
1925 /* No payload to send on error. */
1926 reply_size = sizeof(reply_header);
553b2adb 1927 reply_header.status = htobe32(LTTNG_VIEWER_GET_PACKET_ERR);
d3e2ba59
JD
1928
1929send_reply:
7591bab1
MD
1930 if (vstream) {
1931 pthread_mutex_unlock(&vstream->stream->lock);
1932 }
1933send_reply_nolock:
eea7556c
MD
1934
1935 health_code_update();
2f8f53af 1936
553b2adb
JG
1937 if (reply) {
1938 memcpy(reply, &reply_header, sizeof(reply_header));
1939 ret = send_response(conn->sock, reply, reply_size);
1940 } else {
1941 /* No reply to send. */
1942 ret = send_response(conn->sock, &reply_header,
1943 reply_size);
1944 }
1945
b6025e94 1946 health_code_update();
d3e2ba59 1947 if (ret < 0) {
b6025e94 1948 PERROR("sendmsg of packet data failed");
7591bab1 1949 goto end_free;
d3e2ba59 1950 }
d3e2ba59 1951
8bb66c3c 1952 DBG("Sent %u bytes for stream %" PRIu64, reply_size, stream_id);
d3e2ba59 1953
7591bab1 1954end_free:
553b2adb 1955 free(reply);
d3e2ba59 1956end:
7591bab1
MD
1957 if (vstream) {
1958 viewer_stream_put(vstream);
1959 }
d3e2ba59
JD
1960 return ret;
1961}
1962
1963/*
1964 * Send the session's metadata
1965 *
1966 * Return 0 on success else a negative value.
1967 */
1968static
58eb9381 1969int viewer_get_metadata(struct relay_connection *conn)
d3e2ba59
JD
1970{
1971 int ret = 0;
8bb66c3c 1972 int fd = -1;
d3e2ba59
JD
1973 ssize_t read_len;
1974 uint64_t len = 0;
1975 char *data = NULL;
1976 struct lttng_viewer_get_metadata request;
1977 struct lttng_viewer_metadata_packet reply;
7591bab1 1978 struct relay_viewer_stream *vstream = NULL;
d3e2ba59 1979
a0377dfe 1980 LTTNG_ASSERT(conn);
d3e2ba59
JD
1981
1982 DBG("Relay get metadata");
1983
eea7556c 1984 health_code_update();
2f8f53af 1985
58eb9381 1986 ret = recv_request(conn->sock, &request, sizeof(request));
2f8f53af 1987 if (ret < 0) {
d3e2ba59
JD
1988 goto end;
1989 }
eea7556c 1990 health_code_update();
d3e2ba59 1991
53efb85a
MD
1992 memset(&reply, 0, sizeof(reply));
1993
7591bab1
MD
1994 vstream = viewer_stream_get_by_id(be64toh(request.stream_id));
1995 if (!vstream) {
3b463131
MD
1996 /*
1997 * The metadata stream can be closed by a CLOSE command
1998 * just before we attach. It can also be closed by
1999 * per-pid tracing during tracing. Therefore, it is
2000 * possible that we cannot find this viewer stream.
2001 * Reply back to the client with an error if we cannot
2002 * find it.
2003 */
a44ca2ca 2004 DBG("Client requested metadata of unknown stream id %" PRIu64,
9b9f9f94 2005 (uint64_t) be64toh(request.stream_id));
3b463131 2006 reply.status = htobe32(LTTNG_VIEWER_METADATA_ERR);
7591bab1 2007 goto send_reply;
d3e2ba59 2008 }
7591bab1
MD
2009 pthread_mutex_lock(&vstream->stream->lock);
2010 if (!vstream->stream->is_metadata) {
2011 ERR("Invalid metadata stream");
6763619c
JD
2012 goto error;
2013 }
2014
b0d240a2 2015 if (vstream->metadata_sent >= vstream->stream->metadata_received) {
94f73d08
MD
2016 /*
2017 * The live viewers expect to receive a NO_NEW_METADATA
2018 * status before a stream disappears, otherwise they abort the
2019 * entire live connection when receiving an error status.
b0d240a2
MD
2020 *
2021 * Clear feature resets the metadata_sent to 0 until the
2022 * same metadata is received again.
94f73d08 2023 */
c4e361a4 2024 reply.status = htobe32(LTTNG_VIEWER_NO_NEW_METADATA);
94f73d08
MD
2025 /*
2026 * The live viewer considers a closed 0 byte metadata stream as
2027 * an error.
2028 */
2029 if (vstream->metadata_sent > 0) {
e8b269fa 2030 if (vstream->stream->closed && vstream->stream->no_new_metadata_notified) {
94f73d08
MD
2031 /* Release ownership for the viewer metadata stream. */
2032 viewer_stream_put(vstream);
2033 }
e8b269fa 2034 vstream->stream->no_new_metadata_notified = true;
94f73d08 2035 }
d3e2ba59
JD
2036 goto send_reply;
2037 }
2038
ad8bec24
JG
2039 if (vstream->stream->trace_chunk &&
2040 !lttng_trace_chunk_ids_equal(
2041 conn->viewer_session->current_trace_chunk,
2042 vstream->stream->trace_chunk)) {
2043 /* A rotation has occurred on the relay stream. */
2044 DBG("Metadata relay stream and viewer chunk ids differ");
2045
2046 ret = viewer_session_set_trace_chunk_copy(
2047 conn->viewer_session,
2048 vstream->stream->trace_chunk);
2049 if (ret) {
2050 reply.status = htobe32(LTTNG_VIEWER_METADATA_ERR);
2051 goto send_reply;
2052 }
2053 }
2054
87250ba1 2055 if (conn->viewer_session->current_trace_chunk &&
d8f644d9
MD
2056 !lttng_trace_chunk_ids_equal(conn->viewer_session->current_trace_chunk,
2057 vstream->stream_file.trace_chunk)) {
ad8bec24
JG
2058 bool acquired_reference;
2059
2060 DBG("Viewer session and viewer stream chunk differ: "
2061 "vsession chunk %p vstream chunk %p",
2062 conn->viewer_session->current_trace_chunk,
2063 vstream->stream_file.trace_chunk);
2064 lttng_trace_chunk_put(vstream->stream_file.trace_chunk);
2065 acquired_reference = lttng_trace_chunk_get(conn->viewer_session->current_trace_chunk);
a0377dfe 2066 LTTNG_ASSERT(acquired_reference);
ad8bec24
JG
2067 vstream->stream_file.trace_chunk =
2068 conn->viewer_session->current_trace_chunk;
2069 viewer_stream_close_files(vstream);
2070 }
2071
b0d240a2
MD
2072 len = vstream->stream->metadata_received - vstream->metadata_sent;
2073
87250ba1
JG
2074 if (!vstream->stream_file.trace_chunk) {
2075 reply.status = htobe32(LTTNG_VIEWER_NO_NEW_METADATA);
2076 len = 0;
2077 goto send_reply;
2078 } else if (vstream->stream_file.trace_chunk &&
2079 !vstream->stream_file.handle && len > 0) {
2080 /*
2081 * Either this is the first time the metadata file is read, or a
2082 * rotation of the corresponding relay stream has occurred.
2083 */
8bb66c3c 2084 struct fs_handle *fs_handle;
ebb29c10
JG
2085 char file_path[LTTNG_PATH_MAX];
2086 enum lttng_trace_chunk_status status;
2087 struct relay_stream *rstream = vstream->stream;
2088
2089 ret = utils_stream_file_path(rstream->path_name,
2090 rstream->channel_name, rstream->tracefile_size,
2091 vstream->current_tracefile_id, NULL, file_path,
2092 sizeof(file_path));
d3e2ba59
JD
2093 if (ret < 0) {
2094 goto error;
2095 }
ebb29c10 2096
3ff5c5db
MD
2097 /*
2098 * It is possible the the metadata file we are trying to open is
2099 * missing if the stream has been closed (application exits with
2100 * per-pid buffers) and a clear command has been performed.
2101 */
8bb66c3c 2102 status = lttng_trace_chunk_open_fs_handle(
ebb29c10 2103 vstream->stream_file.trace_chunk,
8bb66c3c 2104 file_path, O_RDONLY, 0, &fs_handle, true);
ebb29c10 2105 if (status != LTTNG_TRACE_CHUNK_STATUS_OK) {
b0d240a2
MD
2106 if (status == LTTNG_TRACE_CHUNK_STATUS_NO_FILE) {
2107 reply.status = htobe32(LTTNG_VIEWER_NO_NEW_METADATA);
2108 len = 0;
2109 if (vstream->stream->closed) {
2110 viewer_stream_put(vstream);
2111 }
2112 goto send_reply;
2113 }
ebb29c10 2114 PERROR("Failed to open metadata file for viewer stream");
d3e2ba59
JD
2115 goto error;
2116 }
8bb66c3c 2117 vstream->stream_file.handle = fs_handle;
ad8bec24
JG
2118
2119 if (vstream->metadata_sent != 0) {
2120 /*
2121 * The client does not expect to receive any metadata
2122 * it has received and metadata files in successive
2123 * chunks must be a strict superset of one another.
2124 *
2125 * Skip the first `metadata_sent` bytes to ensure
2126 * they are not sent a second time to the client.
2127 *
2128 * Baring a block layer error or an internal error,
2129 * this seek should not fail as
2130 * `vstream->stream->metadata_received` is reset when
2131 * a relay stream is rotated. If this is reached, it is
2132 * safe to assume that
2133 * `metadata_received` > `metadata_sent`.
2134 */
2135 const off_t seek_ret = fs_handle_seek(fs_handle,
2136 vstream->metadata_sent, SEEK_SET);
2137
2138 if (seek_ret < 0) {
2139 PERROR("Failed to seek metadata viewer stream file to `sent` position: pos = %" PRId64,
2140 vstream->metadata_sent);
2141 reply.status = htobe32(LTTNG_VIEWER_METADATA_ERR);
2142 goto send_reply;
2143 }
2144 }
d3e2ba59
JD
2145 }
2146
2147 reply.len = htobe64(len);
ac497a37 2148 data = (char *) zmalloc(len);
d3e2ba59
JD
2149 if (!data) {
2150 PERROR("viewer metadata zmalloc");
2151 goto error;
2152 }
2153
8bb66c3c
JG
2154 fd = fs_handle_get_fd(vstream->stream_file.handle);
2155 if (fd < 0) {
2156 ERR("Failed to restore viewer stream file system handle");
2157 goto error;
2158 }
2159 read_len = lttng_read(fd, data, len);
2160 fs_handle_put_fd(vstream->stream_file.handle);
2161 fd = -1;
6cd525e8 2162 if (read_len < len) {
ad8bec24
JG
2163 if (read_len < 0) {
2164 PERROR("Failed to read metadata file");
2165 goto error;
2166 } else {
2167 /*
2168 * A clear has been performed which prevents the relay
2169 * from sending `len` bytes of metadata.
2170 *
2171 * It is important not to send any metadata if we
2172 * couldn't read all the available metadata in one shot:
2173 * sending partial metadata can cause the client to
2174 * attempt to parse an incomplete (incoherent) metadata
2175 * stream, which would result in an error.
2176 */
2177 const off_t seek_ret = fs_handle_seek(
2178 vstream->stream_file.handle, -read_len,
2179 SEEK_CUR);
2180
cfa1e2c2 2181 DBG("Failed to read metadata: requested = %" PRIu64 ", got = %zd",
ad8bec24
JG
2182 len, read_len);
2183 read_len = 0;
2184 len = 0;
2185 if (seek_ret < 0) {
2186 PERROR("Failed to restore metadata file position after partial read");
2187 ret = -1;
2188 goto error;
2189 }
2190 }
d3e2ba59 2191 }
7591bab1 2192 vstream->metadata_sent += read_len;
c4e361a4 2193 reply.status = htobe32(LTTNG_VIEWER_METADATA_OK);
7591bab1 2194
d3e2ba59
JD
2195 goto send_reply;
2196
2197error:
c4e361a4 2198 reply.status = htobe32(LTTNG_VIEWER_METADATA_ERR);
d3e2ba59
JD
2199
2200send_reply:
eea7556c 2201 health_code_update();
7591bab1
MD
2202 if (vstream) {
2203 pthread_mutex_unlock(&vstream->stream->lock);
2204 }
58eb9381 2205 ret = send_response(conn->sock, &reply, sizeof(reply));
d3e2ba59 2206 if (ret < 0) {
7591bab1 2207 goto end_free;
d3e2ba59 2208 }
eea7556c 2209 health_code_update();
d3e2ba59
JD
2210
2211 if (len > 0) {
58eb9381 2212 ret = send_response(conn->sock, data, len);
d3e2ba59 2213 if (ret < 0) {
7591bab1 2214 goto end_free;
d3e2ba59
JD
2215 }
2216 }
2217
2218 DBG("Sent %" PRIu64 " bytes of metadata for stream %" PRIu64, len,
9b9f9f94 2219 (uint64_t) be64toh(request.stream_id));
d3e2ba59
JD
2220
2221 DBG("Metadata sent");
2222
7591bab1 2223end_free:
d3e2ba59 2224 free(data);
d3e2ba59 2225end:
7591bab1
MD
2226 if (vstream) {
2227 viewer_stream_put(vstream);
2228 }
d3e2ba59
JD
2229 return ret;
2230}
2231
c3b7390b
JD
2232/*
2233 * Create a viewer session.
2234 *
2235 * Return 0 on success or else a negative value.
2236 */
2237static
2238int viewer_create_session(struct relay_connection *conn)
2239{
2240 int ret;
2241 struct lttng_viewer_create_session_response resp;
2242
2243 DBG("Viewer create session received");
2244
53efb85a 2245 memset(&resp, 0, sizeof(resp));
c3b7390b 2246 resp.status = htobe32(LTTNG_VIEWER_CREATE_SESSION_OK);
7591bab1 2247 conn->viewer_session = viewer_session_create();
c3b7390b
JD
2248 if (!conn->viewer_session) {
2249 ERR("Allocation viewer session");
2250 resp.status = htobe32(LTTNG_VIEWER_CREATE_SESSION_ERR);
2251 goto send_reply;
2252 }
c3b7390b
JD
2253
2254send_reply:
2255 health_code_update();
2256 ret = send_response(conn->sock, &resp, sizeof(resp));
2257 if (ret < 0) {
2258 goto end;
2259 }
2260 health_code_update();
2261 ret = 0;
2262
2263end:
2264 return ret;
2265}
2266
d62023be
JD
2267/*
2268 * Detach a viewer session.
2269 *
2270 * Return 0 on success or else a negative value.
2271 */
2272static
2273int viewer_detach_session(struct relay_connection *conn)
2274{
2275 int ret;
2276 struct lttng_viewer_detach_session_response response;
2277 struct lttng_viewer_detach_session_request request;
2278 struct relay_session *session = NULL;
2279 uint64_t viewer_session_to_close;
2280
2281 DBG("Viewer detach session received");
2282
a0377dfe 2283 LTTNG_ASSERT(conn);
d62023be
JD
2284
2285 health_code_update();
2286
2287 /* Receive the request from the connected client. */
2288 ret = recv_request(conn->sock, &request, sizeof(request));
2289 if (ret < 0) {
2290 goto end;
2291 }
2292 viewer_session_to_close = be64toh(request.session_id);
2293
2294 if (!conn->viewer_session) {
2295 DBG("Client trying to detach before creating a live viewer session");
2296 response.status = htobe32(LTTNG_VIEWER_DETACH_SESSION_ERR);
2297 goto send_reply;
2298 }
2299
2300 health_code_update();
2301
2302 memset(&response, 0, sizeof(response));
2303 DBG("Detaching from session ID %" PRIu64, viewer_session_to_close);
2304
2305 session = session_get_by_id(be64toh(request.session_id));
2306 if (!session) {
2307 DBG("Relay session %" PRIu64 " not found",
9b9f9f94 2308 (uint64_t) be64toh(request.session_id));
d62023be
JD
2309 response.status = htobe32(LTTNG_VIEWER_DETACH_SESSION_UNK);
2310 goto send_reply;
2311 }
2312
2313 ret = viewer_session_is_attached(conn->viewer_session, session);
2314 if (ret != 1) {
2315 DBG("Not attached to this session");
2316 response.status = htobe32(LTTNG_VIEWER_DETACH_SESSION_ERR);
2317 goto send_reply_put;
2318 }
2319
2320 viewer_session_close_one_session(conn->viewer_session, session);
2321 response.status = htobe32(LTTNG_VIEWER_DETACH_SESSION_OK);
2322 DBG("Session %" PRIu64 " detached.", viewer_session_to_close);
2323
2324send_reply_put:
2325 session_put(session);
2326
2327send_reply:
2328 health_code_update();
2329 ret = send_response(conn->sock, &response, sizeof(response));
2330 if (ret < 0) {
2331 goto end;
2332 }
2333 health_code_update();
2334 ret = 0;
2335
2336end:
2337 return ret;
2338}
c3b7390b 2339
d3e2ba59
JD
2340/*
2341 * live_relay_unknown_command: send -1 if received unknown command
2342 */
2343static
58eb9381 2344void live_relay_unknown_command(struct relay_connection *conn)
d3e2ba59
JD
2345{
2346 struct lttcomm_relayd_generic_reply reply;
d3e2ba59 2347
53efb85a 2348 memset(&reply, 0, sizeof(reply));
d3e2ba59 2349 reply.ret_code = htobe32(LTTNG_ERR_UNK);
58eb9381 2350 (void) send_response(conn->sock, &reply, sizeof(reply));
d3e2ba59
JD
2351}
2352
2353/*
2354 * Process the commands received on the control socket
2355 */
2356static
2357int process_control(struct lttng_viewer_cmd *recv_hdr,
58eb9381 2358 struct relay_connection *conn)
d3e2ba59
JD
2359{
2360 int ret = 0;
2f8f53af
DG
2361 uint32_t msg_value;
2362
2f8f53af
DG
2363 msg_value = be32toh(recv_hdr->cmd);
2364
2365 /*
2366 * Make sure we've done the version check before any command other then a
2367 * new client connection.
2368 */
c4e361a4 2369 if (msg_value != LTTNG_VIEWER_CONNECT && !conn->version_check_done) {
58eb9381 2370 ERR("Viewer conn value %" PRIu32 " before version check", msg_value);
2f8f53af
DG
2371 ret = -1;
2372 goto end;
2373 }
d3e2ba59 2374
2f8f53af 2375 switch (msg_value) {
c4e361a4 2376 case LTTNG_VIEWER_CONNECT:
58eb9381 2377 ret = viewer_connect(conn);
d3e2ba59 2378 break;
c4e361a4 2379 case LTTNG_VIEWER_LIST_SESSIONS:
58eb9381 2380 ret = viewer_list_sessions(conn);
d3e2ba59 2381 break;
c4e361a4 2382 case LTTNG_VIEWER_ATTACH_SESSION:
58eb9381 2383 ret = viewer_attach_session(conn);
d3e2ba59 2384 break;
c4e361a4 2385 case LTTNG_VIEWER_GET_NEXT_INDEX:
58eb9381 2386 ret = viewer_get_next_index(conn);
d3e2ba59 2387 break;
c4e361a4 2388 case LTTNG_VIEWER_GET_PACKET:
58eb9381 2389 ret = viewer_get_packet(conn);
d3e2ba59 2390 break;
c4e361a4 2391 case LTTNG_VIEWER_GET_METADATA:
58eb9381 2392 ret = viewer_get_metadata(conn);
d3e2ba59 2393 break;
c4e361a4 2394 case LTTNG_VIEWER_GET_NEW_STREAMS:
58eb9381 2395 ret = viewer_get_new_streams(conn);
80e8027a 2396 break;
c3b7390b
JD
2397 case LTTNG_VIEWER_CREATE_SESSION:
2398 ret = viewer_create_session(conn);
2399 break;
d62023be
JD
2400 case LTTNG_VIEWER_DETACH_SESSION:
2401 ret = viewer_detach_session(conn);
2402 break;
d3e2ba59 2403 default:
7591bab1
MD
2404 ERR("Received unknown viewer command (%u)",
2405 be32toh(recv_hdr->cmd));
58eb9381 2406 live_relay_unknown_command(conn);
d3e2ba59
JD
2407 ret = -1;
2408 goto end;
2409 }
2410
2411end:
2412 return ret;
2413}
2414
2415static
58eb9381 2416void cleanup_connection_pollfd(struct lttng_poll_event *events, int pollfd)
d3e2ba59
JD
2417{
2418 int ret;
2419
58eb9381 2420 (void) lttng_poll_del(events, pollfd);
d3e2ba59 2421
29555a78
JG
2422 ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker, &pollfd, 1,
2423 fd_tracker_util_close_fd, NULL);
d3e2ba59
JD
2424 if (ret < 0) {
2425 ERR("Closing pollfd %d", pollfd);
2426 }
2427}
2428
d3e2ba59
JD
2429/*
2430 * This thread does the actual work
2431 */
2432static
2433void *thread_worker(void *data)
2434{
2435 int ret, err = -1;
2436 uint32_t nb_fd;
d3e2ba59 2437 struct lttng_poll_event events;
7591bab1 2438 struct lttng_ht *viewer_connections_ht;
d3e2ba59
JD
2439 struct lttng_ht_iter iter;
2440 struct lttng_viewer_cmd recv_hdr;
302d8906 2441 struct relay_connection *destroy_conn;
d3e2ba59
JD
2442
2443 DBG("[thread] Live viewer relay worker started");
2444
2445 rcu_register_thread();
2446
eea7556c
MD
2447 health_register(health_relayd, HEALTH_RELAYD_TYPE_LIVE_WORKER);
2448
9b5e0863
MD
2449 if (testpoint(relayd_thread_live_worker)) {
2450 goto error_testpoint;
2451 }
2452
d3e2ba59 2453 /* table of connections indexed on socket */
7591bab1
MD
2454 viewer_connections_ht = lttng_ht_new(0, LTTNG_HT_TYPE_ULONG);
2455 if (!viewer_connections_ht) {
2456 goto viewer_connections_ht_error;
d3e2ba59
JD
2457 }
2458
35bc1f58
JG
2459 ret = create_named_thread_poll_set(&events, 2,
2460 "Live viewer worker thread epoll");
d3e2ba59
JD
2461 if (ret < 0) {
2462 goto error_poll_create;
2463 }
2464
58eb9381 2465 ret = lttng_poll_add(&events, live_conn_pipe[0], LPOLLIN | LPOLLRDHUP);
d3e2ba59
JD
2466 if (ret < 0) {
2467 goto error;
2468 }
2469
2470restart:
2471 while (1) {
2472 int i;
2473
eea7556c
MD
2474 health_code_update();
2475
d3e2ba59
JD
2476 /* Infinite blocking call, waiting for transmission */
2477 DBG3("Relayd live viewer worker thread polling...");
eea7556c 2478 health_poll_entry();
d3e2ba59 2479 ret = lttng_poll_wait(&events, -1);
eea7556c 2480 health_poll_exit();
d3e2ba59
JD
2481 if (ret < 0) {
2482 /*
2483 * Restart interrupted system call.
2484 */
2485 if (errno == EINTR) {
2486 goto restart;
2487 }
2488 goto error;
2489 }
2490
2491 nb_fd = ret;
2492
2493 /*
2494 * Process control. The control connection is prioritised so we don't
2495 * starve it with high throughput tracing data on the data
2496 * connection.
2497 */
2498 for (i = 0; i < nb_fd; i++) {
2499 /* Fetch once the poll data */
2500 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
2501 int pollfd = LTTNG_POLL_GETFD(&events, i);
2502
eea7556c
MD
2503 health_code_update();
2504
d3e2ba59 2505 /* Thread quit pipe has been closed. Killing thread. */
bcf4a440 2506 ret = check_thread_quit_pipe(pollfd, revents);
d3e2ba59
JD
2507 if (ret) {
2508 err = 0;
2509 goto exit;
2510 }
2511
7591bab1 2512 /* Inspect the relay conn pipe for new connection. */
58eb9381 2513 if (pollfd == live_conn_pipe[0]) {
03e43155 2514 if (revents & LPOLLIN) {
302d8906
JG
2515 struct relay_connection *conn;
2516
7591bab1
MD
2517 ret = lttng_read(live_conn_pipe[0],
2518 &conn, sizeof(conn));
d3e2ba59
JD
2519 if (ret < 0) {
2520 goto error;
2521 }
73039936
FD
2522 ret = lttng_poll_add(&events,
2523 conn->sock->fd,
58eb9381 2524 LPOLLIN | LPOLLRDHUP);
73039936
FD
2525 if (ret) {
2526 ERR("Failed to add new live connection file descriptor to poll set");
2527 goto error;
2528 }
7591bab1
MD
2529 connection_ht_add(viewer_connections_ht, conn);
2530 DBG("Connection socket %d added to poll", conn->sock->fd);
03e43155
MD
2531 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2532 ERR("Relay live pipe error");
2533 goto error;
2534 } else {
2535 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
2536 goto error;
d3e2ba59 2537 }
58eb9381 2538 } else {
7591bab1 2539 /* Connection activity. */
302d8906
JG
2540 struct relay_connection *conn;
2541
7591bab1
MD
2542 conn = connection_get_by_sock(viewer_connections_ht, pollfd);
2543 if (!conn) {
2544 continue;
2545 }
58eb9381 2546
03e43155 2547 if (revents & LPOLLIN) {
58eb9381
DG
2548 ret = conn->sock->ops->recvmsg(conn->sock, &recv_hdr,
2549 sizeof(recv_hdr), 0);
d3e2ba59 2550 if (ret <= 0) {
7591bab1 2551 /* Connection closed. */
58eb9381 2552 cleanup_connection_pollfd(&events, pollfd);
7591bab1
MD
2553 /* Put "create" ownership reference. */
2554 connection_put(conn);
58eb9381 2555 DBG("Viewer control conn closed with %d", pollfd);
d3e2ba59 2556 } else {
58eb9381 2557 ret = process_control(&recv_hdr, conn);
d3e2ba59
JD
2558 if (ret < 0) {
2559 /* Clear the session on error. */
58eb9381 2560 cleanup_connection_pollfd(&events, pollfd);
7591bab1
MD
2561 /* Put "create" ownership reference. */
2562 connection_put(conn);
d3e2ba59
JD
2563 DBG("Viewer connection closed with %d", pollfd);
2564 }
2565 }
03e43155
MD
2566 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2567 cleanup_connection_pollfd(&events, pollfd);
2568 /* Put "create" ownership reference. */
2569 connection_put(conn);
2570 } else {
2571 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
2572 connection_put(conn);
2573 goto error;
d3e2ba59 2574 }
7591bab1
MD
2575 /* Put local "get_by_sock" reference. */
2576 connection_put(conn);
d3e2ba59
JD
2577 }
2578 }
2579 }
2580
2581exit:
2582error:
35bc1f58 2583 (void) fd_tracker_util_poll_clean(the_fd_tracker, &events);
d3e2ba59 2584
71efa8ef 2585 /* Cleanup remaining connection object. */
d3e2ba59 2586 rcu_read_lock();
7591bab1 2587 cds_lfht_for_each_entry(viewer_connections_ht->ht, &iter.iter,
302d8906 2588 destroy_conn,
58eb9381 2589 sock_n.node) {
eea7556c 2590 health_code_update();
7591bab1 2591 connection_put(destroy_conn);
d3e2ba59
JD
2592 }
2593 rcu_read_unlock();
2594error_poll_create:
7591bab1
MD
2595 lttng_ht_destroy(viewer_connections_ht);
2596viewer_connections_ht_error:
58eb9381 2597 /* Close relay conn pipes */
87bcbe91 2598 (void) fd_tracker_util_pipe_close(the_fd_tracker, live_conn_pipe);
d3e2ba59
JD
2599 if (err) {
2600 DBG("Viewer worker thread exited with error");
2601 }
2602 DBG("Viewer worker thread cleanup complete");
9b5e0863 2603error_testpoint:
eea7556c
MD
2604 if (err) {
2605 health_error();
2606 ERR("Health error occurred in %s", __func__);
2607 }
2608 health_unregister(health_relayd);
b4aacfdc
MD
2609 if (lttng_relay_stop_threads()) {
2610 ERR("Error stopping threads");
178a0557 2611 }
d3e2ba59
JD
2612 rcu_unregister_thread();
2613 return NULL;
2614}
2615
2616/*
2617 * Create the relay command pipe to wake thread_manage_apps.
2618 * Closed in cleanup().
2619 */
58eb9381 2620static int create_conn_pipe(void)
d3e2ba59 2621{
87bcbe91
JG
2622 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker,
2623 "Live connection pipe", live_conn_pipe);
178a0557 2624}
d3e2ba59 2625
178a0557 2626int relayd_live_join(void)
d3e2ba59 2627{
178a0557 2628 int ret, retval = 0;
d3e2ba59
JD
2629 void *status;
2630
d3e2ba59 2631 ret = pthread_join(live_listener_thread, &status);
178a0557
MD
2632 if (ret) {
2633 errno = ret;
d3e2ba59 2634 PERROR("pthread_join live listener");
178a0557 2635 retval = -1;
d3e2ba59
JD
2636 }
2637
2638 ret = pthread_join(live_worker_thread, &status);
178a0557
MD
2639 if (ret) {
2640 errno = ret;
d3e2ba59 2641 PERROR("pthread_join live worker");
178a0557 2642 retval = -1;
d3e2ba59
JD
2643 }
2644
2645 ret = pthread_join(live_dispatcher_thread, &status);
178a0557
MD
2646 if (ret) {
2647 errno = ret;
d3e2ba59 2648 PERROR("pthread_join live dispatcher");
178a0557 2649 retval = -1;
d3e2ba59
JD
2650 }
2651
178a0557 2652 cleanup_relayd_live();
d3e2ba59 2653
178a0557 2654 return retval;
d3e2ba59
JD
2655}
2656
2657/*
2658 * main
2659 */
7591bab1 2660int relayd_live_create(struct lttng_uri *uri)
d3e2ba59 2661{
178a0557 2662 int ret = 0, retval = 0;
d3e2ba59
JD
2663 void *status;
2664 int is_root;
2665
178a0557
MD
2666 if (!uri) {
2667 retval = -1;
2668 goto exit_init_data;
2669 }
d3e2ba59
JD
2670 live_uri = uri;
2671
d3e2ba59
JD
2672 /* Check if daemon is UID = 0 */
2673 is_root = !getuid();
2674
2675 if (!is_root) {
2676 if (live_uri->port < 1024) {
2677 ERR("Need to be root to use ports < 1024");
178a0557
MD
2678 retval = -1;
2679 goto exit_init_data;
d3e2ba59
JD
2680 }
2681 }
2682
2683 /* Setup the thread apps communication pipe. */
178a0557
MD
2684 if (create_conn_pipe()) {
2685 retval = -1;
2686 goto exit_init_data;
d3e2ba59
JD
2687 }
2688
2689 /* Init relay command queue. */
8bdee6e2 2690 cds_wfcq_init(&viewer_conn_queue.head, &viewer_conn_queue.tail);
d3e2ba59
JD
2691
2692 /* Set up max poll set size */
25b397f9
MD
2693 if (lttng_poll_set_max_size()) {
2694 retval = -1;
2695 goto exit_init_data;
2696 }
d3e2ba59
JD
2697
2698 /* Setup the dispatcher thread */
1a1a34b4 2699 ret = pthread_create(&live_dispatcher_thread, default_pthread_attr(),
d3e2ba59 2700 thread_dispatcher, (void *) NULL);
178a0557
MD
2701 if (ret) {
2702 errno = ret;
d3e2ba59 2703 PERROR("pthread_create viewer dispatcher");
178a0557
MD
2704 retval = -1;
2705 goto exit_dispatcher_thread;
d3e2ba59
JD
2706 }
2707
2708 /* Setup the worker thread */
1a1a34b4 2709 ret = pthread_create(&live_worker_thread, default_pthread_attr(),
7591bab1 2710 thread_worker, NULL);
178a0557
MD
2711 if (ret) {
2712 errno = ret;
d3e2ba59 2713 PERROR("pthread_create viewer worker");
178a0557
MD
2714 retval = -1;
2715 goto exit_worker_thread;
d3e2ba59
JD
2716 }
2717
2718 /* Setup the listener thread */
1a1a34b4 2719 ret = pthread_create(&live_listener_thread, default_pthread_attr(),
d3e2ba59 2720 thread_listener, (void *) NULL);
178a0557
MD
2721 if (ret) {
2722 errno = ret;
d3e2ba59 2723 PERROR("pthread_create viewer listener");
178a0557
MD
2724 retval = -1;
2725 goto exit_listener_thread;
d3e2ba59
JD
2726 }
2727
178a0557
MD
2728 /*
2729 * All OK, started all threads.
2730 */
2731 return retval;
2732
9911d21b
JG
2733 /*
2734 * Join on the live_listener_thread should anything be added after
2735 * the live_listener thread's creation.
2736 */
d3e2ba59 2737
178a0557 2738exit_listener_thread:
d3e2ba59 2739
d3e2ba59 2740 ret = pthread_join(live_worker_thread, &status);
178a0557
MD
2741 if (ret) {
2742 errno = ret;
d3e2ba59 2743 PERROR("pthread_join live worker");
178a0557 2744 retval = -1;
d3e2ba59 2745 }
178a0557 2746exit_worker_thread:
d3e2ba59 2747
d3e2ba59 2748 ret = pthread_join(live_dispatcher_thread, &status);
178a0557
MD
2749 if (ret) {
2750 errno = ret;
d3e2ba59 2751 PERROR("pthread_join live dispatcher");
178a0557 2752 retval = -1;
d3e2ba59 2753 }
178a0557 2754exit_dispatcher_thread:
d3e2ba59 2755
178a0557
MD
2756exit_init_data:
2757 cleanup_relayd_live();
d3e2ba59 2758
178a0557 2759 return retval;
d3e2ba59 2760}
This page took 0.205695 seconds and 4 git commands to generate.