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