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