relayd: track the live client connections socket
[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 * 2015 - Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License, version 2 only,
8 * as published by the Free Software Foundation.
9 *
10 * This program is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
13 * more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #define _LGPL_SOURCE
21 #include <getopt.h>
22 #include <grp.h>
23 #include <limits.h>
24 #include <pthread.h>
25 #include <signal.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/mman.h>
30 #include <sys/mount.h>
31 #include <sys/resource.h>
32 #include <sys/socket.h>
33 #include <sys/stat.h>
34 #include <sys/types.h>
35 #include <sys/wait.h>
36 #include <inttypes.h>
37 #include <urcu/futex.h>
38 #include <urcu/uatomic.h>
39 #include <urcu/rculist.h>
40 #include <unistd.h>
41 #include <fcntl.h>
42
43 #include <lttng/lttng.h>
44 #include <common/common.h>
45 #include <common/compat/poll.h>
46 #include <common/compat/socket.h>
47 #include <common/compat/endian.h>
48 #include <common/defaults.h>
49 #include <common/futex.h>
50 #include <common/index/index.h>
51 #include <common/sessiond-comm/sessiond-comm.h>
52 #include <common/sessiond-comm/inet.h>
53 #include <common/sessiond-comm/relayd.h>
54 #include <common/uri.h>
55 #include <common/utils.h>
56 #include <common/fd-tracker/utils.h>
57
58 #include "cmd.h"
59 #include "live.h"
60 #include "lttng-relayd.h"
61 #include "utils.h"
62 #include "health-relayd.h"
63 #include "testpoint.h"
64 #include "viewer-stream.h"
65 #include "stream.h"
66 #include "session.h"
67 #include "ctf-trace.h"
68 #include "connection.h"
69 #include "viewer-session.h"
70
71 #define SESSION_BUF_DEFAULT_COUNT 16
72
73 static struct lttng_uri *live_uri;
74
75 /*
76 * This pipe is used to inform the worker thread that a command is queued and
77 * ready to be processed.
78 */
79 static int live_conn_pipe[2] = { -1, -1 };
80
81 /* Shared between threads */
82 static int live_dispatch_thread_exit;
83
84 static pthread_t live_listener_thread;
85 static pthread_t live_dispatcher_thread;
86 static pthread_t live_worker_thread;
87
88 /*
89 * Relay command queue.
90 *
91 * The live_thread_listener and live_thread_dispatcher communicate with this
92 * queue.
93 */
94 static struct relay_conn_queue viewer_conn_queue;
95
96 static uint64_t last_relay_viewer_session_id;
97 static pthread_mutex_t last_relay_viewer_session_id_lock =
98 PTHREAD_MUTEX_INITIALIZER;
99
100 /*
101 * Cleanup the daemon
102 */
103 static
104 void cleanup_relayd_live(void)
105 {
106 DBG("Cleaning up");
107
108 free(live_uri);
109 }
110
111 /*
112 * Receive a request buffer using a given socket, destination allocated buffer
113 * of length size.
114 *
115 * Return the size of the received message or else a negative value on error
116 * with errno being set by recvmsg() syscall.
117 */
118 static
119 ssize_t recv_request(struct lttcomm_sock *sock, void *buf, size_t size)
120 {
121 ssize_t ret;
122
123 ret = sock->ops->recvmsg(sock, buf, size, 0);
124 if (ret < 0 || ret != size) {
125 if (ret == 0) {
126 /* Orderly shutdown. Not necessary to print an error. */
127 DBG("Socket %d did an orderly shutdown", sock->fd);
128 } else {
129 ERR("Relay failed to receive request.");
130 }
131 ret = -1;
132 }
133
134 return ret;
135 }
136
137 /*
138 * Send a response buffer using a given socket, source allocated buffer of
139 * length size.
140 *
141 * Return the size of the sent message or else a negative value on error with
142 * errno being set by sendmsg() syscall.
143 */
144 static
145 ssize_t send_response(struct lttcomm_sock *sock, void *buf, size_t size)
146 {
147 ssize_t ret;
148
149 ret = sock->ops->sendmsg(sock, buf, size, 0);
150 if (ret < 0) {
151 ERR("Relayd failed to send response.");
152 }
153
154 return ret;
155 }
156
157 /*
158 * Atomically check if new streams got added in one of the sessions attached
159 * and reset the flag to 0.
160 *
161 * Returns 1 if new streams got added, 0 if nothing changed, a negative value
162 * on error.
163 */
164 static
165 int check_new_streams(struct relay_connection *conn)
166 {
167 struct relay_session *session;
168 unsigned long current_val;
169 int ret = 0;
170
171 if (!conn->viewer_session) {
172 goto end;
173 }
174 rcu_read_lock();
175 cds_list_for_each_entry_rcu(session,
176 &conn->viewer_session->session_list,
177 viewer_session_node) {
178 if (!session_get(session)) {
179 continue;
180 }
181 current_val = uatomic_cmpxchg(&session->new_streams, 1, 0);
182 ret = current_val;
183 session_put(session);
184 if (ret == 1) {
185 goto end;
186 }
187 }
188 end:
189 rcu_read_unlock();
190 return ret;
191 }
192
193 /*
194 * Send viewer streams to the given socket. The ignore_sent_flag indicates if
195 * this function should ignore the sent flag or not.
196 *
197 * Return 0 on success or else a negative value.
198 */
199 static
200 ssize_t send_viewer_streams(struct lttcomm_sock *sock,
201 uint64_t session_id, unsigned int ignore_sent_flag)
202 {
203 ssize_t ret;
204 struct lttng_viewer_stream send_stream;
205 struct lttng_ht_iter iter;
206 struct relay_viewer_stream *vstream;
207
208 rcu_read_lock();
209
210 cds_lfht_for_each_entry(viewer_streams_ht->ht, &iter.iter, vstream,
211 stream_n.node) {
212 struct ctf_trace *ctf_trace;
213
214 health_code_update();
215
216 if (!viewer_stream_get(vstream)) {
217 continue;
218 }
219
220 pthread_mutex_lock(&vstream->stream->lock);
221 /* Ignore if not the same session. */
222 if (vstream->stream->trace->session->id != session_id ||
223 (!ignore_sent_flag && vstream->sent_flag)) {
224 pthread_mutex_unlock(&vstream->stream->lock);
225 viewer_stream_put(vstream);
226 continue;
227 }
228
229 ctf_trace = vstream->stream->trace;
230 send_stream.id = htobe64(vstream->stream->stream_handle);
231 send_stream.ctf_trace_id = htobe64(ctf_trace->id);
232 send_stream.metadata_flag = htobe32(
233 vstream->stream->is_metadata);
234 if (lttng_strncpy(send_stream.path_name, vstream->path_name,
235 sizeof(send_stream.path_name))) {
236 pthread_mutex_unlock(&vstream->stream->lock);
237 viewer_stream_put(vstream);
238 ret = -1; /* Error. */
239 goto end_unlock;
240 }
241 if (lttng_strncpy(send_stream.channel_name,
242 vstream->channel_name,
243 sizeof(send_stream.channel_name))) {
244 pthread_mutex_unlock(&vstream->stream->lock);
245 viewer_stream_put(vstream);
246 ret = -1; /* Error. */
247 goto end_unlock;
248 }
249
250 DBG("Sending stream %" PRIu64 " to viewer",
251 vstream->stream->stream_handle);
252 vstream->sent_flag = 1;
253 pthread_mutex_unlock(&vstream->stream->lock);
254
255 ret = send_response(sock, &send_stream, sizeof(send_stream));
256 viewer_stream_put(vstream);
257 if (ret < 0) {
258 goto end_unlock;
259 }
260 }
261
262 ret = 0;
263
264 end_unlock:
265 rcu_read_unlock();
266 return ret;
267 }
268
269 /*
270 * Create every viewer stream possible for the given session with the seek
271 * type. Three counters *can* be return which are in order the total amount of
272 * viewer stream of the session, the number of unsent stream and the number of
273 * stream created. Those counters can be NULL and thus will be ignored.
274 *
275 * session must be locked to ensure that we see either none or all initial
276 * streams for a session, but no intermediate state..
277 *
278 * Return 0 on success or else a negative value.
279 */
280 static int make_viewer_streams(struct relay_session *session,
281 struct lttng_trace_chunk *viewer_trace_chunk,
282 enum lttng_viewer_seek seek_t,
283 uint32_t *nb_total,
284 uint32_t *nb_unsent,
285 uint32_t *nb_created,
286 bool *closed)
287 {
288 int ret;
289 struct lttng_ht_iter iter;
290 struct ctf_trace *ctf_trace;
291
292 assert(session);
293 ASSERT_LOCKED(session->lock);
294
295 if (!viewer_trace_chunk) {
296 ERR("Internal error: viewer session associated with session \"%s\" has a NULL trace chunk",
297 session->session_name);
298 ret = -1;
299 goto error;
300 }
301
302 if (session->connection_closed) {
303 *closed = true;
304 }
305
306 /*
307 * Create viewer streams for relay streams that are ready to be
308 * used for a the given session id only.
309 */
310 rcu_read_lock();
311 cds_lfht_for_each_entry(session->ctf_traces_ht->ht, &iter.iter, ctf_trace,
312 node.node) {
313 bool trace_has_metadata_stream = false;
314 struct relay_stream *stream;
315
316 health_code_update();
317
318 if (!ctf_trace_get(ctf_trace)) {
319 continue;
320 }
321
322 /*
323 * Iterate over all the streams of the trace to see if we have a
324 * metadata stream.
325 */
326 cds_list_for_each_entry_rcu(
327 stream, &ctf_trace->stream_list, stream_node)
328 {
329 if (stream->is_metadata) {
330 trace_has_metadata_stream = true;
331 break;
332 }
333 }
334
335 /*
336 * If there is no metadata stream in this trace at the moment
337 * and we never sent one to the viewer, skip the trace. We
338 * accept that the viewer will not see this trace at all.
339 */
340 if (!trace_has_metadata_stream &&
341 !ctf_trace->metadata_stream_sent_to_viewer) {
342 ctf_trace_put(ctf_trace);
343 continue;
344 }
345
346 cds_list_for_each_entry_rcu(stream, &ctf_trace->stream_list, stream_node) {
347 struct relay_viewer_stream *vstream;
348
349 if (!stream_get(stream)) {
350 continue;
351 }
352 /*
353 * stream published is protected by the session lock.
354 */
355 if (!stream->published) {
356 goto next;
357 }
358 vstream = viewer_stream_get_by_id(stream->stream_handle);
359 if (!vstream) {
360 /*
361 * Save that we sent the metadata stream to the
362 * viewer. So that we know what trace the viewer
363 * is aware of.
364 */
365 if (stream->is_metadata) {
366 ctf_trace->metadata_stream_sent_to_viewer =
367 true;
368 }
369 vstream = viewer_stream_create(stream,
370 viewer_trace_chunk, seek_t);
371 if (!vstream) {
372 ret = -1;
373 ctf_trace_put(ctf_trace);
374 stream_put(stream);
375 goto error_unlock;
376 }
377
378 if (nb_created) {
379 /* Update number of created stream counter. */
380 (*nb_created)++;
381 }
382 /*
383 * Ensure a self-reference is preserved even
384 * after we have put our local reference.
385 */
386 if (!viewer_stream_get(vstream)) {
387 ERR("Unable to get self-reference on viewer stream, logic error.");
388 abort();
389 }
390 } else {
391 if (!vstream->sent_flag && nb_unsent) {
392 /* Update number of unsent stream counter. */
393 (*nb_unsent)++;
394 }
395 }
396 /* Update number of total stream counter. */
397 if (nb_total) {
398 if (stream->is_metadata) {
399 if (!stream->closed ||
400 stream->metadata_received > vstream->metadata_sent) {
401 (*nb_total)++;
402 }
403 } else {
404 if (!stream->closed ||
405 !(((int64_t) (stream->prev_data_seq - stream->last_net_seq_num)) >= 0)) {
406
407 (*nb_total)++;
408 }
409 }
410 }
411 /* Put local reference. */
412 viewer_stream_put(vstream);
413 next:
414 stream_put(stream);
415 }
416 ctf_trace_put(ctf_trace);
417 }
418
419 ret = 0;
420
421 error_unlock:
422 rcu_read_unlock();
423 error:
424 return ret;
425 }
426
427 int relayd_live_stop(void)
428 {
429 /* Stop dispatch thread */
430 CMM_STORE_SHARED(live_dispatch_thread_exit, 1);
431 futex_nto1_wake(&viewer_conn_queue.futex);
432 return 0;
433 }
434
435 /*
436 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
437 */
438 static
439 int create_named_thread_poll_set(struct lttng_poll_event *events,
440 int size, const char *name)
441 {
442 int ret;
443
444 if (events == NULL || size == 0) {
445 ret = -1;
446 goto error;
447 }
448
449 ret = fd_tracker_util_poll_create(the_fd_tracker,
450 name, events, 1, LTTNG_CLOEXEC);
451
452 /* Add quit pipe */
453 ret = lttng_poll_add(events, thread_quit_pipe[0], LPOLLIN | LPOLLERR);
454 if (ret < 0) {
455 goto error;
456 }
457
458 return 0;
459
460 error:
461 return ret;
462 }
463
464 /*
465 * Check if the thread quit pipe was triggered.
466 *
467 * Return 1 if it was triggered else 0;
468 */
469 static
470 int check_thread_quit_pipe(int fd, uint32_t events)
471 {
472 if (fd == thread_quit_pipe[0] && (events & LPOLLIN)) {
473 return 1;
474 }
475
476 return 0;
477 }
478
479 static
480 int create_sock(void *data, int *out_fd)
481 {
482 int ret;
483 struct lttcomm_sock *sock = data;
484
485 ret = lttcomm_create_sock(sock);
486 if (ret < 0) {
487 goto end;
488 }
489
490 *out_fd = sock->fd;
491 end:
492 return ret;
493 }
494
495 static
496 int close_sock(void *data, int *in_fd)
497 {
498 struct lttcomm_sock *sock = data;
499
500 return sock->ops->close(sock);
501 }
502
503 static int accept_sock(void *data, int *out_fd)
504 {
505 int ret = 0;
506 /* Socks is an array of in_sock, out_sock. */
507 struct lttcomm_sock **socks = data;
508 struct lttcomm_sock *in_sock = socks[0];
509
510 socks[1] = in_sock->ops->accept(in_sock);
511 if (!socks[1]) {
512 ret = -1;
513 goto end;
514 }
515 *out_fd = socks[1]->fd;
516 end:
517 return ret;
518 }
519
520 static
521 struct lttcomm_sock *accept_live_sock(struct lttcomm_sock *listening_sock,
522 const char *name)
523 {
524 int out_fd, ret;
525 struct lttcomm_sock *socks[2] = { listening_sock, NULL };
526 struct lttcomm_sock *new_sock = NULL;
527
528 ret = fd_tracker_open_unsuspendable_fd(the_fd_tracker, &out_fd,
529 (const char **) &name, 1, accept_sock, &socks);
530 if (ret) {
531 goto end;
532 }
533 new_sock = socks[1];
534 DBG("%s accepted, socket %d", name, new_sock->fd);
535 end:
536 return new_sock;
537 }
538
539 /*
540 * Create and init socket from uri.
541 */
542 static
543 struct lttcomm_sock *init_socket(struct lttng_uri *uri, const char *name)
544 {
545 int ret, sock_fd;
546 struct lttcomm_sock *sock = NULL;
547 char uri_str[LTTNG_PATH_MAX];
548 char *formated_name = NULL;
549
550 sock = lttcomm_alloc_sock_from_uri(uri);
551 if (sock == NULL) {
552 ERR("Allocating socket");
553 goto error;
554 }
555
556 /*
557 * Don't fail to create the socket if the name can't be built as it is
558 * only used for debugging purposes.
559 */
560 ret = uri_to_str_url(uri, uri_str, sizeof(uri_str));
561 uri_str[sizeof(uri_str) - 1] = '\0';
562 if (ret >= 0) {
563 ret = asprintf(&formated_name, "%s socket @ %s", name,
564 uri_str);
565 if (ret < 0) {
566 formated_name = NULL;
567 }
568 }
569
570 ret = fd_tracker_open_unsuspendable_fd(the_fd_tracker, &sock_fd,
571 (const char **) (formated_name ? &formated_name : NULL),
572 1, create_sock, sock);
573 free(formated_name);
574 DBG("Listening on %s socket %d", name, sock->fd);
575
576 ret = sock->ops->bind(sock);
577 if (ret < 0) {
578 PERROR("Failed to bind lttng-live socket");
579 goto error;
580 }
581
582 ret = sock->ops->listen(sock, -1);
583 if (ret < 0) {
584 goto error;
585
586 }
587
588 return sock;
589
590 error:
591 if (sock) {
592 lttcomm_destroy_sock(sock);
593 }
594 return NULL;
595 }
596
597 /*
598 * This thread manages the listening for new connections on the network
599 */
600 static
601 void *thread_listener(void *data)
602 {
603 int i, ret, pollfd, err = -1;
604 uint32_t revents, nb_fd;
605 struct lttng_poll_event events;
606 struct lttcomm_sock *live_control_sock;
607
608 DBG("[thread] Relay live listener started");
609
610 health_register(health_relayd, HEALTH_RELAYD_TYPE_LIVE_LISTENER);
611
612 health_code_update();
613
614 live_control_sock = init_socket(live_uri, "Live listener");
615 if (!live_control_sock) {
616 goto error_sock_control;
617 }
618
619 /* Pass 2 as size here for the thread quit pipe and control sockets. */
620 ret = create_named_thread_poll_set(&events, 2,
621 "Live listener thread epoll");
622 if (ret < 0) {
623 goto error_create_poll;
624 }
625
626 /* Add the control socket */
627 ret = lttng_poll_add(&events, live_control_sock->fd, LPOLLIN | LPOLLRDHUP);
628 if (ret < 0) {
629 goto error_poll_add;
630 }
631
632 lttng_relay_notify_ready();
633
634 if (testpoint(relayd_thread_live_listener)) {
635 goto error_testpoint;
636 }
637
638 while (1) {
639 health_code_update();
640
641 DBG("Listener accepting live viewers connections");
642
643 restart:
644 health_poll_entry();
645 ret = lttng_poll_wait(&events, -1);
646 health_poll_exit();
647 if (ret < 0) {
648 /*
649 * Restart interrupted system call.
650 */
651 if (errno == EINTR) {
652 goto restart;
653 }
654 goto error;
655 }
656 nb_fd = ret;
657
658 DBG("Relay new viewer connection received");
659 for (i = 0; i < nb_fd; i++) {
660 health_code_update();
661
662 /* Fetch once the poll data */
663 revents = LTTNG_POLL_GETEV(&events, i);
664 pollfd = LTTNG_POLL_GETFD(&events, i);
665
666 /* Thread quit pipe has been closed. Killing thread. */
667 ret = check_thread_quit_pipe(pollfd, revents);
668 if (ret) {
669 err = 0;
670 goto exit;
671 }
672
673 if (revents & LPOLLIN) {
674 /*
675 * A new connection is requested, therefore a
676 * viewer connection is allocated in this
677 * thread, enqueued to a global queue and
678 * dequeued (and freed) in the worker thread.
679 */
680 int val = 1;
681 struct relay_connection *new_conn;
682 struct lttcomm_sock *newsock;
683
684 newsock = accept_live_sock(live_control_sock,
685 "Live socket to client");
686 if (!newsock) {
687 PERROR("accepting control sock");
688 goto error;
689 }
690 DBG("Relay viewer connection accepted socket %d", newsock->fd);
691
692 ret = setsockopt(newsock->fd, SOL_SOCKET, SO_REUSEADDR, &val,
693 sizeof(val));
694 if (ret < 0) {
695 PERROR("setsockopt inet");
696 lttcomm_destroy_sock(newsock);
697 goto error;
698 }
699 new_conn = connection_create(newsock, RELAY_CONNECTION_UNKNOWN);
700 if (!new_conn) {
701 lttcomm_destroy_sock(newsock);
702 goto error;
703 }
704 /* Ownership assumed by the connection. */
705 newsock = NULL;
706
707 /* Enqueue request for the dispatcher thread. */
708 cds_wfcq_enqueue(&viewer_conn_queue.head, &viewer_conn_queue.tail,
709 &new_conn->qnode);
710
711 /*
712 * Wake the dispatch queue futex.
713 * Implicit memory barrier with the
714 * exchange in cds_wfcq_enqueue.
715 */
716 futex_nto1_wake(&viewer_conn_queue.futex);
717 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
718 ERR("socket poll error");
719 goto error;
720 } else {
721 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
722 goto error;
723 }
724 }
725 }
726
727 exit:
728 error:
729 error_poll_add:
730 error_testpoint:
731 (void) fd_tracker_util_poll_clean(the_fd_tracker, &events);
732 error_create_poll:
733 if (live_control_sock->fd >= 0) {
734 int sock_fd = live_control_sock->fd;
735
736 ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker,
737 &sock_fd, 1, close_sock,
738 live_control_sock);
739 if (ret) {
740 PERROR("close");
741 }
742 live_control_sock->fd = -1;
743 }
744 lttcomm_destroy_sock(live_control_sock);
745 error_sock_control:
746 if (err) {
747 health_error();
748 DBG("Live viewer listener thread exited with error");
749 }
750 health_unregister(health_relayd);
751 DBG("Live viewer listener thread cleanup complete");
752 if (lttng_relay_stop_threads()) {
753 ERR("Error stopping threads");
754 }
755 return NULL;
756 }
757
758 /*
759 * This thread manages the dispatching of the requests to worker threads
760 */
761 static
762 void *thread_dispatcher(void *data)
763 {
764 int err = -1;
765 ssize_t ret;
766 struct cds_wfcq_node *node;
767 struct relay_connection *conn = NULL;
768
769 DBG("[thread] Live viewer relay dispatcher started");
770
771 health_register(health_relayd, HEALTH_RELAYD_TYPE_LIVE_DISPATCHER);
772
773 if (testpoint(relayd_thread_live_dispatcher)) {
774 goto error_testpoint;
775 }
776
777 health_code_update();
778
779 for (;;) {
780 health_code_update();
781
782 /* Atomically prepare the queue futex */
783 futex_nto1_prepare(&viewer_conn_queue.futex);
784
785 if (CMM_LOAD_SHARED(live_dispatch_thread_exit)) {
786 break;
787 }
788
789 do {
790 health_code_update();
791
792 /* Dequeue commands */
793 node = cds_wfcq_dequeue_blocking(&viewer_conn_queue.head,
794 &viewer_conn_queue.tail);
795 if (node == NULL) {
796 DBG("Woken up but nothing in the live-viewer "
797 "relay command queue");
798 /* Continue thread execution */
799 break;
800 }
801 conn = caa_container_of(node, struct relay_connection, qnode);
802 DBG("Dispatching viewer request waiting on sock %d",
803 conn->sock->fd);
804
805 /*
806 * Inform worker thread of the new request. This
807 * call is blocking so we can be assured that
808 * the data will be read at some point in time
809 * or wait to the end of the world :)
810 */
811 ret = lttng_write(live_conn_pipe[1], &conn, sizeof(conn));
812 if (ret < 0) {
813 PERROR("write conn pipe");
814 connection_put(conn);
815 goto error;
816 }
817 } while (node != NULL);
818
819 /* Futex wait on queue. Blocking call on futex() */
820 health_poll_entry();
821 futex_nto1_wait(&viewer_conn_queue.futex);
822 health_poll_exit();
823 }
824
825 /* Normal exit, no error */
826 err = 0;
827
828 error:
829 error_testpoint:
830 if (err) {
831 health_error();
832 ERR("Health error occurred in %s", __func__);
833 }
834 health_unregister(health_relayd);
835 DBG("Live viewer dispatch thread dying");
836 if (lttng_relay_stop_threads()) {
837 ERR("Error stopping threads");
838 }
839 return NULL;
840 }
841
842 /*
843 * Establish connection with the viewer and check the versions.
844 *
845 * Return 0 on success or else negative value.
846 */
847 static
848 int viewer_connect(struct relay_connection *conn)
849 {
850 int ret;
851 struct lttng_viewer_connect reply, msg;
852
853 conn->version_check_done = 1;
854
855 health_code_update();
856
857 DBG("Viewer is establishing a connection to the relayd.");
858
859 ret = recv_request(conn->sock, &msg, sizeof(msg));
860 if (ret < 0) {
861 goto end;
862 }
863
864 health_code_update();
865
866 memset(&reply, 0, sizeof(reply));
867 reply.major = RELAYD_VERSION_COMM_MAJOR;
868 reply.minor = RELAYD_VERSION_COMM_MINOR;
869
870 /* Major versions must be the same */
871 if (reply.major != be32toh(msg.major)) {
872 DBG("Incompatible major versions ([relayd] %u vs [client] %u)",
873 reply.major, be32toh(msg.major));
874 ret = -1;
875 goto end;
876 }
877
878 conn->major = reply.major;
879 /* We adapt to the lowest compatible version */
880 if (reply.minor <= be32toh(msg.minor)) {
881 conn->minor = reply.minor;
882 } else {
883 conn->minor = be32toh(msg.minor);
884 }
885
886 if (be32toh(msg.type) == LTTNG_VIEWER_CLIENT_COMMAND) {
887 conn->type = RELAY_VIEWER_COMMAND;
888 } else if (be32toh(msg.type) == LTTNG_VIEWER_CLIENT_NOTIFICATION) {
889 conn->type = RELAY_VIEWER_NOTIFICATION;
890 } else {
891 ERR("Unknown connection type : %u", be32toh(msg.type));
892 ret = -1;
893 goto end;
894 }
895
896 reply.major = htobe32(reply.major);
897 reply.minor = htobe32(reply.minor);
898 if (conn->type == RELAY_VIEWER_COMMAND) {
899 /*
900 * Increment outside of htobe64 macro, because the argument can
901 * be used more than once within the macro, and thus the
902 * operation may be undefined.
903 */
904 pthread_mutex_lock(&last_relay_viewer_session_id_lock);
905 last_relay_viewer_session_id++;
906 pthread_mutex_unlock(&last_relay_viewer_session_id_lock);
907 reply.viewer_session_id = htobe64(last_relay_viewer_session_id);
908 }
909
910 health_code_update();
911
912 ret = send_response(conn->sock, &reply, sizeof(reply));
913 if (ret < 0) {
914 goto end;
915 }
916
917 health_code_update();
918
919 DBG("Version check done using protocol %u.%u", conn->major, conn->minor);
920 ret = 0;
921
922 end:
923 return ret;
924 }
925
926 /*
927 * Send the viewer the list of current sessions.
928 * We need to create a copy of the hash table content because otherwise
929 * we cannot assume the number of entries stays the same between getting
930 * the number of HT elements and iteration over the HT.
931 *
932 * Return 0 on success or else a negative value.
933 */
934 static
935 int viewer_list_sessions(struct relay_connection *conn)
936 {
937 int ret = 0;
938 struct lttng_viewer_list_sessions session_list;
939 struct lttng_ht_iter iter;
940 struct relay_session *session;
941 struct lttng_viewer_session *send_session_buf = NULL;
942 uint32_t buf_count = SESSION_BUF_DEFAULT_COUNT;
943 uint32_t count = 0;
944
945 DBG("List sessions received");
946
947 send_session_buf = zmalloc(SESSION_BUF_DEFAULT_COUNT * sizeof(*send_session_buf));
948 if (!send_session_buf) {
949 return -1;
950 }
951
952 rcu_read_lock();
953 cds_lfht_for_each_entry(sessions_ht->ht, &iter.iter, session,
954 session_n.node) {
955 struct lttng_viewer_session *send_session;
956
957 health_code_update();
958
959 pthread_mutex_lock(&session->lock);
960 if (session->connection_closed) {
961 /* Skip closed session */
962 goto next_session;
963 }
964 if (!session->current_trace_chunk) {
965 /*
966 * Skip un-attachable session. It is either
967 * being destroyed or has not had a trace
968 * chunk created against it yet.
969 */
970 goto next_session;
971 }
972
973 if (count >= buf_count) {
974 struct lttng_viewer_session *newbuf;
975 uint32_t new_buf_count = buf_count << 1;
976
977 newbuf = realloc(send_session_buf,
978 new_buf_count * sizeof(*send_session_buf));
979 if (!newbuf) {
980 ret = -1;
981 goto break_loop;
982 }
983 send_session_buf = newbuf;
984 buf_count = new_buf_count;
985 }
986 send_session = &send_session_buf[count];
987 if (lttng_strncpy(send_session->session_name,
988 session->session_name,
989 sizeof(send_session->session_name))) {
990 ret = -1;
991 goto break_loop;
992 }
993 if (lttng_strncpy(send_session->hostname, session->hostname,
994 sizeof(send_session->hostname))) {
995 ret = -1;
996 goto break_loop;
997 }
998 send_session->id = htobe64(session->id);
999 send_session->live_timer = htobe32(session->live_timer);
1000 if (session->viewer_attached) {
1001 send_session->clients = htobe32(1);
1002 } else {
1003 send_session->clients = htobe32(0);
1004 }
1005 send_session->streams = htobe32(session->stream_count);
1006 count++;
1007 next_session:
1008 pthread_mutex_unlock(&session->lock);
1009 continue;
1010 break_loop:
1011 pthread_mutex_unlock(&session->lock);
1012 break;
1013 }
1014 rcu_read_unlock();
1015 if (ret < 0) {
1016 goto end_free;
1017 }
1018
1019 session_list.sessions_count = htobe32(count);
1020
1021 health_code_update();
1022
1023 ret = send_response(conn->sock, &session_list, sizeof(session_list));
1024 if (ret < 0) {
1025 goto end_free;
1026 }
1027
1028 health_code_update();
1029
1030 ret = send_response(conn->sock, send_session_buf,
1031 count * sizeof(*send_session_buf));
1032 if (ret < 0) {
1033 goto end_free;
1034 }
1035 health_code_update();
1036
1037 ret = 0;
1038 end_free:
1039 free(send_session_buf);
1040 return ret;
1041 }
1042
1043 /*
1044 * Send the viewer the list of current streams.
1045 */
1046 static
1047 int viewer_get_new_streams(struct relay_connection *conn)
1048 {
1049 int ret, send_streams = 0;
1050 uint32_t nb_created = 0, nb_unsent = 0, nb_streams = 0, nb_total = 0;
1051 struct lttng_viewer_new_streams_request request;
1052 struct lttng_viewer_new_streams_response response;
1053 struct relay_session *session = NULL;
1054 uint64_t session_id;
1055 bool closed = false;
1056
1057 assert(conn);
1058
1059 DBG("Get new streams received");
1060
1061 health_code_update();
1062
1063 /* Receive the request from the connected client. */
1064 ret = recv_request(conn->sock, &request, sizeof(request));
1065 if (ret < 0) {
1066 goto error;
1067 }
1068 session_id = be64toh(request.session_id);
1069
1070 health_code_update();
1071
1072 memset(&response, 0, sizeof(response));
1073
1074 session = session_get_by_id(session_id);
1075 if (!session) {
1076 DBG("Relay session %" PRIu64 " not found", session_id);
1077 response.status = htobe32(LTTNG_VIEWER_NEW_STREAMS_ERR);
1078 goto send_reply;
1079 }
1080
1081 if (!viewer_session_is_attached(conn->viewer_session, session)) {
1082 response.status = htobe32(LTTNG_VIEWER_NEW_STREAMS_ERR);
1083 goto send_reply;
1084 }
1085
1086 pthread_mutex_lock(&session->lock);
1087 ret = make_viewer_streams(session,
1088 conn->viewer_session->current_trace_chunk,
1089 LTTNG_VIEWER_SEEK_LAST, &nb_total, &nb_unsent,
1090 &nb_created, &closed);
1091 if (ret < 0) {
1092 goto error_unlock_session;
1093 }
1094 send_streams = 1;
1095 response.status = htobe32(LTTNG_VIEWER_NEW_STREAMS_OK);
1096
1097 /* Only send back the newly created streams with the unsent ones. */
1098 nb_streams = nb_created + nb_unsent;
1099 response.streams_count = htobe32(nb_streams);
1100
1101 /*
1102 * If the session is closed, HUP when there are no more streams
1103 * with data.
1104 */
1105 if (closed && nb_total == 0) {
1106 send_streams = 0;
1107 response.streams_count = 0;
1108 response.status = htobe32(LTTNG_VIEWER_NEW_STREAMS_HUP);
1109 goto send_reply_unlock;
1110 }
1111 send_reply_unlock:
1112 pthread_mutex_unlock(&session->lock);
1113
1114 send_reply:
1115 health_code_update();
1116 ret = send_response(conn->sock, &response, sizeof(response));
1117 if (ret < 0) {
1118 goto end_put_session;
1119 }
1120 health_code_update();
1121
1122 /*
1123 * Unknown or empty session, just return gracefully, the viewer
1124 * knows what is happening.
1125 */
1126 if (!send_streams || !nb_streams) {
1127 ret = 0;
1128 goto end_put_session;
1129 }
1130
1131 /*
1132 * Send stream and *DON'T* ignore the sent flag so every viewer
1133 * streams that were not sent from that point will be sent to
1134 * the viewer.
1135 */
1136 ret = send_viewer_streams(conn->sock, session_id, 0);
1137 if (ret < 0) {
1138 goto end_put_session;
1139 }
1140
1141 end_put_session:
1142 if (session) {
1143 session_put(session);
1144 }
1145 error:
1146 return ret;
1147 error_unlock_session:
1148 pthread_mutex_unlock(&session->lock);
1149 session_put(session);
1150 return ret;
1151 }
1152
1153 /*
1154 * Send the viewer the list of current sessions.
1155 */
1156 static
1157 int viewer_attach_session(struct relay_connection *conn)
1158 {
1159 int send_streams = 0;
1160 ssize_t ret;
1161 uint32_t nb_streams = 0;
1162 enum lttng_viewer_seek seek_type;
1163 struct lttng_viewer_attach_session_request request;
1164 struct lttng_viewer_attach_session_response response;
1165 struct relay_session *session = NULL;
1166 enum lttng_viewer_attach_return_code viewer_attach_status;
1167 bool closed = false;
1168 uint64_t session_id;
1169
1170 assert(conn);
1171
1172 health_code_update();
1173
1174 /* Receive the request from the connected client. */
1175 ret = recv_request(conn->sock, &request, sizeof(request));
1176 if (ret < 0) {
1177 goto error;
1178 }
1179
1180 session_id = be64toh(request.session_id);
1181 health_code_update();
1182
1183 memset(&response, 0, sizeof(response));
1184
1185 if (!conn->viewer_session) {
1186 DBG("Client trying to attach before creating a live viewer session");
1187 response.status = htobe32(LTTNG_VIEWER_ATTACH_NO_SESSION);
1188 goto send_reply;
1189 }
1190
1191 session = session_get_by_id(session_id);
1192 if (!session) {
1193 DBG("Relay session %" PRIu64 " not found", session_id);
1194 response.status = htobe32(LTTNG_VIEWER_ATTACH_UNK);
1195 goto send_reply;
1196 }
1197 DBG("Attach session ID %" PRIu64 " received", session_id);
1198
1199 pthread_mutex_lock(&session->lock);
1200 if (!session->current_trace_chunk) {
1201 /*
1202 * Session is either being destroyed or it never had a trace
1203 * chunk created against it.
1204 */
1205 DBG("Session requested by live client has no current trace chunk, returning unknown session");
1206 response.status = htobe32(LTTNG_VIEWER_ATTACH_UNK);
1207 goto send_reply;
1208 }
1209 if (session->live_timer == 0) {
1210 DBG("Not live session");
1211 response.status = htobe32(LTTNG_VIEWER_ATTACH_NOT_LIVE);
1212 goto send_reply;
1213 }
1214
1215 send_streams = 1;
1216 viewer_attach_status = viewer_session_attach(conn->viewer_session,
1217 session);
1218 if (viewer_attach_status != LTTNG_VIEWER_ATTACH_OK) {
1219 response.status = htobe32(viewer_attach_status);
1220 goto send_reply;
1221 }
1222
1223 switch (be32toh(request.seek)) {
1224 case LTTNG_VIEWER_SEEK_BEGINNING:
1225 case LTTNG_VIEWER_SEEK_LAST:
1226 response.status = htobe32(LTTNG_VIEWER_ATTACH_OK);
1227 seek_type = be32toh(request.seek);
1228 break;
1229 default:
1230 ERR("Wrong seek parameter");
1231 response.status = htobe32(LTTNG_VIEWER_ATTACH_SEEK_ERR);
1232 send_streams = 0;
1233 goto send_reply;
1234 }
1235
1236 ret = make_viewer_streams(session,
1237 conn->viewer_session->current_trace_chunk, seek_type,
1238 &nb_streams, NULL, NULL, &closed);
1239 if (ret < 0) {
1240 goto end_put_session;
1241 }
1242 pthread_mutex_unlock(&session->lock);
1243 session_put(session);
1244 session = NULL;
1245
1246 response.streams_count = htobe32(nb_streams);
1247 /*
1248 * If the session is closed when the viewer is attaching, it
1249 * means some of the streams may have been concurrently removed,
1250 * so we don't allow the viewer to attach, even if there are
1251 * streams available.
1252 */
1253 if (closed) {
1254 send_streams = 0;
1255 response.streams_count = 0;
1256 response.status = htobe32(LTTNG_VIEWER_ATTACH_UNK);
1257 goto send_reply;
1258 }
1259
1260 send_reply:
1261 health_code_update();
1262 ret = send_response(conn->sock, &response, sizeof(response));
1263 if (ret < 0) {
1264 goto end_put_session;
1265 }
1266 health_code_update();
1267
1268 /*
1269 * Unknown or empty session, just return gracefully, the viewer
1270 * knows what is happening.
1271 */
1272 if (!send_streams || !nb_streams) {
1273 ret = 0;
1274 goto end_put_session;
1275 }
1276
1277 /* Send stream and ignore the sent flag. */
1278 ret = send_viewer_streams(conn->sock, session_id, 1);
1279 if (ret < 0) {
1280 goto end_put_session;
1281 }
1282
1283 end_put_session:
1284 if (session) {
1285 pthread_mutex_unlock(&session->lock);
1286 session_put(session);
1287 }
1288 error:
1289 return ret;
1290 }
1291
1292 /*
1293 * Open the index file if needed for the given vstream.
1294 *
1295 * If an index file is successfully opened, the vstream will set it as its
1296 * current index file.
1297 *
1298 * Return 0 on success, a negative value on error (-ENOENT if not ready yet).
1299 *
1300 * Called with rstream lock held.
1301 */
1302 static int try_open_index(struct relay_viewer_stream *vstream,
1303 struct relay_stream *rstream)
1304 {
1305 int ret = 0;
1306 const uint32_t connection_major = rstream->trace->session->major;
1307 const uint32_t connection_minor = rstream->trace->session->minor;
1308 enum lttng_trace_chunk_status chunk_status;
1309
1310 if (vstream->index_file) {
1311 goto end;
1312 }
1313
1314 /*
1315 * First time, we open the index file and at least one index is ready.
1316 */
1317 if (rstream->index_received_seqcount == 0) {
1318 ret = -ENOENT;
1319 goto end;
1320 }
1321 chunk_status = lttng_index_file_create_from_trace_chunk_read_only(
1322 vstream->stream_file.trace_chunk, rstream->path_name,
1323 rstream->channel_name, rstream->tracefile_size,
1324 vstream->current_tracefile_id,
1325 lttng_to_index_major(connection_major, connection_minor),
1326 lttng_to_index_minor(connection_major, connection_minor),
1327 true, &vstream->index_file);
1328 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
1329 if (chunk_status == LTTNG_TRACE_CHUNK_STATUS_NO_FILE) {
1330 ret = -ENOENT;
1331 } else {
1332 ret = -1;
1333 }
1334 }
1335
1336 end:
1337 return ret;
1338 }
1339
1340 /*
1341 * Check the status of the index for the given stream. This function
1342 * updates the index structure if needed and can put (close) the vstream
1343 * in the HUP situation.
1344 *
1345 * Return 0 means that we can proceed with the index. A value of 1 means
1346 * that the index has been updated and is ready to be sent to the
1347 * client. A negative value indicates an error that can't be handled.
1348 *
1349 * Called with rstream lock held.
1350 */
1351 static int check_index_status(struct relay_viewer_stream *vstream,
1352 struct relay_stream *rstream, struct ctf_trace *trace,
1353 struct lttng_viewer_index *index)
1354 {
1355 int ret;
1356
1357 DBG("Check index status: index_received_seqcount %" PRIu64 " "
1358 "index_sent_seqcount %" PRIu64 " "
1359 "for stream %" PRIu64,
1360 rstream->index_received_seqcount,
1361 vstream->index_sent_seqcount,
1362 vstream->stream->stream_handle);
1363 if ((trace->session->connection_closed || rstream->closed)
1364 && rstream->index_received_seqcount
1365 == vstream->index_sent_seqcount) {
1366 /*
1367 * Last index sent and session connection or relay
1368 * stream are closed.
1369 */
1370 index->status = htobe32(LTTNG_VIEWER_INDEX_HUP);
1371 goto hup;
1372 } else if (rstream->beacon_ts_end != -1ULL &&
1373 (rstream->index_received_seqcount == 0 ||
1374 (vstream->index_sent_seqcount != 0 &&
1375 rstream->index_received_seqcount
1376 <= vstream->index_sent_seqcount))) {
1377 /*
1378 * We've received a synchronization beacon and the last index
1379 * available has been sent, the index for now is inactive.
1380 *
1381 * In this case, we have received a beacon which allows us to
1382 * inform the client of a time interval during which we can
1383 * guarantee that there are no events to read (and never will
1384 * be).
1385 *
1386 * The sent seqcount can grow higher than receive seqcount on
1387 * clear because the rotation performed by clear will push
1388 * the index_sent_seqcount ahead (see
1389 * viewer_stream_sync_tracefile_array_tail) and skip over
1390 * packet sequence numbers.
1391 */
1392 index->status = htobe32(LTTNG_VIEWER_INDEX_INACTIVE);
1393 index->timestamp_end = htobe64(rstream->beacon_ts_end);
1394 index->stream_id = htobe64(rstream->ctf_stream_id);
1395 DBG("Check index status: inactive with beacon, for stream %" PRIu64,
1396 vstream->stream->stream_handle);
1397 goto index_ready;
1398 } else if (rstream->index_received_seqcount == 0 ||
1399 (vstream->index_sent_seqcount != 0 &&
1400 rstream->index_received_seqcount
1401 <= vstream->index_sent_seqcount)) {
1402 /*
1403 * This checks whether received <= sent seqcount. In
1404 * this case, we have not received a beacon. Therefore,
1405 * we can only ask the client to retry later.
1406 *
1407 * The sent seqcount can grow higher than receive seqcount on
1408 * clear because the rotation performed by clear will push
1409 * the index_sent_seqcount ahead (see
1410 * viewer_stream_sync_tracefile_array_tail) and skip over
1411 * packet sequence numbers.
1412 */
1413 index->status = htobe32(LTTNG_VIEWER_INDEX_RETRY);
1414 DBG("Check index status: retry for stream %" PRIu64,
1415 vstream->stream->stream_handle);
1416 goto index_ready;
1417 } else if (!tracefile_array_seq_in_file(rstream->tfa,
1418 vstream->current_tracefile_id,
1419 vstream->index_sent_seqcount)) {
1420 /*
1421 * The next index we want to send cannot be read either
1422 * because we need to perform a rotation, or due to
1423 * the producer having overwritten its trace file.
1424 */
1425 DBG("Viewer stream %" PRIu64 " rotation",
1426 vstream->stream->stream_handle);
1427 ret = viewer_stream_rotate(vstream);
1428 if (ret == 1) {
1429 /* EOF across entire stream. */
1430 index->status = htobe32(LTTNG_VIEWER_INDEX_HUP);
1431 goto hup;
1432 }
1433 /*
1434 * If we have been pushed due to overwrite, it
1435 * necessarily means there is data that can be read in
1436 * the stream. If we rotated because we reached the end
1437 * of a tracefile, it means the following tracefile
1438 * needs to contain at least one index, else we would
1439 * have already returned LTTNG_VIEWER_INDEX_RETRY to the
1440 * viewer. The updated index_sent_seqcount needs to
1441 * point to a readable index entry now.
1442 *
1443 * In the case where we "rotate" on a single file, we
1444 * can end up in a case where the requested index is
1445 * still unavailable.
1446 */
1447 if (rstream->tracefile_count == 1 &&
1448 !tracefile_array_seq_in_file(
1449 rstream->tfa,
1450 vstream->current_tracefile_id,
1451 vstream->index_sent_seqcount)) {
1452 index->status = htobe32(LTTNG_VIEWER_INDEX_RETRY);
1453 DBG("Check index status: retry: "
1454 "tracefile array sequence number %" PRIu64
1455 " not in file for stream %" PRIu64,
1456 vstream->index_sent_seqcount,
1457 vstream->stream->stream_handle);
1458 goto index_ready;
1459 }
1460 assert(tracefile_array_seq_in_file(rstream->tfa,
1461 vstream->current_tracefile_id,
1462 vstream->index_sent_seqcount));
1463 }
1464 /* ret == 0 means successful so we continue. */
1465 ret = 0;
1466 return ret;
1467
1468 hup:
1469 viewer_stream_put(vstream);
1470 index_ready:
1471 return 1;
1472 }
1473
1474 /*
1475 * Send the next index for a stream.
1476 *
1477 * Return 0 on success or else a negative value.
1478 */
1479 static
1480 int viewer_get_next_index(struct relay_connection *conn)
1481 {
1482 int ret;
1483 struct lttng_viewer_get_next_index request_index;
1484 struct lttng_viewer_index viewer_index;
1485 struct ctf_packet_index packet_index;
1486 struct relay_viewer_stream *vstream = NULL;
1487 struct relay_stream *rstream = NULL;
1488 struct ctf_trace *ctf_trace = NULL;
1489 struct relay_viewer_stream *metadata_viewer_stream = NULL;
1490
1491 assert(conn);
1492
1493 DBG("Viewer get next index");
1494
1495 memset(&viewer_index, 0, sizeof(viewer_index));
1496 health_code_update();
1497
1498 ret = recv_request(conn->sock, &request_index, sizeof(request_index));
1499 if (ret < 0) {
1500 goto end;
1501 }
1502 health_code_update();
1503
1504 vstream = viewer_stream_get_by_id(be64toh(request_index.stream_id));
1505 if (!vstream) {
1506 DBG("Client requested index of unknown stream id %" PRIu64,
1507 (uint64_t) be64toh(request_index.stream_id));
1508 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_ERR);
1509 goto send_reply;
1510 }
1511
1512 /* Use back. ref. Protected by refcounts. */
1513 rstream = vstream->stream;
1514 ctf_trace = rstream->trace;
1515
1516 /* metadata_viewer_stream may be NULL. */
1517 metadata_viewer_stream =
1518 ctf_trace_get_viewer_metadata_stream(ctf_trace);
1519
1520 pthread_mutex_lock(&rstream->lock);
1521
1522 /*
1523 * The viewer should not ask for index on metadata stream.
1524 */
1525 if (rstream->is_metadata) {
1526 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_HUP);
1527 goto send_reply;
1528 }
1529
1530 if (rstream->ongoing_rotation.is_set) {
1531 /* Rotation is ongoing, try again later. */
1532 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_RETRY);
1533 goto send_reply;
1534 }
1535
1536 if (rstream->trace->session->ongoing_rotation) {
1537 /* Rotation is ongoing, try again later. */
1538 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_RETRY);
1539 goto send_reply;
1540 }
1541
1542 if (rstream->trace_chunk) {
1543 uint64_t rchunk_id, vchunk_id;
1544
1545 /*
1546 * If the relay stream is not yet closed, ensure the viewer
1547 * chunk matches the relay chunk after clear.
1548 */
1549 if (lttng_trace_chunk_get_id(rstream->trace_chunk,
1550 &rchunk_id) != LTTNG_TRACE_CHUNK_STATUS_OK) {
1551 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_ERR);
1552 goto send_reply;
1553 }
1554 if (lttng_trace_chunk_get_id(
1555 conn->viewer_session->current_trace_chunk,
1556 &vchunk_id) != LTTNG_TRACE_CHUNK_STATUS_OK) {
1557 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_ERR);
1558 goto send_reply;
1559 }
1560
1561 if (rchunk_id != vchunk_id) {
1562 DBG("Relay and viewer chunk ids differ: "
1563 "rchunk_id %" PRIu64 " vchunk_id %" PRIu64,
1564 rchunk_id, vchunk_id);
1565
1566 lttng_trace_chunk_put(
1567 conn->viewer_session->current_trace_chunk);
1568 conn->viewer_session->current_trace_chunk = NULL;
1569 ret = viewer_session_set_trace_chunk_copy(
1570 conn->viewer_session,
1571 rstream->trace_chunk);
1572 if (ret) {
1573 viewer_index.status =
1574 htobe32(LTTNG_VIEWER_INDEX_ERR);
1575 goto send_reply;
1576 }
1577 }
1578 }
1579 if (conn->viewer_session->current_trace_chunk !=
1580 vstream->stream_file.trace_chunk) {
1581 bool acquired_reference;
1582
1583 DBG("Viewer session and viewer stream chunk differ: "
1584 "vsession chunk %p vstream chunk %p",
1585 conn->viewer_session->current_trace_chunk,
1586 vstream->stream_file.trace_chunk);
1587 lttng_trace_chunk_put(vstream->stream_file.trace_chunk);
1588 acquired_reference = lttng_trace_chunk_get(conn->viewer_session->current_trace_chunk);
1589 assert(acquired_reference);
1590 vstream->stream_file.trace_chunk =
1591 conn->viewer_session->current_trace_chunk;
1592 viewer_stream_sync_tracefile_array_tail(vstream);
1593 viewer_stream_close_files(vstream);
1594 }
1595
1596 ret = check_index_status(vstream, rstream, ctf_trace, &viewer_index);
1597 if (ret < 0) {
1598 goto error_put;
1599 } else if (ret == 1) {
1600 /*
1601 * We have no index to send and check_index_status has populated
1602 * viewer_index's status.
1603 */
1604 goto send_reply;
1605 }
1606 /* At this point, ret is 0 thus we will be able to read the index. */
1607 assert(!ret);
1608
1609 /* Try to open an index if one is needed for that stream. */
1610 ret = try_open_index(vstream, rstream);
1611 if (ret == -ENOENT) {
1612 if (rstream->closed) {
1613 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_HUP);
1614 goto send_reply;
1615 } else {
1616 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_RETRY);
1617 goto send_reply;
1618 }
1619 }
1620 if (ret < 0) {
1621 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_ERR);
1622 goto send_reply;
1623 }
1624
1625 /*
1626 * vstream->stream_fd may be NULL if it has been closed by
1627 * tracefile rotation, or if we are at the beginning of the
1628 * stream. We open the data stream file here to protect against
1629 * overwrite caused by tracefile rotation (in association with
1630 * unlink performed before overwrite).
1631 */
1632 if (!vstream->stream_file.fd) {
1633 int fd;
1634 char file_path[LTTNG_PATH_MAX];
1635 enum lttng_trace_chunk_status status;
1636
1637 ret = utils_stream_file_path(rstream->path_name,
1638 rstream->channel_name, rstream->tracefile_size,
1639 vstream->current_tracefile_id, NULL, file_path,
1640 sizeof(file_path));
1641 if (ret < 0) {
1642 goto error_put;
1643 }
1644
1645 /*
1646 * It is possible the the file we are trying to open is
1647 * missing if the stream has been closed (application exits with
1648 * per-pid buffers) and a clear command has been performed.
1649 */
1650 status = lttng_trace_chunk_open_file(
1651 vstream->stream_file.trace_chunk,
1652 file_path, O_RDONLY, 0, &fd, true);
1653 if (status != LTTNG_TRACE_CHUNK_STATUS_OK) {
1654 if (status == LTTNG_TRACE_CHUNK_STATUS_NO_FILE &&
1655 rstream->closed) {
1656 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_HUP);
1657 goto send_reply;
1658 }
1659 PERROR("Failed to open trace file for viewer stream");
1660 goto error_put;
1661 }
1662 vstream->stream_file.fd = stream_fd_create(fd);
1663 if (!vstream->stream_file.fd) {
1664 if (close(fd)) {
1665 PERROR("Failed to close viewer stream file");
1666 }
1667 goto error_put;
1668 }
1669 }
1670
1671 ret = check_new_streams(conn);
1672 if (ret < 0) {
1673 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_ERR);
1674 goto send_reply;
1675 } else if (ret == 1) {
1676 viewer_index.flags |= LTTNG_VIEWER_FLAG_NEW_STREAM;
1677 }
1678
1679 ret = lttng_index_file_read(vstream->index_file, &packet_index);
1680 if (ret) {
1681 ERR("Relay error reading index file %d",
1682 vstream->index_file->fd);
1683 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_ERR);
1684 goto send_reply;
1685 } else {
1686 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_OK);
1687 vstream->index_sent_seqcount++;
1688 }
1689
1690 /*
1691 * Indexes are stored in big endian, no need to switch before sending.
1692 */
1693 DBG("Sending viewer index for stream %" PRIu64 " offset %" PRIu64,
1694 rstream->stream_handle,
1695 (uint64_t) be64toh(packet_index.offset));
1696 viewer_index.offset = packet_index.offset;
1697 viewer_index.packet_size = packet_index.packet_size;
1698 viewer_index.content_size = packet_index.content_size;
1699 viewer_index.timestamp_begin = packet_index.timestamp_begin;
1700 viewer_index.timestamp_end = packet_index.timestamp_end;
1701 viewer_index.events_discarded = packet_index.events_discarded;
1702 viewer_index.stream_id = packet_index.stream_id;
1703
1704 send_reply:
1705 if (rstream) {
1706 pthread_mutex_unlock(&rstream->lock);
1707 }
1708
1709 if (metadata_viewer_stream) {
1710 pthread_mutex_lock(&metadata_viewer_stream->stream->lock);
1711 DBG("get next index metadata check: recv %" PRIu64
1712 " sent %" PRIu64,
1713 metadata_viewer_stream->stream->metadata_received,
1714 metadata_viewer_stream->metadata_sent);
1715 if (!metadata_viewer_stream->stream->metadata_received ||
1716 metadata_viewer_stream->stream->metadata_received >
1717 metadata_viewer_stream->metadata_sent) {
1718 viewer_index.flags |= LTTNG_VIEWER_FLAG_NEW_METADATA;
1719 }
1720 pthread_mutex_unlock(&metadata_viewer_stream->stream->lock);
1721 }
1722
1723 viewer_index.flags = htobe32(viewer_index.flags);
1724 health_code_update();
1725
1726 ret = send_response(conn->sock, &viewer_index, sizeof(viewer_index));
1727 if (ret < 0) {
1728 goto end;
1729 }
1730 health_code_update();
1731
1732 if (vstream) {
1733 DBG("Index %" PRIu64 " for stream %" PRIu64 " sent",
1734 vstream->index_sent_seqcount,
1735 vstream->stream->stream_handle);
1736 }
1737 end:
1738 if (metadata_viewer_stream) {
1739 viewer_stream_put(metadata_viewer_stream);
1740 }
1741 if (vstream) {
1742 viewer_stream_put(vstream);
1743 }
1744 return ret;
1745
1746 error_put:
1747 pthread_mutex_unlock(&rstream->lock);
1748 if (metadata_viewer_stream) {
1749 viewer_stream_put(metadata_viewer_stream);
1750 }
1751 viewer_stream_put(vstream);
1752 return ret;
1753 }
1754
1755 /*
1756 * Send the next index for a stream
1757 *
1758 * Return 0 on success or else a negative value.
1759 */
1760 static
1761 int viewer_get_packet(struct relay_connection *conn)
1762 {
1763 int ret;
1764 off_t lseek_ret;
1765 char *reply = NULL;
1766 struct lttng_viewer_get_packet get_packet_info;
1767 struct lttng_viewer_trace_packet reply_header;
1768 struct relay_viewer_stream *vstream = NULL;
1769 uint32_t reply_size = sizeof(reply_header);
1770 uint32_t packet_data_len = 0;
1771 ssize_t read_len;
1772
1773 DBG2("Relay get data packet");
1774
1775 health_code_update();
1776
1777 ret = recv_request(conn->sock, &get_packet_info,
1778 sizeof(get_packet_info));
1779 if (ret < 0) {
1780 goto end;
1781 }
1782 health_code_update();
1783
1784 /* From this point on, the error label can be reached. */
1785 memset(&reply_header, 0, sizeof(reply_header));
1786
1787 vstream = viewer_stream_get_by_id(be64toh(get_packet_info.stream_id));
1788 if (!vstream) {
1789 DBG("Client requested packet of unknown stream id %" PRIu64,
1790 (uint64_t) be64toh(get_packet_info.stream_id));
1791 reply_header.status = htobe32(LTTNG_VIEWER_GET_PACKET_ERR);
1792 goto send_reply_nolock;
1793 } else {
1794 packet_data_len = be32toh(get_packet_info.len);
1795 reply_size += packet_data_len;
1796 }
1797
1798 reply = zmalloc(reply_size);
1799 if (!reply) {
1800 PERROR("packet reply zmalloc");
1801 reply_size = sizeof(reply_header);
1802 goto error;
1803 }
1804
1805 pthread_mutex_lock(&vstream->stream->lock);
1806 lseek_ret = lseek(vstream->stream_file.fd->fd,
1807 be64toh(get_packet_info.offset), SEEK_SET);
1808 if (lseek_ret < 0) {
1809 PERROR("lseek fd %d to offset %" PRIu64,
1810 vstream->stream_file.fd->fd,
1811 (uint64_t) be64toh(get_packet_info.offset));
1812 goto error;
1813 }
1814 read_len = lttng_read(vstream->stream_file.fd->fd,
1815 reply + sizeof(reply_header), packet_data_len);
1816 if (read_len < packet_data_len) {
1817 PERROR("Relay reading trace file, fd: %d, offset: %" PRIu64,
1818 vstream->stream_file.fd->fd,
1819 (uint64_t) be64toh(get_packet_info.offset));
1820 goto error;
1821 }
1822 reply_header.status = htobe32(LTTNG_VIEWER_GET_PACKET_OK);
1823 reply_header.len = htobe32(packet_data_len);
1824 goto send_reply;
1825
1826 error:
1827 reply_header.status = htobe32(LTTNG_VIEWER_GET_PACKET_ERR);
1828
1829 send_reply:
1830 if (vstream) {
1831 pthread_mutex_unlock(&vstream->stream->lock);
1832 }
1833 send_reply_nolock:
1834
1835 health_code_update();
1836
1837 if (reply) {
1838 memcpy(reply, &reply_header, sizeof(reply_header));
1839 ret = send_response(conn->sock, reply, reply_size);
1840 } else {
1841 /* No reply to send. */
1842 ret = send_response(conn->sock, &reply_header,
1843 reply_size);
1844 }
1845
1846 health_code_update();
1847 if (ret < 0) {
1848 PERROR("sendmsg of packet data failed");
1849 goto end_free;
1850 }
1851
1852 DBG("Sent %u bytes for stream %" PRIu64, reply_size,
1853 (uint64_t) be64toh(get_packet_info.stream_id));
1854
1855 end_free:
1856 free(reply);
1857 end:
1858 if (vstream) {
1859 viewer_stream_put(vstream);
1860 }
1861 return ret;
1862 }
1863
1864 /*
1865 * Send the session's metadata
1866 *
1867 * Return 0 on success else a negative value.
1868 */
1869 static
1870 int viewer_get_metadata(struct relay_connection *conn)
1871 {
1872 int ret = 0;
1873 ssize_t read_len;
1874 uint64_t len = 0;
1875 char *data = NULL;
1876 struct lttng_viewer_get_metadata request;
1877 struct lttng_viewer_metadata_packet reply;
1878 struct relay_viewer_stream *vstream = NULL;
1879
1880 assert(conn);
1881
1882 DBG("Relay get metadata");
1883
1884 health_code_update();
1885
1886 ret = recv_request(conn->sock, &request, sizeof(request));
1887 if (ret < 0) {
1888 goto end;
1889 }
1890 health_code_update();
1891
1892 memset(&reply, 0, sizeof(reply));
1893
1894 vstream = viewer_stream_get_by_id(be64toh(request.stream_id));
1895 if (!vstream) {
1896 /*
1897 * The metadata stream can be closed by a CLOSE command
1898 * just before we attach. It can also be closed by
1899 * per-pid tracing during tracing. Therefore, it is
1900 * possible that we cannot find this viewer stream.
1901 * Reply back to the client with an error if we cannot
1902 * find it.
1903 */
1904 DBG("Client requested metadata of unknown stream id %" PRIu64,
1905 (uint64_t) be64toh(request.stream_id));
1906 reply.status = htobe32(LTTNG_VIEWER_METADATA_ERR);
1907 goto send_reply;
1908 }
1909 pthread_mutex_lock(&vstream->stream->lock);
1910 if (!vstream->stream->is_metadata) {
1911 ERR("Invalid metadata stream");
1912 goto error;
1913 }
1914
1915 if (vstream->metadata_sent >= vstream->stream->metadata_received) {
1916 /*
1917 * The live viewers expect to receive a NO_NEW_METADATA
1918 * status before a stream disappears, otherwise they abort the
1919 * entire live connection when receiving an error status.
1920 *
1921 * Clear feature resets the metadata_sent to 0 until the
1922 * same metadata is received again.
1923 */
1924 reply.status = htobe32(LTTNG_VIEWER_NO_NEW_METADATA);
1925 /*
1926 * The live viewer considers a closed 0 byte metadata stream as
1927 * an error.
1928 */
1929 if (vstream->metadata_sent > 0) {
1930 vstream->stream->no_new_metadata_notified = true;
1931 if (vstream->stream->closed) {
1932 /* Release ownership for the viewer metadata stream. */
1933 viewer_stream_put(vstream);
1934 }
1935 }
1936 goto send_reply;
1937 }
1938
1939 len = vstream->stream->metadata_received - vstream->metadata_sent;
1940
1941 /* first time, we open the metadata file */
1942 if (!vstream->stream_file.fd) {
1943 int fd;
1944 char file_path[LTTNG_PATH_MAX];
1945 enum lttng_trace_chunk_status status;
1946 struct relay_stream *rstream = vstream->stream;
1947
1948 ret = utils_stream_file_path(rstream->path_name,
1949 rstream->channel_name, rstream->tracefile_size,
1950 vstream->current_tracefile_id, NULL, file_path,
1951 sizeof(file_path));
1952 if (ret < 0) {
1953 goto error;
1954 }
1955
1956 /*
1957 * It is possible the the metadata file we are trying to open is
1958 * missing if the stream has been closed (application exits with
1959 * per-pid buffers) and a clear command has been performed.
1960 */
1961 status = lttng_trace_chunk_open_file(
1962 vstream->stream_file.trace_chunk,
1963 file_path, O_RDONLY, 0, &fd, true);
1964 if (status != LTTNG_TRACE_CHUNK_STATUS_OK) {
1965 if (status == LTTNG_TRACE_CHUNK_STATUS_NO_FILE) {
1966 reply.status = htobe32(LTTNG_VIEWER_NO_NEW_METADATA);
1967 len = 0;
1968 if (vstream->stream->closed) {
1969 viewer_stream_put(vstream);
1970 }
1971 goto send_reply;
1972 }
1973 PERROR("Failed to open metadata file for viewer stream");
1974 goto error;
1975 }
1976 vstream->stream_file.fd = stream_fd_create(fd);
1977 if (!vstream->stream_file.fd) {
1978 if (close(fd)) {
1979 PERROR("Failed to close viewer metadata file");
1980 }
1981 goto error;
1982 }
1983 }
1984
1985 reply.len = htobe64(len);
1986 data = zmalloc(len);
1987 if (!data) {
1988 PERROR("viewer metadata zmalloc");
1989 goto error;
1990 }
1991
1992 read_len = lttng_read(vstream->stream_file.fd->fd, data, len);
1993 if (read_len < len) {
1994 PERROR("Relay reading metadata file");
1995 goto error;
1996 }
1997 vstream->metadata_sent += read_len;
1998 reply.status = htobe32(LTTNG_VIEWER_METADATA_OK);
1999
2000 goto send_reply;
2001
2002 error:
2003 reply.status = htobe32(LTTNG_VIEWER_METADATA_ERR);
2004
2005 send_reply:
2006 health_code_update();
2007 if (vstream) {
2008 pthread_mutex_unlock(&vstream->stream->lock);
2009 }
2010 ret = send_response(conn->sock, &reply, sizeof(reply));
2011 if (ret < 0) {
2012 goto end_free;
2013 }
2014 health_code_update();
2015
2016 if (len > 0) {
2017 ret = send_response(conn->sock, data, len);
2018 if (ret < 0) {
2019 goto end_free;
2020 }
2021 }
2022
2023 DBG("Sent %" PRIu64 " bytes of metadata for stream %" PRIu64, len,
2024 (uint64_t) be64toh(request.stream_id));
2025
2026 DBG("Metadata sent");
2027
2028 end_free:
2029 free(data);
2030 end:
2031 if (vstream) {
2032 viewer_stream_put(vstream);
2033 }
2034 return ret;
2035 }
2036
2037 /*
2038 * Create a viewer session.
2039 *
2040 * Return 0 on success or else a negative value.
2041 */
2042 static
2043 int viewer_create_session(struct relay_connection *conn)
2044 {
2045 int ret;
2046 struct lttng_viewer_create_session_response resp;
2047
2048 DBG("Viewer create session received");
2049
2050 memset(&resp, 0, sizeof(resp));
2051 resp.status = htobe32(LTTNG_VIEWER_CREATE_SESSION_OK);
2052 conn->viewer_session = viewer_session_create();
2053 if (!conn->viewer_session) {
2054 ERR("Allocation viewer session");
2055 resp.status = htobe32(LTTNG_VIEWER_CREATE_SESSION_ERR);
2056 goto send_reply;
2057 }
2058
2059 send_reply:
2060 health_code_update();
2061 ret = send_response(conn->sock, &resp, sizeof(resp));
2062 if (ret < 0) {
2063 goto end;
2064 }
2065 health_code_update();
2066 ret = 0;
2067
2068 end:
2069 return ret;
2070 }
2071
2072 /*
2073 * Detach a viewer session.
2074 *
2075 * Return 0 on success or else a negative value.
2076 */
2077 static
2078 int viewer_detach_session(struct relay_connection *conn)
2079 {
2080 int ret;
2081 struct lttng_viewer_detach_session_response response;
2082 struct lttng_viewer_detach_session_request request;
2083 struct relay_session *session = NULL;
2084 uint64_t viewer_session_to_close;
2085
2086 DBG("Viewer detach session received");
2087
2088 assert(conn);
2089
2090 health_code_update();
2091
2092 /* Receive the request from the connected client. */
2093 ret = recv_request(conn->sock, &request, sizeof(request));
2094 if (ret < 0) {
2095 goto end;
2096 }
2097 viewer_session_to_close = be64toh(request.session_id);
2098
2099 if (!conn->viewer_session) {
2100 DBG("Client trying to detach before creating a live viewer session");
2101 response.status = htobe32(LTTNG_VIEWER_DETACH_SESSION_ERR);
2102 goto send_reply;
2103 }
2104
2105 health_code_update();
2106
2107 memset(&response, 0, sizeof(response));
2108 DBG("Detaching from session ID %" PRIu64, viewer_session_to_close);
2109
2110 session = session_get_by_id(be64toh(request.session_id));
2111 if (!session) {
2112 DBG("Relay session %" PRIu64 " not found",
2113 (uint64_t) be64toh(request.session_id));
2114 response.status = htobe32(LTTNG_VIEWER_DETACH_SESSION_UNK);
2115 goto send_reply;
2116 }
2117
2118 ret = viewer_session_is_attached(conn->viewer_session, session);
2119 if (ret != 1) {
2120 DBG("Not attached to this session");
2121 response.status = htobe32(LTTNG_VIEWER_DETACH_SESSION_ERR);
2122 goto send_reply_put;
2123 }
2124
2125 viewer_session_close_one_session(conn->viewer_session, session);
2126 response.status = htobe32(LTTNG_VIEWER_DETACH_SESSION_OK);
2127 DBG("Session %" PRIu64 " detached.", viewer_session_to_close);
2128
2129 send_reply_put:
2130 session_put(session);
2131
2132 send_reply:
2133 health_code_update();
2134 ret = send_response(conn->sock, &response, sizeof(response));
2135 if (ret < 0) {
2136 goto end;
2137 }
2138 health_code_update();
2139 ret = 0;
2140
2141 end:
2142 return ret;
2143 }
2144
2145 /*
2146 * live_relay_unknown_command: send -1 if received unknown command
2147 */
2148 static
2149 void live_relay_unknown_command(struct relay_connection *conn)
2150 {
2151 struct lttcomm_relayd_generic_reply reply;
2152
2153 memset(&reply, 0, sizeof(reply));
2154 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2155 (void) send_response(conn->sock, &reply, sizeof(reply));
2156 }
2157
2158 /*
2159 * Process the commands received on the control socket
2160 */
2161 static
2162 int process_control(struct lttng_viewer_cmd *recv_hdr,
2163 struct relay_connection *conn)
2164 {
2165 int ret = 0;
2166 uint32_t msg_value;
2167
2168 msg_value = be32toh(recv_hdr->cmd);
2169
2170 /*
2171 * Make sure we've done the version check before any command other then a
2172 * new client connection.
2173 */
2174 if (msg_value != LTTNG_VIEWER_CONNECT && !conn->version_check_done) {
2175 ERR("Viewer conn value %" PRIu32 " before version check", msg_value);
2176 ret = -1;
2177 goto end;
2178 }
2179
2180 switch (msg_value) {
2181 case LTTNG_VIEWER_CONNECT:
2182 ret = viewer_connect(conn);
2183 break;
2184 case LTTNG_VIEWER_LIST_SESSIONS:
2185 ret = viewer_list_sessions(conn);
2186 break;
2187 case LTTNG_VIEWER_ATTACH_SESSION:
2188 ret = viewer_attach_session(conn);
2189 break;
2190 case LTTNG_VIEWER_GET_NEXT_INDEX:
2191 ret = viewer_get_next_index(conn);
2192 break;
2193 case LTTNG_VIEWER_GET_PACKET:
2194 ret = viewer_get_packet(conn);
2195 break;
2196 case LTTNG_VIEWER_GET_METADATA:
2197 ret = viewer_get_metadata(conn);
2198 break;
2199 case LTTNG_VIEWER_GET_NEW_STREAMS:
2200 ret = viewer_get_new_streams(conn);
2201 break;
2202 case LTTNG_VIEWER_CREATE_SESSION:
2203 ret = viewer_create_session(conn);
2204 break;
2205 case LTTNG_VIEWER_DETACH_SESSION:
2206 ret = viewer_detach_session(conn);
2207 break;
2208 default:
2209 ERR("Received unknown viewer command (%u)",
2210 be32toh(recv_hdr->cmd));
2211 live_relay_unknown_command(conn);
2212 ret = -1;
2213 goto end;
2214 }
2215
2216 end:
2217 return ret;
2218 }
2219
2220 static
2221 void cleanup_connection_pollfd(struct lttng_poll_event *events, int pollfd)
2222 {
2223 int ret;
2224
2225 (void) lttng_poll_del(events, pollfd);
2226
2227 ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker, &pollfd, 1,
2228 fd_tracker_util_close_fd, NULL);
2229 if (ret < 0) {
2230 ERR("Closing pollfd %d", pollfd);
2231 }
2232 }
2233
2234 /*
2235 * This thread does the actual work
2236 */
2237 static
2238 void *thread_worker(void *data)
2239 {
2240 int ret, err = -1;
2241 uint32_t nb_fd;
2242 struct lttng_poll_event events;
2243 struct lttng_ht *viewer_connections_ht;
2244 struct lttng_ht_iter iter;
2245 struct lttng_viewer_cmd recv_hdr;
2246 struct relay_connection *destroy_conn;
2247
2248 DBG("[thread] Live viewer relay worker started");
2249
2250 rcu_register_thread();
2251
2252 health_register(health_relayd, HEALTH_RELAYD_TYPE_LIVE_WORKER);
2253
2254 if (testpoint(relayd_thread_live_worker)) {
2255 goto error_testpoint;
2256 }
2257
2258 /* table of connections indexed on socket */
2259 viewer_connections_ht = lttng_ht_new(0, LTTNG_HT_TYPE_ULONG);
2260 if (!viewer_connections_ht) {
2261 goto viewer_connections_ht_error;
2262 }
2263
2264 ret = create_named_thread_poll_set(&events, 2,
2265 "Live viewer worker thread epoll");
2266 if (ret < 0) {
2267 goto error_poll_create;
2268 }
2269
2270 ret = lttng_poll_add(&events, live_conn_pipe[0], LPOLLIN | LPOLLRDHUP);
2271 if (ret < 0) {
2272 goto error;
2273 }
2274
2275 restart:
2276 while (1) {
2277 int i;
2278
2279 health_code_update();
2280
2281 /* Infinite blocking call, waiting for transmission */
2282 DBG3("Relayd live viewer worker thread polling...");
2283 health_poll_entry();
2284 ret = lttng_poll_wait(&events, -1);
2285 health_poll_exit();
2286 if (ret < 0) {
2287 /*
2288 * Restart interrupted system call.
2289 */
2290 if (errno == EINTR) {
2291 goto restart;
2292 }
2293 goto error;
2294 }
2295
2296 nb_fd = ret;
2297
2298 /*
2299 * Process control. The control connection is prioritised so we don't
2300 * starve it with high throughput tracing data on the data
2301 * connection.
2302 */
2303 for (i = 0; i < nb_fd; i++) {
2304 /* Fetch once the poll data */
2305 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
2306 int pollfd = LTTNG_POLL_GETFD(&events, i);
2307
2308 health_code_update();
2309
2310 /* Thread quit pipe has been closed. Killing thread. */
2311 ret = check_thread_quit_pipe(pollfd, revents);
2312 if (ret) {
2313 err = 0;
2314 goto exit;
2315 }
2316
2317 /* Inspect the relay conn pipe for new connection. */
2318 if (pollfd == live_conn_pipe[0]) {
2319 if (revents & LPOLLIN) {
2320 struct relay_connection *conn;
2321
2322 ret = lttng_read(live_conn_pipe[0],
2323 &conn, sizeof(conn));
2324 if (ret < 0) {
2325 goto error;
2326 }
2327 ret = lttng_poll_add(&events,
2328 conn->sock->fd,
2329 LPOLLIN | LPOLLRDHUP);
2330 if (ret) {
2331 ERR("Failed to add new live connection file descriptor to poll set");
2332 goto error;
2333 }
2334 connection_ht_add(viewer_connections_ht, conn);
2335 DBG("Connection socket %d added to poll", conn->sock->fd);
2336 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2337 ERR("Relay live pipe error");
2338 goto error;
2339 } else {
2340 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
2341 goto error;
2342 }
2343 } else {
2344 /* Connection activity. */
2345 struct relay_connection *conn;
2346
2347 conn = connection_get_by_sock(viewer_connections_ht, pollfd);
2348 if (!conn) {
2349 continue;
2350 }
2351
2352 if (revents & LPOLLIN) {
2353 ret = conn->sock->ops->recvmsg(conn->sock, &recv_hdr,
2354 sizeof(recv_hdr), 0);
2355 if (ret <= 0) {
2356 /* Connection closed. */
2357 cleanup_connection_pollfd(&events, pollfd);
2358 /* Put "create" ownership reference. */
2359 connection_put(conn);
2360 DBG("Viewer control conn closed with %d", pollfd);
2361 } else {
2362 ret = process_control(&recv_hdr, conn);
2363 if (ret < 0) {
2364 /* Clear the session on error. */
2365 cleanup_connection_pollfd(&events, pollfd);
2366 /* Put "create" ownership reference. */
2367 connection_put(conn);
2368 DBG("Viewer connection closed with %d", pollfd);
2369 }
2370 }
2371 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2372 cleanup_connection_pollfd(&events, pollfd);
2373 /* Put "create" ownership reference. */
2374 connection_put(conn);
2375 } else {
2376 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
2377 connection_put(conn);
2378 goto error;
2379 }
2380 /* Put local "get_by_sock" reference. */
2381 connection_put(conn);
2382 }
2383 }
2384 }
2385
2386 exit:
2387 error:
2388 (void) fd_tracker_util_poll_clean(the_fd_tracker, &events);
2389
2390 /* Cleanup remaining connection object. */
2391 rcu_read_lock();
2392 cds_lfht_for_each_entry(viewer_connections_ht->ht, &iter.iter,
2393 destroy_conn,
2394 sock_n.node) {
2395 health_code_update();
2396 connection_put(destroy_conn);
2397 }
2398 rcu_read_unlock();
2399 error_poll_create:
2400 lttng_ht_destroy(viewer_connections_ht);
2401 viewer_connections_ht_error:
2402 /* Close relay conn pipes */
2403 (void) fd_tracker_util_pipe_close(the_fd_tracker, live_conn_pipe);
2404 if (err) {
2405 DBG("Viewer worker thread exited with error");
2406 }
2407 DBG("Viewer worker thread cleanup complete");
2408 error_testpoint:
2409 if (err) {
2410 health_error();
2411 ERR("Health error occurred in %s", __func__);
2412 }
2413 health_unregister(health_relayd);
2414 if (lttng_relay_stop_threads()) {
2415 ERR("Error stopping threads");
2416 }
2417 rcu_unregister_thread();
2418 return NULL;
2419 }
2420
2421 /*
2422 * Create the relay command pipe to wake thread_manage_apps.
2423 * Closed in cleanup().
2424 */
2425 static int create_conn_pipe(void)
2426 {
2427 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker,
2428 "Live connection pipe", live_conn_pipe);
2429 }
2430
2431 int relayd_live_join(void)
2432 {
2433 int ret, retval = 0;
2434 void *status;
2435
2436 ret = pthread_join(live_listener_thread, &status);
2437 if (ret) {
2438 errno = ret;
2439 PERROR("pthread_join live listener");
2440 retval = -1;
2441 }
2442
2443 ret = pthread_join(live_worker_thread, &status);
2444 if (ret) {
2445 errno = ret;
2446 PERROR("pthread_join live worker");
2447 retval = -1;
2448 }
2449
2450 ret = pthread_join(live_dispatcher_thread, &status);
2451 if (ret) {
2452 errno = ret;
2453 PERROR("pthread_join live dispatcher");
2454 retval = -1;
2455 }
2456
2457 cleanup_relayd_live();
2458
2459 return retval;
2460 }
2461
2462 /*
2463 * main
2464 */
2465 int relayd_live_create(struct lttng_uri *uri)
2466 {
2467 int ret = 0, retval = 0;
2468 void *status;
2469 int is_root;
2470
2471 if (!uri) {
2472 retval = -1;
2473 goto exit_init_data;
2474 }
2475 live_uri = uri;
2476
2477 /* Check if daemon is UID = 0 */
2478 is_root = !getuid();
2479
2480 if (!is_root) {
2481 if (live_uri->port < 1024) {
2482 ERR("Need to be root to use ports < 1024");
2483 retval = -1;
2484 goto exit_init_data;
2485 }
2486 }
2487
2488 /* Setup the thread apps communication pipe. */
2489 if (create_conn_pipe()) {
2490 retval = -1;
2491 goto exit_init_data;
2492 }
2493
2494 /* Init relay command queue. */
2495 cds_wfcq_init(&viewer_conn_queue.head, &viewer_conn_queue.tail);
2496
2497 /* Set up max poll set size */
2498 if (lttng_poll_set_max_size()) {
2499 retval = -1;
2500 goto exit_init_data;
2501 }
2502
2503 /* Setup the dispatcher thread */
2504 ret = pthread_create(&live_dispatcher_thread, default_pthread_attr(),
2505 thread_dispatcher, (void *) NULL);
2506 if (ret) {
2507 errno = ret;
2508 PERROR("pthread_create viewer dispatcher");
2509 retval = -1;
2510 goto exit_dispatcher_thread;
2511 }
2512
2513 /* Setup the worker thread */
2514 ret = pthread_create(&live_worker_thread, default_pthread_attr(),
2515 thread_worker, NULL);
2516 if (ret) {
2517 errno = ret;
2518 PERROR("pthread_create viewer worker");
2519 retval = -1;
2520 goto exit_worker_thread;
2521 }
2522
2523 /* Setup the listener thread */
2524 ret = pthread_create(&live_listener_thread, default_pthread_attr(),
2525 thread_listener, (void *) NULL);
2526 if (ret) {
2527 errno = ret;
2528 PERROR("pthread_create viewer listener");
2529 retval = -1;
2530 goto exit_listener_thread;
2531 }
2532
2533 /*
2534 * All OK, started all threads.
2535 */
2536 return retval;
2537
2538 /*
2539 * Join on the live_listener_thread should anything be added after
2540 * the live_listener thread's creation.
2541 */
2542
2543 exit_listener_thread:
2544
2545 ret = pthread_join(live_worker_thread, &status);
2546 if (ret) {
2547 errno = ret;
2548 PERROR("pthread_join live worker");
2549 retval = -1;
2550 }
2551 exit_worker_thread:
2552
2553 ret = pthread_join(live_dispatcher_thread, &status);
2554 if (ret) {
2555 errno = ret;
2556 PERROR("pthread_join live dispatcher");
2557 retval = -1;
2558 }
2559 exit_dispatcher_thread:
2560
2561 exit_init_data:
2562 cleanup_relayd_live();
2563
2564 return retval;
2565 }
This page took 0.115254 seconds and 5 git commands to generate.