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