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