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