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