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