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