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