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