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