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