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