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