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