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