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