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