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