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