Fix: relayd: don't check new metadata on 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
1482 DBG2("Relay get data packet");
1483
1484 health_code_update();
1485
1486 ret = recv_request(conn->sock, &get_packet_info,
1487 sizeof(get_packet_info));
1488 if (ret < 0) {
1489 goto end;
1490 }
1491 health_code_update();
1492
1493 /* From this point on, the error label can be reached. */
1494 memset(&reply, 0, sizeof(reply));
1495
1496 vstream = viewer_stream_get_by_id(be64toh(get_packet_info.stream_id));
1497 if (!vstream) {
1498 reply.status = htobe32(LTTNG_VIEWER_GET_PACKET_ERR);
1499 goto send_reply_nolock;
1500 }
1501
1502 pthread_mutex_lock(&vstream->stream->lock);
1503
1504 len = be32toh(get_packet_info.len);
1505 data = zmalloc(len);
1506 if (!data) {
1507 PERROR("relay data zmalloc");
1508 goto error;
1509 }
1510
1511 ret = lseek(vstream->stream_fd->fd, be64toh(get_packet_info.offset),
1512 SEEK_SET);
1513 if (ret < 0) {
1514 PERROR("lseek fd %d to offset %" PRIu64, vstream->stream_fd->fd,
1515 be64toh(get_packet_info.offset));
1516 goto error;
1517 }
1518 read_len = lttng_read(vstream->stream_fd->fd, data, len);
1519 if (read_len < len) {
1520 PERROR("Relay reading trace file, fd: %d, offset: %" PRIu64,
1521 vstream->stream_fd->fd,
1522 be64toh(get_packet_info.offset));
1523 goto error;
1524 }
1525 reply.status = htobe32(LTTNG_VIEWER_GET_PACKET_OK);
1526 reply.len = htobe32(len);
1527 send_data = 1;
1528 goto send_reply;
1529
1530 error:
1531 reply.status = htobe32(LTTNG_VIEWER_GET_PACKET_ERR);
1532
1533 send_reply:
1534 if (vstream) {
1535 pthread_mutex_unlock(&vstream->stream->lock);
1536 }
1537 send_reply_nolock:
1538 reply.flags = htobe32(reply.flags);
1539
1540 health_code_update();
1541
1542 ret = send_response(conn->sock, &reply, sizeof(reply));
1543 if (ret < 0) {
1544 goto end_free;
1545 }
1546 health_code_update();
1547
1548 if (send_data) {
1549 health_code_update();
1550 ret = send_response(conn->sock, data, len);
1551 if (ret < 0) {
1552 goto end_free;
1553 }
1554 health_code_update();
1555 }
1556
1557 DBG("Sent %u bytes for stream %" PRIu64, len,
1558 be64toh(get_packet_info.stream_id));
1559
1560 end_free:
1561 free(data);
1562 end:
1563 if (vstream) {
1564 viewer_stream_put(vstream);
1565 }
1566 return ret;
1567 }
1568
1569 /*
1570 * Send the session's metadata
1571 *
1572 * Return 0 on success else a negative value.
1573 */
1574 static
1575 int viewer_get_metadata(struct relay_connection *conn)
1576 {
1577 int ret = 0;
1578 ssize_t read_len;
1579 uint64_t len = 0;
1580 char *data = NULL;
1581 struct lttng_viewer_get_metadata request;
1582 struct lttng_viewer_metadata_packet reply;
1583 struct relay_viewer_stream *vstream = NULL;
1584
1585 assert(conn);
1586
1587 DBG("Relay get metadata");
1588
1589 health_code_update();
1590
1591 ret = recv_request(conn->sock, &request, sizeof(request));
1592 if (ret < 0) {
1593 goto end;
1594 }
1595 health_code_update();
1596
1597 memset(&reply, 0, sizeof(reply));
1598
1599 vstream = viewer_stream_get_by_id(be64toh(request.stream_id));
1600 if (!vstream) {
1601 /*
1602 * The metadata stream can be closed by a CLOSE command
1603 * just before we attach. It can also be closed by
1604 * per-pid tracing during tracing. Therefore, it is
1605 * possible that we cannot find this viewer stream.
1606 * Reply back to the client with an error if we cannot
1607 * find it.
1608 */
1609 reply.status = htobe32(LTTNG_VIEWER_METADATA_ERR);
1610 goto send_reply;
1611 }
1612 pthread_mutex_lock(&vstream->stream->lock);
1613 if (!vstream->stream->is_metadata) {
1614 ERR("Invalid metadata stream");
1615 goto error;
1616 }
1617
1618 assert(vstream->metadata_sent <= vstream->stream->metadata_received);
1619
1620 len = vstream->stream->metadata_received - vstream->metadata_sent;
1621 if (len == 0) {
1622 reply.status = htobe32(LTTNG_VIEWER_NO_NEW_METADATA);
1623 goto send_reply;
1624 }
1625
1626 /* first time, we open the metadata file */
1627 if (!vstream->stream_fd) {
1628 char fullpath[PATH_MAX];
1629
1630 ret = snprintf(fullpath, PATH_MAX, "%s/%s", vstream->path_name,
1631 vstream->channel_name);
1632 if (ret < 0) {
1633 goto error;
1634 }
1635 ret = open(fullpath, O_RDONLY);
1636 if (ret < 0) {
1637 PERROR("Relay opening metadata file");
1638 goto error;
1639 }
1640 vstream->stream_fd = stream_fd_create(ret);
1641 if (!vstream->stream_fd) {
1642 if (close(ret)) {
1643 PERROR("close");
1644 }
1645 goto error;
1646 }
1647 }
1648
1649 reply.len = htobe64(len);
1650 data = zmalloc(len);
1651 if (!data) {
1652 PERROR("viewer metadata zmalloc");
1653 goto error;
1654 }
1655
1656 read_len = lttng_read(vstream->stream_fd->fd, data, len);
1657 if (read_len < len) {
1658 PERROR("Relay reading metadata file");
1659 goto error;
1660 }
1661 vstream->metadata_sent += read_len;
1662 if (vstream->metadata_sent == vstream->stream->metadata_received
1663 && vstream->stream->closed) {
1664 /* Release ownership for the viewer metadata stream. */
1665 viewer_stream_put(vstream);
1666 }
1667
1668 reply.status = htobe32(LTTNG_VIEWER_METADATA_OK);
1669
1670 goto send_reply;
1671
1672 error:
1673 reply.status = htobe32(LTTNG_VIEWER_METADATA_ERR);
1674
1675 send_reply:
1676 health_code_update();
1677 if (vstream) {
1678 pthread_mutex_unlock(&vstream->stream->lock);
1679 }
1680 ret = send_response(conn->sock, &reply, sizeof(reply));
1681 if (ret < 0) {
1682 goto end_free;
1683 }
1684 health_code_update();
1685
1686 if (len > 0) {
1687 ret = send_response(conn->sock, data, len);
1688 if (ret < 0) {
1689 goto end_free;
1690 }
1691 }
1692
1693 DBG("Sent %" PRIu64 " bytes of metadata for stream %" PRIu64, len,
1694 be64toh(request.stream_id));
1695
1696 DBG("Metadata sent");
1697
1698 end_free:
1699 free(data);
1700 end:
1701 if (vstream) {
1702 viewer_stream_put(vstream);
1703 }
1704 return ret;
1705 }
1706
1707 /*
1708 * Create a viewer session.
1709 *
1710 * Return 0 on success or else a negative value.
1711 */
1712 static
1713 int viewer_create_session(struct relay_connection *conn)
1714 {
1715 int ret;
1716 struct lttng_viewer_create_session_response resp;
1717
1718 DBG("Viewer create session received");
1719
1720 memset(&resp, 0, sizeof(resp));
1721 resp.status = htobe32(LTTNG_VIEWER_CREATE_SESSION_OK);
1722 conn->viewer_session = viewer_session_create();
1723 if (!conn->viewer_session) {
1724 ERR("Allocation viewer session");
1725 resp.status = htobe32(LTTNG_VIEWER_CREATE_SESSION_ERR);
1726 goto send_reply;
1727 }
1728
1729 send_reply:
1730 health_code_update();
1731 ret = send_response(conn->sock, &resp, sizeof(resp));
1732 if (ret < 0) {
1733 goto end;
1734 }
1735 health_code_update();
1736 ret = 0;
1737
1738 end:
1739 return ret;
1740 }
1741
1742
1743 /*
1744 * live_relay_unknown_command: send -1 if received unknown command
1745 */
1746 static
1747 void live_relay_unknown_command(struct relay_connection *conn)
1748 {
1749 struct lttcomm_relayd_generic_reply reply;
1750
1751 memset(&reply, 0, sizeof(reply));
1752 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1753 (void) send_response(conn->sock, &reply, sizeof(reply));
1754 }
1755
1756 /*
1757 * Process the commands received on the control socket
1758 */
1759 static
1760 int process_control(struct lttng_viewer_cmd *recv_hdr,
1761 struct relay_connection *conn)
1762 {
1763 int ret = 0;
1764 uint32_t msg_value;
1765
1766 msg_value = be32toh(recv_hdr->cmd);
1767
1768 /*
1769 * Make sure we've done the version check before any command other then a
1770 * new client connection.
1771 */
1772 if (msg_value != LTTNG_VIEWER_CONNECT && !conn->version_check_done) {
1773 ERR("Viewer conn value %" PRIu32 " before version check", msg_value);
1774 ret = -1;
1775 goto end;
1776 }
1777
1778 switch (msg_value) {
1779 case LTTNG_VIEWER_CONNECT:
1780 ret = viewer_connect(conn);
1781 break;
1782 case LTTNG_VIEWER_LIST_SESSIONS:
1783 ret = viewer_list_sessions(conn);
1784 break;
1785 case LTTNG_VIEWER_ATTACH_SESSION:
1786 ret = viewer_attach_session(conn);
1787 break;
1788 case LTTNG_VIEWER_GET_NEXT_INDEX:
1789 ret = viewer_get_next_index(conn);
1790 break;
1791 case LTTNG_VIEWER_GET_PACKET:
1792 ret = viewer_get_packet(conn);
1793 break;
1794 case LTTNG_VIEWER_GET_METADATA:
1795 ret = viewer_get_metadata(conn);
1796 break;
1797 case LTTNG_VIEWER_GET_NEW_STREAMS:
1798 ret = viewer_get_new_streams(conn);
1799 break;
1800 case LTTNG_VIEWER_CREATE_SESSION:
1801 ret = viewer_create_session(conn);
1802 break;
1803 default:
1804 ERR("Received unknown viewer command (%u)",
1805 be32toh(recv_hdr->cmd));
1806 live_relay_unknown_command(conn);
1807 ret = -1;
1808 goto end;
1809 }
1810
1811 end:
1812 return ret;
1813 }
1814
1815 static
1816 void cleanup_connection_pollfd(struct lttng_poll_event *events, int pollfd)
1817 {
1818 int ret;
1819
1820 (void) lttng_poll_del(events, pollfd);
1821
1822 ret = close(pollfd);
1823 if (ret < 0) {
1824 ERR("Closing pollfd %d", pollfd);
1825 }
1826 }
1827
1828 /*
1829 * This thread does the actual work
1830 */
1831 static
1832 void *thread_worker(void *data)
1833 {
1834 int ret, err = -1;
1835 uint32_t nb_fd;
1836 struct lttng_poll_event events;
1837 struct lttng_ht *viewer_connections_ht;
1838 struct lttng_ht_iter iter;
1839 struct lttng_viewer_cmd recv_hdr;
1840 struct relay_connection *destroy_conn;
1841
1842 DBG("[thread] Live viewer relay worker started");
1843
1844 rcu_register_thread();
1845
1846 health_register(health_relayd, HEALTH_RELAYD_TYPE_LIVE_WORKER);
1847
1848 if (testpoint(relayd_thread_live_worker)) {
1849 goto error_testpoint;
1850 }
1851
1852 /* table of connections indexed on socket */
1853 viewer_connections_ht = lttng_ht_new(0, LTTNG_HT_TYPE_ULONG);
1854 if (!viewer_connections_ht) {
1855 goto viewer_connections_ht_error;
1856 }
1857
1858 ret = create_thread_poll_set(&events, 2);
1859 if (ret < 0) {
1860 goto error_poll_create;
1861 }
1862
1863 ret = lttng_poll_add(&events, live_conn_pipe[0], LPOLLIN | LPOLLRDHUP);
1864 if (ret < 0) {
1865 goto error;
1866 }
1867
1868 restart:
1869 while (1) {
1870 int i;
1871
1872 health_code_update();
1873
1874 /* Infinite blocking call, waiting for transmission */
1875 DBG3("Relayd live viewer worker thread polling...");
1876 health_poll_entry();
1877 ret = lttng_poll_wait(&events, -1);
1878 health_poll_exit();
1879 if (ret < 0) {
1880 /*
1881 * Restart interrupted system call.
1882 */
1883 if (errno == EINTR) {
1884 goto restart;
1885 }
1886 goto error;
1887 }
1888
1889 nb_fd = ret;
1890
1891 /*
1892 * Process control. The control connection is prioritised so we don't
1893 * starve it with high throughput tracing data on the data
1894 * connection.
1895 */
1896 for (i = 0; i < nb_fd; i++) {
1897 /* Fetch once the poll data */
1898 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
1899 int pollfd = LTTNG_POLL_GETFD(&events, i);
1900
1901 health_code_update();
1902
1903 if (!revents) {
1904 /* No activity for this FD (poll implementation). */
1905 continue;
1906 }
1907
1908 /* Thread quit pipe has been closed. Killing thread. */
1909 ret = check_thread_quit_pipe(pollfd, revents);
1910 if (ret) {
1911 err = 0;
1912 goto exit;
1913 }
1914
1915 /* Inspect the relay conn pipe for new connection. */
1916 if (pollfd == live_conn_pipe[0]) {
1917 if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
1918 ERR("Relay live pipe error");
1919 goto error;
1920 } else if (revents & LPOLLIN) {
1921 struct relay_connection *conn;
1922
1923 ret = lttng_read(live_conn_pipe[0],
1924 &conn, sizeof(conn));
1925 if (ret < 0) {
1926 goto error;
1927 }
1928 lttng_poll_add(&events, conn->sock->fd,
1929 LPOLLIN | LPOLLRDHUP);
1930 connection_ht_add(viewer_connections_ht, conn);
1931 DBG("Connection socket %d added to poll", conn->sock->fd);
1932 }
1933 } else {
1934 /* Connection activity. */
1935 struct relay_connection *conn;
1936
1937 conn = connection_get_by_sock(viewer_connections_ht, pollfd);
1938 if (!conn) {
1939 continue;
1940 }
1941
1942 if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
1943 cleanup_connection_pollfd(&events, pollfd);
1944 /* Put "create" ownership reference. */
1945 connection_put(conn);
1946 } else if (revents & LPOLLIN) {
1947 ret = conn->sock->ops->recvmsg(conn->sock, &recv_hdr,
1948 sizeof(recv_hdr), 0);
1949 if (ret <= 0) {
1950 /* Connection closed. */
1951 cleanup_connection_pollfd(&events, pollfd);
1952 /* Put "create" ownership reference. */
1953 connection_put(conn);
1954 DBG("Viewer control conn closed with %d", pollfd);
1955 } else {
1956 ret = process_control(&recv_hdr, conn);
1957 if (ret < 0) {
1958 /* Clear the session on error. */
1959 cleanup_connection_pollfd(&events, pollfd);
1960 /* Put "create" ownership reference. */
1961 connection_put(conn);
1962 DBG("Viewer connection closed with %d", pollfd);
1963 }
1964 }
1965 }
1966 /* Put local "get_by_sock" reference. */
1967 connection_put(conn);
1968 }
1969 }
1970 }
1971
1972 exit:
1973 error:
1974 lttng_poll_clean(&events);
1975
1976 /* Cleanup reamaining connection object. */
1977 rcu_read_lock();
1978 cds_lfht_for_each_entry(viewer_connections_ht->ht, &iter.iter,
1979 destroy_conn,
1980 sock_n.node) {
1981 health_code_update();
1982 connection_put(destroy_conn);
1983 }
1984 rcu_read_unlock();
1985 error_poll_create:
1986 lttng_ht_destroy(viewer_connections_ht);
1987 viewer_connections_ht_error:
1988 /* Close relay conn pipes */
1989 utils_close_pipe(live_conn_pipe);
1990 if (err) {
1991 DBG("Viewer worker thread exited with error");
1992 }
1993 DBG("Viewer worker thread cleanup complete");
1994 error_testpoint:
1995 if (err) {
1996 health_error();
1997 ERR("Health error occurred in %s", __func__);
1998 }
1999 health_unregister(health_relayd);
2000 if (lttng_relay_stop_threads()) {
2001 ERR("Error stopping threads");
2002 }
2003 rcu_unregister_thread();
2004 return NULL;
2005 }
2006
2007 /*
2008 * Create the relay command pipe to wake thread_manage_apps.
2009 * Closed in cleanup().
2010 */
2011 static int create_conn_pipe(void)
2012 {
2013 return utils_create_pipe_cloexec(live_conn_pipe);
2014 }
2015
2016 int relayd_live_join(void)
2017 {
2018 int ret, retval = 0;
2019 void *status;
2020
2021 ret = pthread_join(live_listener_thread, &status);
2022 if (ret) {
2023 errno = ret;
2024 PERROR("pthread_join live listener");
2025 retval = -1;
2026 }
2027
2028 ret = pthread_join(live_worker_thread, &status);
2029 if (ret) {
2030 errno = ret;
2031 PERROR("pthread_join live worker");
2032 retval = -1;
2033 }
2034
2035 ret = pthread_join(live_dispatcher_thread, &status);
2036 if (ret) {
2037 errno = ret;
2038 PERROR("pthread_join live dispatcher");
2039 retval = -1;
2040 }
2041
2042 cleanup_relayd_live();
2043
2044 return retval;
2045 }
2046
2047 /*
2048 * main
2049 */
2050 int relayd_live_create(struct lttng_uri *uri)
2051 {
2052 int ret = 0, retval = 0;
2053 void *status;
2054 int is_root;
2055
2056 if (!uri) {
2057 retval = -1;
2058 goto exit_init_data;
2059 }
2060 live_uri = uri;
2061
2062 /* Check if daemon is UID = 0 */
2063 is_root = !getuid();
2064
2065 if (!is_root) {
2066 if (live_uri->port < 1024) {
2067 ERR("Need to be root to use ports < 1024");
2068 retval = -1;
2069 goto exit_init_data;
2070 }
2071 }
2072
2073 /* Setup the thread apps communication pipe. */
2074 if (create_conn_pipe()) {
2075 retval = -1;
2076 goto exit_init_data;
2077 }
2078
2079 /* Init relay command queue. */
2080 cds_wfcq_init(&viewer_conn_queue.head, &viewer_conn_queue.tail);
2081
2082 /* Set up max poll set size */
2083 if (lttng_poll_set_max_size()) {
2084 retval = -1;
2085 goto exit_init_data;
2086 }
2087
2088 /* Setup the dispatcher thread */
2089 ret = pthread_create(&live_dispatcher_thread, NULL,
2090 thread_dispatcher, (void *) NULL);
2091 if (ret) {
2092 errno = ret;
2093 PERROR("pthread_create viewer dispatcher");
2094 retval = -1;
2095 goto exit_dispatcher_thread;
2096 }
2097
2098 /* Setup the worker thread */
2099 ret = pthread_create(&live_worker_thread, NULL,
2100 thread_worker, NULL);
2101 if (ret) {
2102 errno = ret;
2103 PERROR("pthread_create viewer worker");
2104 retval = -1;
2105 goto exit_worker_thread;
2106 }
2107
2108 /* Setup the listener thread */
2109 ret = pthread_create(&live_listener_thread, NULL,
2110 thread_listener, (void *) NULL);
2111 if (ret) {
2112 errno = ret;
2113 PERROR("pthread_create viewer listener");
2114 retval = -1;
2115 goto exit_listener_thread;
2116 }
2117
2118 /*
2119 * All OK, started all threads.
2120 */
2121 return retval;
2122
2123 /*
2124 * Join on the live_listener_thread should anything be added after
2125 * the live_listener thread's creation.
2126 */
2127
2128 exit_listener_thread:
2129
2130 ret = pthread_join(live_worker_thread, &status);
2131 if (ret) {
2132 errno = ret;
2133 PERROR("pthread_join live worker");
2134 retval = -1;
2135 }
2136 exit_worker_thread:
2137
2138 ret = pthread_join(live_dispatcher_thread, &status);
2139 if (ret) {
2140 errno = ret;
2141 PERROR("pthread_join live dispatcher");
2142 retval = -1;
2143 }
2144 exit_dispatcher_thread:
2145
2146 exit_init_data:
2147 cleanup_relayd_live();
2148
2149 return retval;
2150 }
This page took 0.134641 seconds and 4 git commands to generate.