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