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