Cleanup: spaghetti function return path
[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 ret = 0;
817 end_unlock:
818 rcu_read_unlock();
819 return ret;
820 }
821
822 /*
823 * Check if a connection is attached to a session.
824 * Return 1 if attached, 0 if not attached, a negative value on error.
825 */
826 static
827 int session_attached(struct relay_connection *conn, uint64_t session_id)
828 {
829 struct relay_session *session;
830 int found = 0;
831
832 if (!conn->viewer_session) {
833 goto end;
834 }
835 cds_list_for_each_entry(session,
836 &conn->viewer_session->sessions_head,
837 viewer_session_list) {
838 if (session->id == session_id) {
839 found = 1;
840 goto end;
841 }
842 }
843
844 end:
845 return found;
846 }
847
848 /*
849 * Delete all streams for a specific session ID.
850 */
851 static void destroy_viewer_streams_by_session(struct relay_session *session)
852 {
853 struct relay_viewer_stream *stream;
854 struct lttng_ht_iter iter;
855
856 assert(session);
857
858 rcu_read_lock();
859 cds_lfht_for_each_entry(viewer_streams_ht->ht, &iter.iter, stream,
860 stream_n.node) {
861 struct ctf_trace *ctf_trace;
862
863 health_code_update();
864 if (stream->session_id != session->id) {
865 continue;
866 }
867
868 ctf_trace = ctf_trace_find_by_path(session->ctf_traces_ht,
869 stream->path_name);
870 assert(ctf_trace);
871
872 viewer_stream_delete(stream);
873
874 if (stream->metadata_flag) {
875 ctf_trace->metadata_sent = 0;
876 ctf_trace->viewer_metadata_stream = NULL;
877 }
878
879 viewer_stream_destroy(ctf_trace, stream);
880 }
881 rcu_read_unlock();
882 }
883
884 static void try_destroy_streams(struct relay_session *session)
885 {
886 struct ctf_trace *ctf_trace;
887 struct lttng_ht_iter iter;
888
889 assert(session);
890
891 cds_lfht_for_each_entry(session->ctf_traces_ht->ht, &iter.iter, ctf_trace,
892 node.node) {
893 /* Attempt to destroy the ctf trace of that session. */
894 ctf_trace_try_destroy(session, ctf_trace);
895 }
896 }
897
898 /*
899 * Cleanup a session.
900 */
901 static void cleanup_session(struct relay_connection *conn,
902 struct relay_session *session)
903 {
904 /*
905 * Very important that this is done before destroying the session so we
906 * can put back every viewer stream reference from the ctf_trace.
907 */
908 destroy_viewer_streams_by_session(session);
909 try_destroy_streams(session);
910 cds_list_del(&session->viewer_session_list);
911 session_viewer_try_destroy(conn->sessions_ht, session);
912 }
913
914 /*
915 * Send the viewer the list of current sessions.
916 */
917 static
918 int viewer_get_new_streams(struct relay_connection *conn)
919 {
920 int ret, send_streams = 0;
921 uint32_t nb_created = 0, nb_unsent = 0, nb_streams = 0;
922 struct lttng_viewer_new_streams_request request;
923 struct lttng_viewer_new_streams_response response;
924 struct relay_session *session;
925 uint64_t session_id;
926
927 assert(conn);
928
929 DBG("Get new streams received");
930
931 health_code_update();
932
933 /* Receive the request from the connected client. */
934 ret = recv_request(conn->sock, &request, sizeof(request));
935 if (ret < 0) {
936 goto error;
937 }
938 session_id = be64toh(request.session_id);
939
940 health_code_update();
941
942 memset(&response, 0, sizeof(response));
943
944 rcu_read_lock();
945 session = session_find_by_id(conn->sessions_ht, session_id);
946 if (!session) {
947 DBG("Relay session %" PRIu64 " not found", session_id);
948 response.status = htobe32(LTTNG_VIEWER_NEW_STREAMS_ERR);
949 goto send_reply;
950 }
951
952 if (!session_attached(conn, session_id)) {
953 send_streams = 0;
954 response.status = htobe32(LTTNG_VIEWER_NEW_STREAMS_ERR);
955 goto send_reply;
956 }
957
958 send_streams = 1;
959 response.status = htobe32(LTTNG_VIEWER_NEW_STREAMS_OK);
960
961 ret = make_viewer_streams(session, LTTNG_VIEWER_SEEK_LAST, NULL, &nb_unsent,
962 &nb_created);
963 if (ret < 0) {
964 goto end_unlock;
965 }
966 /* Only send back the newly created streams with the unsent ones. */
967 nb_streams = nb_created + nb_unsent;
968 response.streams_count = htobe32(nb_streams);
969
970 /*
971 * If the session is closed and we have no new streams to send,
972 * it means that the viewer has already received the whole trace
973 * for this session and should now close it.
974 */
975 if (nb_streams == 0 && session->close_flag) {
976 send_streams = 0;
977 response.status = htobe32(LTTNG_VIEWER_NEW_STREAMS_HUP);
978 /*
979 * Remove the session from the attached list of the connection
980 * and try to destroy it.
981 */
982 cds_list_del(&session->viewer_session_list);
983 cleanup_session(conn, session);
984 goto send_reply;
985 }
986
987 send_reply:
988 health_code_update();
989 ret = send_response(conn->sock, &response, sizeof(response));
990 if (ret < 0) {
991 goto end_unlock;
992 }
993 health_code_update();
994
995 /*
996 * Unknown or empty session, just return gracefully, the viewer knows what
997 * is happening.
998 */
999 if (!send_streams || !nb_streams) {
1000 ret = 0;
1001 goto end_unlock;
1002 }
1003
1004 /*
1005 * Send stream and *DON'T* ignore the sent flag so every viewer streams
1006 * that were not sent from that point will be sent to the viewer.
1007 */
1008 ret = send_viewer_streams(conn->sock, session, 0);
1009 if (ret < 0) {
1010 goto end_unlock;
1011 }
1012
1013 end_unlock:
1014 rcu_read_unlock();
1015 error:
1016 return ret;
1017 }
1018
1019 /*
1020 * Send the viewer the list of current sessions.
1021 */
1022 static
1023 int viewer_attach_session(struct relay_connection *conn)
1024 {
1025 int send_streams = 0;
1026 ssize_t ret;
1027 uint32_t nb_streams = 0;
1028 enum lttng_viewer_seek seek_type;
1029 struct lttng_viewer_attach_session_request request;
1030 struct lttng_viewer_attach_session_response response;
1031 struct relay_session *session;
1032
1033 assert(conn);
1034
1035 health_code_update();
1036
1037 /* Receive the request from the connected client. */
1038 ret = recv_request(conn->sock, &request, sizeof(request));
1039 if (ret < 0) {
1040 goto error;
1041 }
1042
1043 health_code_update();
1044
1045 memset(&response, 0, sizeof(response));
1046
1047 if (!conn->viewer_session) {
1048 DBG("Client trying to attach before creating a live viewer session");
1049 response.status = htobe32(LTTNG_VIEWER_ATTACH_NO_SESSION);
1050 goto send_reply;
1051 }
1052
1053 rcu_read_lock();
1054 session = session_find_by_id(conn->sessions_ht,
1055 be64toh(request.session_id));
1056 if (!session) {
1057 DBG("Relay session %" PRIu64 " not found",
1058 be64toh(request.session_id));
1059 response.status = htobe32(LTTNG_VIEWER_ATTACH_UNK);
1060 goto send_reply;
1061 }
1062 session_viewer_attach(session);
1063 DBG("Attach session ID %" PRIu64 " received", be64toh(request.session_id));
1064
1065 if (uatomic_read(&session->viewer_refcount) > 1) {
1066 DBG("Already a viewer attached");
1067 response.status = htobe32(LTTNG_VIEWER_ATTACH_ALREADY);
1068 session_viewer_detach(session);
1069 goto send_reply;
1070 } else if (session->live_timer == 0) {
1071 DBG("Not live session");
1072 response.status = htobe32(LTTNG_VIEWER_ATTACH_NOT_LIVE);
1073 goto send_reply;
1074 } else {
1075 send_streams = 1;
1076 response.status = htobe32(LTTNG_VIEWER_ATTACH_OK);
1077 cds_list_add(&session->viewer_session_list,
1078 &conn->viewer_session->sessions_head);
1079 }
1080
1081 switch (be32toh(request.seek)) {
1082 case LTTNG_VIEWER_SEEK_BEGINNING:
1083 case LTTNG_VIEWER_SEEK_LAST:
1084 seek_type = be32toh(request.seek);
1085 break;
1086 default:
1087 ERR("Wrong seek parameter");
1088 response.status = htobe32(LTTNG_VIEWER_ATTACH_SEEK_ERR);
1089 send_streams = 0;
1090 goto send_reply;
1091 }
1092
1093 ret = make_viewer_streams(session, seek_type, &nb_streams, NULL, NULL);
1094 if (ret < 0) {
1095 goto end_unlock;
1096 }
1097 response.streams_count = htobe32(nb_streams);
1098
1099 send_reply:
1100 health_code_update();
1101 ret = send_response(conn->sock, &response, sizeof(response));
1102 if (ret < 0) {
1103 goto end_unlock;
1104 }
1105 health_code_update();
1106
1107 /*
1108 * Unknown or empty session, just return gracefully, the viewer knows what
1109 * is happening.
1110 */
1111 if (!send_streams || !nb_streams) {
1112 ret = 0;
1113 goto end_unlock;
1114 }
1115
1116 /* Send stream and ignore the sent flag. */
1117 ret = send_viewer_streams(conn->sock, session, 1);
1118 if (ret < 0) {
1119 goto end_unlock;
1120 }
1121
1122 end_unlock:
1123 rcu_read_unlock();
1124 error:
1125 return ret;
1126 }
1127
1128 /*
1129 * Open the index file if needed for the given vstream.
1130 *
1131 * If an index file is successfully opened, the index_read_fd of the stream is
1132 * set with it.
1133 *
1134 * Return 0 on success, a negative value on error (-ENOENT if not ready yet).
1135 */
1136 static int try_open_index(struct relay_viewer_stream *vstream,
1137 struct relay_stream *rstream)
1138 {
1139 int ret = 0;
1140
1141 assert(vstream);
1142 assert(rstream);
1143
1144 if (vstream->index_read_fd >= 0) {
1145 goto end;
1146 }
1147
1148 /*
1149 * First time, we open the index file and at least one index is ready. The
1150 * race between the read and write of the total_index_received is
1151 * acceptable here since the client will be notified to simply come back
1152 * and get the next index.
1153 */
1154 if (rstream->total_index_received <= 0) {
1155 ret = -ENOENT;
1156 goto end;
1157 }
1158 ret = index_open(vstream->path_name, vstream->channel_name,
1159 vstream->tracefile_count, vstream->tracefile_count_current);
1160 if (ret >= 0) {
1161 vstream->index_read_fd = ret;
1162 ret = 0;
1163 goto end;
1164 }
1165
1166 end:
1167 return ret;
1168 }
1169
1170 /*
1171 * Check the status of the index for the given stream. This function updates
1172 * the index structure if needed and can destroy the vstream also for the HUP
1173 * situation.
1174 *
1175 * Return 0 means that we can proceed with the index. A value of 1 means that
1176 * the index has been updated and is ready to be send to the client. A negative
1177 * value indicates an error that can't be handled.
1178 */
1179 static int check_index_status(struct relay_viewer_stream *vstream,
1180 struct relay_stream *rstream, struct ctf_trace *trace,
1181 struct lttng_viewer_index *index)
1182 {
1183 int ret;
1184
1185 assert(vstream);
1186 assert(rstream);
1187 assert(index);
1188 assert(trace);
1189
1190 if (!rstream->close_flag) {
1191 /* Rotate on abort (overwrite). */
1192 if (vstream->abort_flag) {
1193 DBG("Viewer stream %" PRIu64 " rotate because of overwrite",
1194 vstream->stream_handle);
1195 ret = viewer_stream_rotate(vstream, rstream);
1196 if (ret < 0) {
1197 goto error;
1198 } else if (ret == 1) {
1199 /* EOF */
1200 index->status = htobe32(LTTNG_VIEWER_INDEX_HUP);
1201 goto hup;
1202 }
1203 /* ret == 0 means successful so we continue. */
1204 }
1205
1206 /* Check if we are in the same trace file at this point. */
1207 if (rstream->tracefile_count_current == vstream->tracefile_count_current) {
1208 if (rstream->beacon_ts_end != -1ULL &&
1209 vstream->last_sent_index == rstream->total_index_received) {
1210 /*
1211 * We've received a synchronization beacon and the last index
1212 * available has been sent, the index for now is inactive.
1213 */
1214 index->status = htobe32(LTTNG_VIEWER_INDEX_INACTIVE);
1215 index->timestamp_end = htobe64(rstream->beacon_ts_end);
1216 index->stream_id = htobe64(rstream->ctf_stream_id);
1217 goto index_ready;
1218 } else if (rstream->total_index_received <= vstream->last_sent_index
1219 && !vstream->close_write_flag) {
1220 /*
1221 * Reader and writer are working in the same tracefile, so we care
1222 * about the number of index received and sent. Otherwise, we read
1223 * up to EOF.
1224 */
1225 index->status = htobe32(LTTNG_VIEWER_INDEX_RETRY);
1226 goto index_ready;
1227 }
1228 }
1229 /* Nothing to do with the index, continue with it. */
1230 ret = 0;
1231 } else if (rstream->close_flag && vstream->close_write_flag &&
1232 vstream->total_index_received == vstream->last_sent_index) {
1233 /* Last index sent and current tracefile closed in write */
1234 index->status = htobe32(LTTNG_VIEWER_INDEX_HUP);
1235 goto hup;
1236 } else {
1237 vstream->close_write_flag = 1;
1238 ret = 0;
1239 }
1240
1241 error:
1242 return ret;
1243
1244 hup:
1245 viewer_stream_delete(vstream);
1246 viewer_stream_destroy(trace, vstream);
1247 index_ready:
1248 return 1;
1249 }
1250
1251 /*
1252 * Send the next index for a stream.
1253 *
1254 * Return 0 on success or else a negative value.
1255 */
1256 static
1257 int viewer_get_next_index(struct relay_connection *conn)
1258 {
1259 int ret;
1260 ssize_t read_ret;
1261 struct lttng_viewer_get_next_index request_index;
1262 struct lttng_viewer_index viewer_index;
1263 struct ctf_packet_index packet_index;
1264 struct relay_viewer_stream *vstream;
1265 struct relay_stream *rstream;
1266 struct ctf_trace *ctf_trace;
1267 struct relay_session *session;
1268
1269 assert(conn);
1270
1271 DBG("Viewer get next index");
1272
1273 health_code_update();
1274
1275 ret = recv_request(conn->sock, &request_index, sizeof(request_index));
1276 if (ret < 0) {
1277 goto end;
1278 }
1279 health_code_update();
1280
1281 rcu_read_lock();
1282 vstream = viewer_stream_find_by_id(be64toh(request_index.stream_id));
1283 if (!vstream) {
1284 ret = -1;
1285 goto end_unlock;
1286 }
1287
1288 session = session_find_by_id(conn->sessions_ht, vstream->session_id);
1289 if (!session) {
1290 ret = -1;
1291 goto end_unlock;
1292 }
1293
1294 ctf_trace = ctf_trace_find_by_path(session->ctf_traces_ht, vstream->path_name);
1295 assert(ctf_trace);
1296
1297 memset(&viewer_index, 0, sizeof(viewer_index));
1298
1299 /*
1300 * The viewer should not ask for index on metadata stream.
1301 */
1302 if (vstream->metadata_flag) {
1303 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_HUP);
1304 goto send_reply;
1305 }
1306
1307 rstream = stream_find_by_id(relay_streams_ht, vstream->stream_handle);
1308 assert(rstream);
1309
1310 /* Try to open an index if one is needed for that stream. */
1311 ret = try_open_index(vstream, rstream);
1312 if (ret < 0) {
1313 if (ret == -ENOENT) {
1314 /*
1315 * The index is created only when the first data packet arrives, it
1316 * might not be ready at the beginning of the session
1317 */
1318 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_RETRY);
1319 } else {
1320 /* Unhandled error. */
1321 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_ERR);
1322 }
1323 goto send_reply;
1324 }
1325
1326 pthread_mutex_lock(&rstream->viewer_stream_rotation_lock);
1327 ret = check_index_status(vstream, rstream, ctf_trace, &viewer_index);
1328 pthread_mutex_unlock(&rstream->viewer_stream_rotation_lock);
1329 if (ret < 0) {
1330 goto end_unlock;
1331 } else if (ret == 1) {
1332 /*
1333 * This means the viewer index data structure has been populated by the
1334 * check call thus we now send back the reply to the client.
1335 */
1336 goto send_reply;
1337 }
1338 /* At this point, ret MUST be 0 thus we continue with the get. */
1339 assert(!ret);
1340
1341 if (!ctf_trace->metadata_received ||
1342 ctf_trace->metadata_received > ctf_trace->metadata_sent) {
1343 viewer_index.flags |= LTTNG_VIEWER_FLAG_NEW_METADATA;
1344 }
1345
1346 ret = check_new_streams(conn);
1347 if (ret < 0) {
1348 goto end_unlock;
1349 } else if (ret == 1) {
1350 viewer_index.flags |= LTTNG_VIEWER_FLAG_NEW_STREAM;
1351 }
1352
1353 pthread_mutex_lock(&rstream->viewer_stream_rotation_lock);
1354 pthread_mutex_lock(&vstream->overwrite_lock);
1355 if (vstream->abort_flag) {
1356 /* The file is being overwritten by the writer, we cannot use it. */
1357 pthread_mutex_unlock(&vstream->overwrite_lock);
1358 ret = viewer_stream_rotate(vstream, rstream);
1359 pthread_mutex_unlock(&rstream->viewer_stream_rotation_lock);
1360 if (ret < 0) {
1361 goto end_unlock;
1362 } else if (ret == 1) {
1363 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_HUP);
1364 viewer_stream_delete(vstream);
1365 viewer_stream_destroy(ctf_trace, vstream);
1366 } else {
1367 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_RETRY);
1368 }
1369 goto send_reply;
1370 }
1371
1372 read_ret = lttng_read(vstream->index_read_fd, &packet_index,
1373 sizeof(packet_index));
1374 pthread_mutex_unlock(&vstream->overwrite_lock);
1375 pthread_mutex_unlock(&rstream->viewer_stream_rotation_lock);
1376 if (read_ret < 0) {
1377 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_HUP);
1378 viewer_stream_delete(vstream);
1379 viewer_stream_destroy(ctf_trace, vstream);
1380 goto send_reply;
1381 } else if (read_ret < sizeof(packet_index)) {
1382 pthread_mutex_lock(&rstream->viewer_stream_rotation_lock);
1383 if (vstream->close_write_flag) {
1384 ret = viewer_stream_rotate(vstream, rstream);
1385 if (ret < 0) {
1386 pthread_mutex_unlock(&rstream->viewer_stream_rotation_lock);
1387 goto end_unlock;
1388 } else if (ret == 1) {
1389 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_HUP);
1390 viewer_stream_delete(vstream);
1391 viewer_stream_destroy(ctf_trace, vstream);
1392 } else {
1393 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_RETRY);
1394 }
1395 } else {
1396 ERR("Relay reading index file %d", vstream->index_read_fd);
1397 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_ERR);
1398 }
1399 pthread_mutex_unlock(&rstream->viewer_stream_rotation_lock);
1400 goto send_reply;
1401 } else {
1402 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_OK);
1403 vstream->last_sent_index++;
1404 }
1405
1406 /*
1407 * Indexes are stored in big endian, no need to switch before sending.
1408 */
1409 viewer_index.offset = packet_index.offset;
1410 viewer_index.packet_size = packet_index.packet_size;
1411 viewer_index.content_size = packet_index.content_size;
1412 viewer_index.timestamp_begin = packet_index.timestamp_begin;
1413 viewer_index.timestamp_end = packet_index.timestamp_end;
1414 viewer_index.events_discarded = packet_index.events_discarded;
1415 viewer_index.stream_id = packet_index.stream_id;
1416
1417 send_reply:
1418 viewer_index.flags = htobe32(viewer_index.flags);
1419 health_code_update();
1420
1421 ret = send_response(conn->sock, &viewer_index, sizeof(viewer_index));
1422 if (ret < 0) {
1423 goto end_unlock;
1424 }
1425 health_code_update();
1426
1427 DBG("Index %" PRIu64 " for stream %" PRIu64 " sent",
1428 vstream->last_sent_index, vstream->stream_handle);
1429
1430 end_unlock:
1431 rcu_read_unlock();
1432
1433 end:
1434 return ret;
1435 }
1436
1437 /*
1438 * Send the next index for a stream
1439 *
1440 * Return 0 on success or else a negative value.
1441 */
1442 static
1443 int viewer_get_packet(struct relay_connection *conn)
1444 {
1445 int ret, send_data = 0;
1446 char *data = NULL;
1447 uint32_t len = 0;
1448 ssize_t read_len;
1449 struct lttng_viewer_get_packet get_packet_info;
1450 struct lttng_viewer_trace_packet reply;
1451 struct relay_viewer_stream *stream;
1452 struct relay_session *session;
1453 struct ctf_trace *ctf_trace;
1454
1455 assert(conn);
1456
1457 DBG2("Relay get data packet");
1458
1459 health_code_update();
1460
1461 ret = recv_request(conn->sock, &get_packet_info, sizeof(get_packet_info));
1462 if (ret < 0) {
1463 goto end;
1464 }
1465 health_code_update();
1466
1467 /* From this point on, the error label can be reached. */
1468 memset(&reply, 0, sizeof(reply));
1469
1470 rcu_read_lock();
1471 stream = viewer_stream_find_by_id(be64toh(get_packet_info.stream_id));
1472 if (!stream) {
1473 goto error;
1474 }
1475
1476 session = session_find_by_id(conn->sessions_ht, stream->session_id);
1477 if (!session) {
1478 ret = -1;
1479 goto error;
1480 }
1481
1482 ctf_trace = ctf_trace_find_by_path(session->ctf_traces_ht,
1483 stream->path_name);
1484 assert(ctf_trace);
1485
1486 /*
1487 * First time we read this stream, we need open the tracefile, we should
1488 * only arrive here if an index has already been sent to the viewer, so the
1489 * tracefile must exist, if it does not it is a fatal error.
1490 */
1491 if (stream->read_fd < 0) {
1492 char fullpath[PATH_MAX];
1493
1494 if (stream->tracefile_count > 0) {
1495 ret = snprintf(fullpath, PATH_MAX, "%s/%s_%" PRIu64, stream->path_name,
1496 stream->channel_name,
1497 stream->tracefile_count_current);
1498 } else {
1499 ret = snprintf(fullpath, PATH_MAX, "%s/%s", stream->path_name,
1500 stream->channel_name);
1501 }
1502 if (ret < 0) {
1503 goto error;
1504 }
1505 ret = open(fullpath, O_RDONLY);
1506 if (ret < 0) {
1507 PERROR("Relay opening trace file");
1508 goto error;
1509 }
1510 stream->read_fd = ret;
1511 }
1512
1513 if (!ctf_trace->metadata_received ||
1514 ctf_trace->metadata_received > ctf_trace->metadata_sent) {
1515 reply.status = htobe32(LTTNG_VIEWER_GET_PACKET_ERR);
1516 reply.flags |= LTTNG_VIEWER_FLAG_NEW_METADATA;
1517 goto send_reply;
1518 }
1519
1520 ret = check_new_streams(conn);
1521 if (ret < 0) {
1522 goto end_unlock;
1523 } else if (ret == 1) {
1524 reply.status = htobe32(LTTNG_VIEWER_GET_PACKET_ERR);
1525 reply.flags |= LTTNG_VIEWER_FLAG_NEW_STREAM;
1526 goto send_reply;
1527 }
1528
1529 len = be32toh(get_packet_info.len);
1530 data = zmalloc(len);
1531 if (!data) {
1532 PERROR("relay data zmalloc");
1533 goto error;
1534 }
1535
1536 ret = lseek(stream->read_fd, be64toh(get_packet_info.offset), SEEK_SET);
1537 if (ret < 0) {
1538 /*
1539 * If the read fd was closed by the streaming side, the
1540 * abort_flag will be set to 1, otherwise it is an error.
1541 */
1542 if (stream->abort_flag == 0) {
1543 PERROR("lseek");
1544 goto error;
1545 }
1546 reply.status = htobe32(LTTNG_VIEWER_GET_PACKET_EOF);
1547 goto send_reply;
1548 }
1549 read_len = lttng_read(stream->read_fd, data, len);
1550 if (read_len < len) {
1551 /*
1552 * If the read fd was closed by the streaming side, the
1553 * abort_flag will be set to 1, otherwise it is an error.
1554 */
1555 if (stream->abort_flag == 0) {
1556 PERROR("Relay reading trace file, fd: %d, offset: %" PRIu64,
1557 stream->read_fd,
1558 be64toh(get_packet_info.offset));
1559 goto error;
1560 } else {
1561 reply.status = htobe32(LTTNG_VIEWER_GET_PACKET_EOF);
1562 goto send_reply;
1563 }
1564 }
1565 reply.status = htobe32(LTTNG_VIEWER_GET_PACKET_OK);
1566 reply.len = htobe32(len);
1567 send_data = 1;
1568 goto send_reply;
1569
1570 error:
1571 reply.status = htobe32(LTTNG_VIEWER_GET_PACKET_ERR);
1572
1573 send_reply:
1574 reply.flags = htobe32(reply.flags);
1575
1576 health_code_update();
1577
1578 ret = send_response(conn->sock, &reply, sizeof(reply));
1579 if (ret < 0) {
1580 goto end_unlock;
1581 }
1582 health_code_update();
1583
1584 if (send_data) {
1585 health_code_update();
1586 ret = send_response(conn->sock, data, len);
1587 if (ret < 0) {
1588 goto end_unlock;
1589 }
1590 health_code_update();
1591 }
1592
1593 DBG("Sent %u bytes for stream %" PRIu64, len,
1594 be64toh(get_packet_info.stream_id));
1595
1596 end_unlock:
1597 free(data);
1598 rcu_read_unlock();
1599
1600 end:
1601 return ret;
1602 }
1603
1604 /*
1605 * Send the session's metadata
1606 *
1607 * Return 0 on success else a negative value.
1608 */
1609 static
1610 int viewer_get_metadata(struct relay_connection *conn)
1611 {
1612 int ret = 0;
1613 ssize_t read_len;
1614 uint64_t len = 0;
1615 char *data = NULL;
1616 struct lttng_viewer_get_metadata request;
1617 struct lttng_viewer_metadata_packet reply;
1618 struct relay_viewer_stream *stream;
1619 struct ctf_trace *ctf_trace;
1620 struct relay_session *session;
1621
1622 assert(conn);
1623
1624 DBG("Relay get metadata");
1625
1626 health_code_update();
1627
1628 ret = recv_request(conn->sock, &request, sizeof(request));
1629 if (ret < 0) {
1630 goto end;
1631 }
1632 health_code_update();
1633
1634 memset(&reply, 0, sizeof(reply));
1635
1636 rcu_read_lock();
1637 stream = viewer_stream_find_by_id(be64toh(request.stream_id));
1638 if (!stream || !stream->metadata_flag) {
1639 ERR("Invalid metadata stream");
1640 goto error;
1641 }
1642
1643 session = session_find_by_id(conn->sessions_ht, stream->session_id);
1644 if (!session) {
1645 ret = -1;
1646 goto error;
1647 }
1648
1649 ctf_trace = ctf_trace_find_by_path(session->ctf_traces_ht,
1650 stream->path_name);
1651 assert(ctf_trace);
1652 assert(ctf_trace->metadata_sent <= ctf_trace->metadata_received);
1653
1654 len = ctf_trace->metadata_received - ctf_trace->metadata_sent;
1655 if (len == 0) {
1656 reply.status = htobe32(LTTNG_VIEWER_NO_NEW_METADATA);
1657 goto send_reply;
1658 }
1659
1660 /* first time, we open the metadata file */
1661 if (stream->read_fd < 0) {
1662 char fullpath[PATH_MAX];
1663
1664 ret = snprintf(fullpath, PATH_MAX, "%s/%s", stream->path_name,
1665 stream->channel_name);
1666 if (ret < 0) {
1667 goto error;
1668 }
1669 ret = open(fullpath, O_RDONLY);
1670 if (ret < 0) {
1671 PERROR("Relay opening metadata file");
1672 goto error;
1673 }
1674 stream->read_fd = ret;
1675 }
1676
1677 reply.len = htobe64(len);
1678 data = zmalloc(len);
1679 if (!data) {
1680 PERROR("viewer metadata zmalloc");
1681 goto error;
1682 }
1683
1684 read_len = lttng_read(stream->read_fd, data, len);
1685 if (read_len < len) {
1686 PERROR("Relay reading metadata file");
1687 goto error;
1688 }
1689 ctf_trace->metadata_sent += read_len;
1690 reply.status = htobe32(LTTNG_VIEWER_METADATA_OK);
1691 goto send_reply;
1692
1693 error:
1694 reply.status = htobe32(LTTNG_VIEWER_METADATA_ERR);
1695
1696 send_reply:
1697 health_code_update();
1698 ret = send_response(conn->sock, &reply, sizeof(reply));
1699 if (ret < 0) {
1700 goto end_unlock;
1701 }
1702 health_code_update();
1703
1704 if (len > 0) {
1705 ret = send_response(conn->sock, data, len);
1706 if (ret < 0) {
1707 goto end_unlock;
1708 }
1709 }
1710
1711 DBG("Sent %" PRIu64 " bytes of metadata for stream %" PRIu64, len,
1712 be64toh(request.stream_id));
1713
1714 DBG("Metadata sent");
1715
1716 end_unlock:
1717 free(data);
1718 rcu_read_unlock();
1719 end:
1720 return ret;
1721 }
1722
1723 /*
1724 * Create a viewer session.
1725 *
1726 * Return 0 on success or else a negative value.
1727 */
1728 static
1729 int viewer_create_session(struct relay_connection *conn)
1730 {
1731 int ret;
1732 struct lttng_viewer_create_session_response resp;
1733
1734 DBG("Viewer create session received");
1735
1736 memset(&resp, 0, sizeof(resp));
1737 resp.status = htobe32(LTTNG_VIEWER_CREATE_SESSION_OK);
1738 conn->viewer_session = zmalloc(sizeof(*conn->viewer_session));
1739 if (!conn->viewer_session) {
1740 ERR("Allocation viewer session");
1741 resp.status = htobe32(LTTNG_VIEWER_CREATE_SESSION_ERR);
1742 goto send_reply;
1743 }
1744 CDS_INIT_LIST_HEAD(&conn->viewer_session->sessions_head);
1745
1746 send_reply:
1747 health_code_update();
1748 ret = send_response(conn->sock, &resp, sizeof(resp));
1749 if (ret < 0) {
1750 goto end;
1751 }
1752 health_code_update();
1753 ret = 0;
1754
1755 end:
1756 return ret;
1757 }
1758
1759
1760 /*
1761 * live_relay_unknown_command: send -1 if received unknown command
1762 */
1763 static
1764 void live_relay_unknown_command(struct relay_connection *conn)
1765 {
1766 struct lttcomm_relayd_generic_reply reply;
1767
1768 memset(&reply, 0, sizeof(reply));
1769 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1770 (void) send_response(conn->sock, &reply, sizeof(reply));
1771 }
1772
1773 /*
1774 * Process the commands received on the control socket
1775 */
1776 static
1777 int process_control(struct lttng_viewer_cmd *recv_hdr,
1778 struct relay_connection *conn)
1779 {
1780 int ret = 0;
1781 uint32_t msg_value;
1782
1783 assert(recv_hdr);
1784 assert(conn);
1785
1786 msg_value = be32toh(recv_hdr->cmd);
1787
1788 /*
1789 * Make sure we've done the version check before any command other then a
1790 * new client connection.
1791 */
1792 if (msg_value != LTTNG_VIEWER_CONNECT && !conn->version_check_done) {
1793 ERR("Viewer conn value %" PRIu32 " before version check", msg_value);
1794 ret = -1;
1795 goto end;
1796 }
1797
1798 switch (msg_value) {
1799 case LTTNG_VIEWER_CONNECT:
1800 ret = viewer_connect(conn);
1801 break;
1802 case LTTNG_VIEWER_LIST_SESSIONS:
1803 ret = viewer_list_sessions(conn);
1804 break;
1805 case LTTNG_VIEWER_ATTACH_SESSION:
1806 ret = viewer_attach_session(conn);
1807 break;
1808 case LTTNG_VIEWER_GET_NEXT_INDEX:
1809 ret = viewer_get_next_index(conn);
1810 break;
1811 case LTTNG_VIEWER_GET_PACKET:
1812 ret = viewer_get_packet(conn);
1813 break;
1814 case LTTNG_VIEWER_GET_METADATA:
1815 ret = viewer_get_metadata(conn);
1816 break;
1817 case LTTNG_VIEWER_GET_NEW_STREAMS:
1818 ret = viewer_get_new_streams(conn);
1819 break;
1820 case LTTNG_VIEWER_CREATE_SESSION:
1821 ret = viewer_create_session(conn);
1822 break;
1823 default:
1824 ERR("Received unknown viewer command (%u)", be32toh(recv_hdr->cmd));
1825 live_relay_unknown_command(conn);
1826 ret = -1;
1827 goto end;
1828 }
1829
1830 end:
1831 return ret;
1832 }
1833
1834 static
1835 void cleanup_connection_pollfd(struct lttng_poll_event *events, int pollfd)
1836 {
1837 int ret;
1838
1839 assert(events);
1840
1841 (void) lttng_poll_del(events, pollfd);
1842
1843 ret = close(pollfd);
1844 if (ret < 0) {
1845 ERR("Closing pollfd %d", pollfd);
1846 }
1847 }
1848
1849 /*
1850 * Delete and destroy a connection.
1851 *
1852 * RCU read side lock MUST be acquired.
1853 */
1854 static void destroy_connection(struct lttng_ht *relay_connections_ht,
1855 struct relay_connection *conn)
1856 {
1857 struct relay_session *session, *tmp_session;
1858
1859 assert(relay_connections_ht);
1860 assert(conn);
1861
1862 connection_delete(relay_connections_ht, conn);
1863
1864 if (!conn->viewer_session) {
1865 goto end;
1866 }
1867
1868 rcu_read_lock();
1869 cds_list_for_each_entry_safe(session, tmp_session,
1870 &conn->viewer_session->sessions_head,
1871 viewer_session_list) {
1872 DBG("Cleaning connection of session ID %" PRIu64, session->id);
1873 cleanup_session(conn, session);
1874 }
1875 rcu_read_unlock();
1876
1877 end:
1878 connection_destroy(conn);
1879 }
1880
1881 /*
1882 * This thread does the actual work
1883 */
1884 static
1885 void *thread_worker(void *data)
1886 {
1887 int ret, err = -1;
1888 uint32_t nb_fd;
1889 struct relay_connection *conn;
1890 struct lttng_poll_event events;
1891 struct lttng_ht *relay_connections_ht;
1892 struct lttng_ht_iter iter;
1893 struct lttng_viewer_cmd recv_hdr;
1894 struct relay_local_data *relay_ctx = (struct relay_local_data *) data;
1895 struct lttng_ht *sessions_ht = relay_ctx->sessions_ht;
1896
1897 DBG("[thread] Live viewer relay worker started");
1898
1899 rcu_register_thread();
1900
1901 health_register(health_relayd, HEALTH_RELAYD_TYPE_LIVE_WORKER);
1902
1903 if (testpoint(relayd_thread_live_worker)) {
1904 goto error_testpoint;
1905 }
1906
1907 /* table of connections indexed on socket */
1908 relay_connections_ht = lttng_ht_new(0, LTTNG_HT_TYPE_ULONG);
1909 if (!relay_connections_ht) {
1910 goto relay_connections_ht_error;
1911 }
1912
1913 ret = create_thread_poll_set(&events, 2);
1914 if (ret < 0) {
1915 goto error_poll_create;
1916 }
1917
1918 ret = lttng_poll_add(&events, live_conn_pipe[0], LPOLLIN | LPOLLRDHUP);
1919 if (ret < 0) {
1920 goto error;
1921 }
1922
1923 restart:
1924 while (1) {
1925 int i;
1926
1927 health_code_update();
1928
1929 /* Infinite blocking call, waiting for transmission */
1930 DBG3("Relayd live viewer worker thread polling...");
1931 health_poll_entry();
1932 ret = lttng_poll_wait(&events, -1);
1933 health_poll_exit();
1934 if (ret < 0) {
1935 /*
1936 * Restart interrupted system call.
1937 */
1938 if (errno == EINTR) {
1939 goto restart;
1940 }
1941 goto error;
1942 }
1943
1944 nb_fd = ret;
1945
1946 /*
1947 * Process control. The control connection is prioritised so we don't
1948 * starve it with high throughput tracing data on the data
1949 * connection.
1950 */
1951 for (i = 0; i < nb_fd; i++) {
1952 /* Fetch once the poll data */
1953 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
1954 int pollfd = LTTNG_POLL_GETFD(&events, i);
1955
1956 health_code_update();
1957
1958 if (!revents) {
1959 /* No activity for this FD (poll implementation). */
1960 continue;
1961 }
1962
1963 /* Thread quit pipe has been closed. Killing thread. */
1964 ret = check_thread_quit_pipe(pollfd, revents);
1965 if (ret) {
1966 err = 0;
1967 goto exit;
1968 }
1969
1970 /* Inspect the relay conn pipe for new connection */
1971 if (pollfd == live_conn_pipe[0]) {
1972 if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
1973 ERR("Relay live pipe error");
1974 goto error;
1975 } else if (revents & LPOLLIN) {
1976 ret = lttng_read(live_conn_pipe[0], &conn, sizeof(conn));
1977 if (ret < 0) {
1978 goto error;
1979 }
1980 conn->sessions_ht = sessions_ht;
1981 connection_init(conn);
1982 lttng_poll_add(&events, conn->sock->fd,
1983 LPOLLIN | LPOLLRDHUP);
1984 rcu_read_lock();
1985 lttng_ht_add_unique_ulong(relay_connections_ht,
1986 &conn->sock_n);
1987 rcu_read_unlock();
1988 DBG("Connection socket %d added", conn->sock->fd);
1989 }
1990 } else {
1991 rcu_read_lock();
1992 conn = connection_find_by_sock(relay_connections_ht, pollfd);
1993 /* If not found, there is a synchronization issue. */
1994 assert(conn);
1995
1996 if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
1997 cleanup_connection_pollfd(&events, pollfd);
1998 destroy_connection(relay_connections_ht, conn);
1999 } else if (revents & LPOLLIN) {
2000 ret = conn->sock->ops->recvmsg(conn->sock, &recv_hdr,
2001 sizeof(recv_hdr), 0);
2002 if (ret <= 0) {
2003 /* Connection closed */
2004 cleanup_connection_pollfd(&events, pollfd);
2005 destroy_connection(relay_connections_ht, conn);
2006 DBG("Viewer control conn closed with %d", pollfd);
2007 } else {
2008 ret = process_control(&recv_hdr, conn);
2009 if (ret < 0) {
2010 /* Clear the session on error. */
2011 cleanup_connection_pollfd(&events, pollfd);
2012 destroy_connection(relay_connections_ht, conn);
2013 DBG("Viewer connection closed with %d", pollfd);
2014 }
2015 }
2016 }
2017 rcu_read_unlock();
2018 }
2019 }
2020 }
2021
2022 exit:
2023 error:
2024 lttng_poll_clean(&events);
2025
2026 /* Cleanup reamaining connection object. */
2027 rcu_read_lock();
2028 cds_lfht_for_each_entry(relay_connections_ht->ht, &iter.iter, conn,
2029 sock_n.node) {
2030 health_code_update();
2031 destroy_connection(relay_connections_ht, conn);
2032 }
2033 rcu_read_unlock();
2034 error_poll_create:
2035 lttng_ht_destroy(relay_connections_ht);
2036 relay_connections_ht_error:
2037 /* Close relay conn pipes */
2038 utils_close_pipe(live_conn_pipe);
2039 if (err) {
2040 DBG("Viewer worker thread exited with error");
2041 }
2042 DBG("Viewer worker thread cleanup complete");
2043 error_testpoint:
2044 if (err) {
2045 health_error();
2046 ERR("Health error occurred in %s", __func__);
2047 }
2048 health_unregister(health_relayd);
2049 stop_threads();
2050 rcu_unregister_thread();
2051 return NULL;
2052 }
2053
2054 /*
2055 * Create the relay command pipe to wake thread_manage_apps.
2056 * Closed in cleanup().
2057 */
2058 static int create_conn_pipe(void)
2059 {
2060 int ret;
2061
2062 ret = utils_create_pipe_cloexec(live_conn_pipe);
2063
2064 return ret;
2065 }
2066
2067 void live_stop_threads(void)
2068 {
2069 int ret;
2070 void *status;
2071
2072 stop_threads();
2073
2074 ret = pthread_join(live_listener_thread, &status);
2075 if (ret != 0) {
2076 PERROR("pthread_join live listener");
2077 goto error; /* join error, exit without cleanup */
2078 }
2079
2080 ret = pthread_join(live_worker_thread, &status);
2081 if (ret != 0) {
2082 PERROR("pthread_join live worker");
2083 goto error; /* join error, exit without cleanup */
2084 }
2085
2086 ret = pthread_join(live_dispatcher_thread, &status);
2087 if (ret != 0) {
2088 PERROR("pthread_join live dispatcher");
2089 goto error; /* join error, exit without cleanup */
2090 }
2091
2092 cleanup();
2093
2094 error:
2095 return;
2096 }
2097
2098 /*
2099 * main
2100 */
2101 int live_start_threads(struct lttng_uri *uri,
2102 struct relay_local_data *relay_ctx)
2103 {
2104 int ret = 0;
2105 void *status;
2106 int is_root;
2107
2108 assert(uri);
2109 live_uri = uri;
2110
2111 /* Check if daemon is UID = 0 */
2112 is_root = !getuid();
2113
2114 if (!is_root) {
2115 if (live_uri->port < 1024) {
2116 ERR("Need to be root to use ports < 1024");
2117 ret = -1;
2118 goto exit;
2119 }
2120 }
2121
2122 /* Setup the thread apps communication pipe. */
2123 if ((ret = create_conn_pipe()) < 0) {
2124 goto exit;
2125 }
2126
2127 /* Init relay command queue. */
2128 cds_wfcq_init(&viewer_conn_queue.head, &viewer_conn_queue.tail);
2129
2130 /* Set up max poll set size */
2131 lttng_poll_set_max_size();
2132
2133 /* Setup the dispatcher thread */
2134 ret = pthread_create(&live_dispatcher_thread, NULL,
2135 thread_dispatcher, (void *) NULL);
2136 if (ret != 0) {
2137 PERROR("pthread_create viewer dispatcher");
2138 goto exit_dispatcher;
2139 }
2140
2141 /* Setup the worker thread */
2142 ret = pthread_create(&live_worker_thread, NULL,
2143 thread_worker, relay_ctx);
2144 if (ret != 0) {
2145 PERROR("pthread_create viewer worker");
2146 goto exit_worker;
2147 }
2148
2149 /* Setup the listener thread */
2150 ret = pthread_create(&live_listener_thread, NULL,
2151 thread_listener, (void *) NULL);
2152 if (ret != 0) {
2153 PERROR("pthread_create viewer listener");
2154 goto exit_listener;
2155 }
2156
2157 ret = 0;
2158 goto end;
2159
2160 exit_listener:
2161 ret = pthread_join(live_listener_thread, &status);
2162 if (ret != 0) {
2163 PERROR("pthread_join live listener");
2164 goto error; /* join error, exit without cleanup */
2165 }
2166
2167 exit_worker:
2168 ret = pthread_join(live_worker_thread, &status);
2169 if (ret != 0) {
2170 PERROR("pthread_join live worker");
2171 goto error; /* join error, exit without cleanup */
2172 }
2173
2174 exit_dispatcher:
2175 ret = pthread_join(live_dispatcher_thread, &status);
2176 if (ret != 0) {
2177 PERROR("pthread_join live dispatcher");
2178 goto error; /* join error, exit without cleanup */
2179 }
2180
2181 exit:
2182 cleanup();
2183
2184 end:
2185 error:
2186 return ret;
2187 }
This page took 0.070644 seconds and 5 git commands to generate.