Fix: race with the viewer and readiness of streams
[lttng-tools.git] / src / bin / lttng-relayd / main.c
1 /*
2 * Copyright (C) 2012 - Julien Desfossez <jdesfossez@efficios.com>
3 * David Goulet <dgoulet@efficios.com>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License, version 2 only,
7 * as published by the Free Software Foundation.
8 *
9 * This program is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
12 * more details.
13 *
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17 */
18
19 #define _GNU_SOURCE
20 #include <getopt.h>
21 #include <grp.h>
22 #include <limits.h>
23 #include <pthread.h>
24 #include <signal.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/mman.h>
29 #include <sys/mount.h>
30 #include <sys/resource.h>
31 #include <sys/socket.h>
32 #include <sys/stat.h>
33 #include <sys/types.h>
34 #include <sys/wait.h>
35 #include <inttypes.h>
36 #include <urcu/futex.h>
37 #include <urcu/uatomic.h>
38 #include <unistd.h>
39 #include <fcntl.h>
40 #include <config.h>
41
42 #include <lttng/lttng.h>
43 #include <common/common.h>
44 #include <common/compat/poll.h>
45 #include <common/compat/socket.h>
46 #include <common/defaults.h>
47 #include <common/futex.h>
48 #include <common/sessiond-comm/sessiond-comm.h>
49 #include <common/sessiond-comm/inet.h>
50 #include <common/sessiond-comm/relayd.h>
51 #include <common/uri.h>
52 #include <common/utils.h>
53
54 #include "cmd.h"
55 #include "ctf-trace.h"
56 #include "index.h"
57 #include "utils.h"
58 #include "lttng-relayd.h"
59 #include "live.h"
60 #include "health-relayd.h"
61
62 /* command line options */
63 char *opt_output_path;
64 static int opt_daemon;
65 static struct lttng_uri *control_uri;
66 static struct lttng_uri *data_uri;
67 static struct lttng_uri *live_uri;
68
69 const char *progname;
70
71 const char *tracing_group_name = DEFAULT_TRACING_GROUP;
72
73 /*
74 * Quit pipe for all threads. This permits a single cancellation point
75 * for all threads when receiving an event on the pipe.
76 */
77 static int thread_quit_pipe[2] = { -1, -1 };
78
79 /*
80 * This pipe is used to inform the worker thread that a command is queued and
81 * ready to be processed.
82 */
83 static int relay_cmd_pipe[2] = { -1, -1 };
84
85 /* Shared between threads */
86 static int dispatch_thread_exit;
87
88 static pthread_t listener_thread;
89 static pthread_t dispatcher_thread;
90 static pthread_t worker_thread;
91 static pthread_t health_thread;
92
93 static uint64_t last_relay_stream_id;
94 static uint64_t last_relay_session_id;
95
96 /*
97 * Relay command queue.
98 *
99 * The relay_thread_listener and relay_thread_dispatcher communicate with this
100 * queue.
101 */
102 static struct relay_cmd_queue relay_cmd_queue;
103
104 /* buffer allocated at startup, used to store the trace data */
105 static char *data_buffer;
106 static unsigned int data_buffer_size;
107
108 /* We need those values for the file/dir creation. */
109 static uid_t relayd_uid;
110 static gid_t relayd_gid;
111
112 /* Global relay stream hash table. */
113 struct lttng_ht *relay_streams_ht;
114
115 /* Global relay viewer stream hash table. */
116 struct lttng_ht *viewer_streams_ht;
117
118 /* Global hash table that stores relay index object. */
119 struct lttng_ht *indexes_ht;
120
121 /* Relayd health monitoring */
122 struct health_app *health_relayd;
123
124 /*
125 * usage function on stderr
126 */
127 static
128 void usage(void)
129 {
130 fprintf(stderr, "Usage: %s OPTIONS\n\nOptions:\n", progname);
131 fprintf(stderr, " -h, --help Display this usage.\n");
132 fprintf(stderr, " -d, --daemonize Start as a daemon.\n");
133 fprintf(stderr, " -C, --control-port URL Control port listening.\n");
134 fprintf(stderr, " -D, --data-port URL Data port listening.\n");
135 fprintf(stderr, " -L, --live-port URL Live view port listening.\n");
136 fprintf(stderr, " -o, --output PATH Output path for traces. Must use an absolute path.\n");
137 fprintf(stderr, " -v, --verbose Verbose mode. Activate DBG() macro.\n");
138 fprintf(stderr, " -g, --group NAME Specify the tracing group name. (default: tracing)\n");
139 }
140
141 static
142 int parse_args(int argc, char **argv)
143 {
144 int c;
145 int ret = 0;
146 char *default_address;
147
148 static struct option long_options[] = {
149 { "control-port", 1, 0, 'C', },
150 { "data-port", 1, 0, 'D', },
151 { "daemonize", 0, 0, 'd', },
152 { "group", 1, 0, 'g', },
153 { "help", 0, 0, 'h', },
154 { "output", 1, 0, 'o', },
155 { "verbose", 0, 0, 'v', },
156 { NULL, 0, 0, 0, },
157 };
158
159 while (1) {
160 int option_index = 0;
161 c = getopt_long(argc, argv, "dhv" "C:D:L:o:g:",
162 long_options, &option_index);
163 if (c == -1) {
164 break;
165 }
166
167 switch (c) {
168 case 0:
169 fprintf(stderr, "option %s", long_options[option_index].name);
170 if (optarg) {
171 fprintf(stderr, " with arg %s\n", optarg);
172 }
173 break;
174 case 'C':
175 ret = uri_parse(optarg, &control_uri);
176 if (ret < 0) {
177 ERR("Invalid control URI specified");
178 goto exit;
179 }
180 if (control_uri->port == 0) {
181 control_uri->port = DEFAULT_NETWORK_CONTROL_PORT;
182 }
183 break;
184 case 'D':
185 ret = uri_parse(optarg, &data_uri);
186 if (ret < 0) {
187 ERR("Invalid data URI specified");
188 goto exit;
189 }
190 if (data_uri->port == 0) {
191 data_uri->port = DEFAULT_NETWORK_DATA_PORT;
192 }
193 break;
194 case 'L':
195 ret = uri_parse(optarg, &live_uri);
196 if (ret < 0) {
197 ERR("Invalid live URI specified");
198 goto exit;
199 }
200 if (live_uri->port == 0) {
201 live_uri->port = DEFAULT_NETWORK_VIEWER_PORT;
202 }
203 break;
204 case 'd':
205 opt_daemon = 1;
206 break;
207 case 'g':
208 tracing_group_name = optarg;
209 break;
210 case 'h':
211 usage();
212 exit(EXIT_FAILURE);
213 case 'o':
214 ret = asprintf(&opt_output_path, "%s", optarg);
215 if (ret < 0) {
216 PERROR("asprintf opt_output_path");
217 goto exit;
218 }
219 break;
220 case 'v':
221 /* Verbose level can increase using multiple -v */
222 lttng_opt_verbose += 1;
223 break;
224 default:
225 /* Unknown option or other error.
226 * Error is printed by getopt, just return */
227 ret = -1;
228 goto exit;
229 }
230 }
231
232 /* assign default values */
233 if (control_uri == NULL) {
234 ret = asprintf(&default_address, "tcp://0.0.0.0:%d",
235 DEFAULT_NETWORK_CONTROL_PORT);
236 if (ret < 0) {
237 PERROR("asprintf default data address");
238 goto exit;
239 }
240
241 ret = uri_parse(default_address, &control_uri);
242 free(default_address);
243 if (ret < 0) {
244 ERR("Invalid control URI specified");
245 goto exit;
246 }
247 }
248 if (data_uri == NULL) {
249 ret = asprintf(&default_address, "tcp://0.0.0.0:%d",
250 DEFAULT_NETWORK_DATA_PORT);
251 if (ret < 0) {
252 PERROR("asprintf default data address");
253 goto exit;
254 }
255
256 ret = uri_parse(default_address, &data_uri);
257 free(default_address);
258 if (ret < 0) {
259 ERR("Invalid data URI specified");
260 goto exit;
261 }
262 }
263 if (live_uri == NULL) {
264 ret = asprintf(&default_address, "tcp://0.0.0.0:%d",
265 DEFAULT_NETWORK_VIEWER_PORT);
266 if (ret < 0) {
267 PERROR("asprintf default viewer control address");
268 goto exit;
269 }
270
271 ret = uri_parse(default_address, &live_uri);
272 free(default_address);
273 if (ret < 0) {
274 ERR("Invalid viewer control URI specified");
275 goto exit;
276 }
277 }
278
279 exit:
280 return ret;
281 }
282
283 /*
284 * Cleanup the daemon
285 */
286 static
287 void cleanup(void)
288 {
289 DBG("Cleaning up");
290
291 /* free the dynamically allocated opt_output_path */
292 free(opt_output_path);
293
294 /* Close thread quit pipes */
295 utils_close_pipe(thread_quit_pipe);
296
297 uri_free(control_uri);
298 uri_free(data_uri);
299 /* Live URI is freed in the live thread. */
300 }
301
302 /*
303 * Write to writable pipe used to notify a thread.
304 */
305 static
306 int notify_thread_pipe(int wpipe)
307 {
308 ssize_t ret;
309
310 ret = lttng_write(wpipe, "!", 1);
311 if (ret < 1) {
312 PERROR("write poll pipe");
313 }
314
315 return ret;
316 }
317
318 static void notify_health_quit_pipe(int *pipe)
319 {
320 ssize_t ret;
321
322 ret = lttng_write(pipe[1], "4", 1);
323 if (ret < 1) {
324 PERROR("write relay health quit");
325 }
326 }
327
328 /*
329 * Stop all threads by closing the thread quit pipe.
330 */
331 static
332 void stop_threads(void)
333 {
334 int ret;
335
336 /* Stopping all threads */
337 DBG("Terminating all threads");
338 ret = notify_thread_pipe(thread_quit_pipe[1]);
339 if (ret < 0) {
340 ERR("write error on thread quit pipe");
341 }
342
343 notify_health_quit_pipe(health_quit_pipe);
344
345 /* Dispatch thread */
346 CMM_STORE_SHARED(dispatch_thread_exit, 1);
347 futex_nto1_wake(&relay_cmd_queue.futex);
348 }
349
350 /*
351 * Signal handler for the daemon
352 *
353 * Simply stop all worker threads, leaving main() return gracefully after
354 * joining all threads and calling cleanup().
355 */
356 static
357 void sighandler(int sig)
358 {
359 switch (sig) {
360 case SIGPIPE:
361 DBG("SIGPIPE caught");
362 return;
363 case SIGINT:
364 DBG("SIGINT caught");
365 stop_threads();
366 break;
367 case SIGTERM:
368 DBG("SIGTERM caught");
369 stop_threads();
370 break;
371 default:
372 break;
373 }
374 }
375
376 /*
377 * Setup signal handler for :
378 * SIGINT, SIGTERM, SIGPIPE
379 */
380 static
381 int set_signal_handler(void)
382 {
383 int ret = 0;
384 struct sigaction sa;
385 sigset_t sigset;
386
387 if ((ret = sigemptyset(&sigset)) < 0) {
388 PERROR("sigemptyset");
389 return ret;
390 }
391
392 sa.sa_handler = sighandler;
393 sa.sa_mask = sigset;
394 sa.sa_flags = 0;
395 if ((ret = sigaction(SIGTERM, &sa, NULL)) < 0) {
396 PERROR("sigaction");
397 return ret;
398 }
399
400 if ((ret = sigaction(SIGINT, &sa, NULL)) < 0) {
401 PERROR("sigaction");
402 return ret;
403 }
404
405 if ((ret = sigaction(SIGPIPE, &sa, NULL)) < 0) {
406 PERROR("sigaction");
407 return ret;
408 }
409
410 DBG("Signal handler set for SIGTERM, SIGPIPE and SIGINT");
411
412 return ret;
413 }
414
415 /*
416 * Init thread quit pipe.
417 *
418 * Return -1 on error or 0 if all pipes are created.
419 */
420 static
421 int init_thread_quit_pipe(void)
422 {
423 int ret;
424
425 ret = utils_create_pipe_cloexec(thread_quit_pipe);
426
427 return ret;
428 }
429
430 /*
431 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
432 */
433 static
434 int create_thread_poll_set(struct lttng_poll_event *events, int size)
435 {
436 int ret;
437
438 if (events == NULL || size == 0) {
439 ret = -1;
440 goto error;
441 }
442
443 ret = lttng_poll_create(events, size, LTTNG_CLOEXEC);
444 if (ret < 0) {
445 goto error;
446 }
447
448 /* Add quit pipe */
449 ret = lttng_poll_add(events, thread_quit_pipe[0], LPOLLIN);
450 if (ret < 0) {
451 goto error;
452 }
453
454 return 0;
455
456 error:
457 return ret;
458 }
459
460 /*
461 * Check if the thread quit pipe was triggered.
462 *
463 * Return 1 if it was triggered else 0;
464 */
465 static
466 int check_thread_quit_pipe(int fd, uint32_t events)
467 {
468 if (fd == thread_quit_pipe[0] && (events & LPOLLIN)) {
469 return 1;
470 }
471
472 return 0;
473 }
474
475 /*
476 * Create and init socket from uri.
477 */
478 static
479 struct lttcomm_sock *relay_init_sock(struct lttng_uri *uri)
480 {
481 int ret;
482 struct lttcomm_sock *sock = NULL;
483
484 sock = lttcomm_alloc_sock_from_uri(uri);
485 if (sock == NULL) {
486 ERR("Allocating socket");
487 goto error;
488 }
489
490 ret = lttcomm_create_sock(sock);
491 if (ret < 0) {
492 goto error;
493 }
494 DBG("Listening on sock %d", sock->fd);
495
496 ret = sock->ops->bind(sock);
497 if (ret < 0) {
498 goto error;
499 }
500
501 ret = sock->ops->listen(sock, -1);
502 if (ret < 0) {
503 goto error;
504
505 }
506
507 return sock;
508
509 error:
510 if (sock) {
511 lttcomm_destroy_sock(sock);
512 }
513 return NULL;
514 }
515
516 /*
517 * Return nonzero if stream needs to be closed.
518 */
519 static
520 int close_stream_check(struct relay_stream *stream)
521 {
522
523 if (stream->close_flag && stream->prev_seq == stream->last_net_seq_num) {
524 /*
525 * We are about to close the stream so set the data pending flag to 1
526 * which will make the end data pending command skip the stream which
527 * is now closed and ready. Note that after proceeding to a file close,
528 * the written file is ready for reading.
529 */
530 stream->data_pending_check_done = 1;
531 return 1;
532 }
533 return 0;
534 }
535
536 /*
537 * This thread manages the listening for new connections on the network
538 */
539 static
540 void *relay_thread_listener(void *data)
541 {
542 int i, ret, pollfd, err = -1;
543 int val = 1;
544 uint32_t revents, nb_fd;
545 struct lttng_poll_event events;
546 struct lttcomm_sock *control_sock, *data_sock;
547
548 DBG("[thread] Relay listener started");
549
550 health_register(health_relayd, HEALTH_RELAYD_TYPE_LISTENER);
551
552 health_code_update();
553
554 control_sock = relay_init_sock(control_uri);
555 if (!control_sock) {
556 goto error_sock_control;
557 }
558
559 data_sock = relay_init_sock(data_uri);
560 if (!data_sock) {
561 goto error_sock_relay;
562 }
563
564 /*
565 * Pass 3 as size here for the thread quit pipe, control and data socket.
566 */
567 ret = create_thread_poll_set(&events, 3);
568 if (ret < 0) {
569 goto error_create_poll;
570 }
571
572 /* Add the control socket */
573 ret = lttng_poll_add(&events, control_sock->fd, LPOLLIN | LPOLLRDHUP);
574 if (ret < 0) {
575 goto error_poll_add;
576 }
577
578 /* Add the data socket */
579 ret = lttng_poll_add(&events, data_sock->fd, LPOLLIN | LPOLLRDHUP);
580 if (ret < 0) {
581 goto error_poll_add;
582 }
583
584 while (1) {
585 health_code_update();
586
587 DBG("Listener accepting connections");
588
589 restart:
590 health_poll_entry();
591 ret = lttng_poll_wait(&events, -1);
592 health_poll_exit();
593 if (ret < 0) {
594 /*
595 * Restart interrupted system call.
596 */
597 if (errno == EINTR) {
598 goto restart;
599 }
600 goto error;
601 }
602
603 nb_fd = ret;
604
605 DBG("Relay new connection received");
606 for (i = 0; i < nb_fd; i++) {
607 health_code_update();
608
609 /* Fetch once the poll data */
610 revents = LTTNG_POLL_GETEV(&events, i);
611 pollfd = LTTNG_POLL_GETFD(&events, i);
612
613 /* Thread quit pipe has been closed. Killing thread. */
614 ret = check_thread_quit_pipe(pollfd, revents);
615 if (ret) {
616 err = 0;
617 goto exit;
618 }
619
620 if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
621 ERR("socket poll error");
622 goto error;
623 } else if (revents & LPOLLIN) {
624 /*
625 * Get allocated in this thread,
626 * enqueued to a global queue, dequeued
627 * and freed in the worker thread.
628 */
629 struct relay_command *relay_cmd;
630 struct lttcomm_sock *newsock;
631
632 relay_cmd = zmalloc(sizeof(struct relay_command));
633 if (relay_cmd == NULL) {
634 PERROR("relay command zmalloc");
635 goto error;
636 }
637
638 if (pollfd == data_sock->fd) {
639 newsock = data_sock->ops->accept(data_sock);
640 if (!newsock) {
641 PERROR("accepting data sock");
642 free(relay_cmd);
643 goto error;
644 }
645 relay_cmd->type = RELAY_DATA;
646 DBG("Relay data connection accepted, socket %d", newsock->fd);
647 } else {
648 assert(pollfd == control_sock->fd);
649 newsock = control_sock->ops->accept(control_sock);
650 if (!newsock) {
651 PERROR("accepting control sock");
652 free(relay_cmd);
653 goto error;
654 }
655 relay_cmd->type = RELAY_CONTROL;
656 DBG("Relay control connection accepted, socket %d", newsock->fd);
657 }
658 ret = setsockopt(newsock->fd, SOL_SOCKET, SO_REUSEADDR,
659 &val, sizeof(int));
660 if (ret < 0) {
661 PERROR("setsockopt inet");
662 lttcomm_destroy_sock(newsock);
663 free(relay_cmd);
664 goto error;
665 }
666 relay_cmd->sock = newsock;
667 /*
668 * Lock free enqueue the request.
669 */
670 cds_wfq_enqueue(&relay_cmd_queue.queue, &relay_cmd->node);
671
672 /*
673 * Wake the dispatch queue futex. Implicit memory
674 * barrier with the exchange in cds_wfq_enqueue.
675 */
676 futex_nto1_wake(&relay_cmd_queue.futex);
677 }
678 }
679 }
680
681 exit:
682 error:
683 error_poll_add:
684 lttng_poll_clean(&events);
685 error_create_poll:
686 if (data_sock->fd >= 0) {
687 ret = data_sock->ops->close(data_sock);
688 if (ret) {
689 PERROR("close");
690 }
691 }
692 lttcomm_destroy_sock(data_sock);
693 error_sock_relay:
694 if (control_sock->fd >= 0) {
695 ret = control_sock->ops->close(control_sock);
696 if (ret) {
697 PERROR("close");
698 }
699 }
700 lttcomm_destroy_sock(control_sock);
701 error_sock_control:
702 if (err) {
703 health_error();
704 ERR("Health error occurred in %s", __func__);
705 }
706 health_unregister(health_relayd);
707 DBG("Relay listener thread cleanup complete");
708 stop_threads();
709 return NULL;
710 }
711
712 /*
713 * This thread manages the dispatching of the requests to worker threads
714 */
715 static
716 void *relay_thread_dispatcher(void *data)
717 {
718 int err = -1;
719 ssize_t ret;
720 struct cds_wfq_node *node;
721 struct relay_command *relay_cmd = NULL;
722
723 DBG("[thread] Relay dispatcher started");
724
725 health_register(health_relayd, HEALTH_RELAYD_TYPE_DISPATCHER);
726
727 health_code_update();
728
729 while (!CMM_LOAD_SHARED(dispatch_thread_exit)) {
730 health_code_update();
731
732 /* Atomically prepare the queue futex */
733 futex_nto1_prepare(&relay_cmd_queue.futex);
734
735 do {
736 health_code_update();
737
738 /* Dequeue commands */
739 node = cds_wfq_dequeue_blocking(&relay_cmd_queue.queue);
740 if (node == NULL) {
741 DBG("Woken up but nothing in the relay command queue");
742 /* Continue thread execution */
743 break;
744 }
745
746 relay_cmd = caa_container_of(node, struct relay_command, node);
747 DBG("Dispatching request waiting on sock %d", relay_cmd->sock->fd);
748
749 /*
750 * Inform worker thread of the new request. This
751 * call is blocking so we can be assured that the data will be read
752 * at some point in time or wait to the end of the world :)
753 */
754 ret = lttng_write(relay_cmd_pipe[1], relay_cmd,
755 sizeof(struct relay_command));
756 free(relay_cmd);
757 if (ret < sizeof(struct relay_command)) {
758 PERROR("write cmd pipe");
759 goto error;
760 }
761 } while (node != NULL);
762
763 /* Futex wait on queue. Blocking call on futex() */
764 health_poll_entry();
765 futex_nto1_wait(&relay_cmd_queue.futex);
766 health_poll_exit();
767 }
768
769 /* Normal exit, no error */
770 err = 0;
771
772 error:
773 if (err) {
774 health_error();
775 ERR("Health error occurred in %s", __func__);
776 }
777 health_unregister(health_relayd);
778 DBG("Dispatch thread dying");
779 stop_threads();
780 return NULL;
781 }
782
783 /*
784 * Get stream from stream id.
785 * Need to be called with RCU read-side lock held.
786 */
787 struct relay_stream *relay_stream_find_by_id(uint64_t stream_id)
788 {
789 struct lttng_ht_node_ulong *node;
790 struct lttng_ht_iter iter;
791 struct relay_stream *ret;
792
793 lttng_ht_lookup(relay_streams_ht,
794 (void *)((unsigned long) stream_id),
795 &iter);
796 node = lttng_ht_iter_get_node_ulong(&iter);
797 if (node == NULL) {
798 DBG("Relay stream %" PRIu64 " not found", stream_id);
799 ret = NULL;
800 goto end;
801 }
802
803 ret = caa_container_of(node, struct relay_stream, stream_n);
804
805 end:
806 return ret;
807 }
808
809 static
810 void deferred_free_stream(struct rcu_head *head)
811 {
812 struct relay_stream *stream =
813 caa_container_of(head, struct relay_stream, rcu_node);
814
815 free(stream->path_name);
816 free(stream->channel_name);
817 free(stream);
818 }
819
820 static
821 void deferred_free_session(struct rcu_head *head)
822 {
823 struct relay_session *session =
824 caa_container_of(head, struct relay_session, rcu_node);
825 free(session);
826 }
827
828 /*
829 * Close a given stream. The stream is freed using a call RCU.
830 *
831 * RCU read side lock MUST be acquired. If NO close_stream_check() was called
832 * BEFORE the stream lock MUST be acquired.
833 */
834 static void destroy_stream(struct relay_stream *stream)
835 {
836 int delret;
837 struct relay_viewer_stream *vstream;
838 struct lttng_ht_iter iter;
839
840 assert(stream);
841
842 delret = close(stream->fd);
843 if (delret < 0) {
844 PERROR("close stream");
845 }
846
847 if (stream->index_fd >= 0) {
848 delret = close(stream->index_fd);
849 if (delret < 0) {
850 PERROR("close stream index_fd");
851 }
852 }
853
854 vstream = live_find_viewer_stream_by_id(stream->stream_handle);
855 if (vstream) {
856 /*
857 * Set the last good value into the viewer stream. This is done
858 * right before the stream gets deleted from the hash table. The
859 * lookup failure on the live thread side of a stream indicates
860 * that the viewer stream index received value should be used.
861 */
862 pthread_mutex_lock(&stream->viewer_stream_rotation_lock);
863 vstream->total_index_received = stream->total_index_received;
864 vstream->tracefile_count_last = stream->tracefile_count_current;
865 vstream->close_write_flag = 1;
866 pthread_mutex_unlock(&stream->viewer_stream_rotation_lock);
867 }
868
869 /* Cleanup index of that stream. */
870 relay_index_destroy_by_stream_id(stream->stream_handle);
871
872 iter.iter.node = &stream->stream_n.node;
873 delret = lttng_ht_del(relay_streams_ht, &iter);
874 assert(!delret);
875 iter.iter.node = &stream->ctf_trace_node.node;
876 delret = lttng_ht_del(stream->ctf_traces_ht, &iter);
877 assert(!delret);
878
879 if (stream->ctf_trace) {
880 ctf_trace_try_destroy(stream->ctf_trace);
881 }
882
883 call_rcu(&stream->rcu_node, deferred_free_stream);
884 DBG("Closed tracefile %d from close stream", stream->fd);
885 }
886
887 /*
888 * relay_delete_session: Free all memory associated with a session and
889 * close all the FDs
890 */
891 static
892 void relay_delete_session(struct relay_command *cmd,
893 struct lttng_ht *sessions_ht)
894 {
895 struct lttng_ht_iter iter;
896 struct lttng_ht_node_ulong *node;
897 struct relay_stream *stream;
898 int ret;
899
900 if (!cmd->session) {
901 return;
902 }
903
904 DBG("Relay deleting session %" PRIu64, cmd->session->id);
905
906 rcu_read_lock();
907 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, node, node) {
908 node = lttng_ht_iter_get_node_ulong(&iter);
909 if (!node) {
910 continue;
911 }
912 stream = caa_container_of(node, struct relay_stream, stream_n);
913 if (stream->session == cmd->session) {
914 destroy_stream(stream);
915 cmd->session->stream_count--;
916 assert(cmd->session->stream_count >= 0);
917 }
918 }
919
920 /* Make this session not visible anymore. */
921 iter.iter.node = &cmd->session->session_n.node;
922 ret = lttng_ht_del(sessions_ht, &iter);
923 assert(!ret);
924 call_rcu(&cmd->session->rcu_node, deferred_free_session);
925 rcu_read_unlock();
926 }
927
928 /*
929 * Copy index data from the control port to a given index object.
930 */
931 static void copy_index_control_data(struct relay_index *index,
932 struct lttcomm_relayd_index *data)
933 {
934 assert(index);
935 assert(data);
936
937 /*
938 * The index on disk is encoded in big endian, so we don't need to convert
939 * the data received on the network. The data_offset value is NEVER
940 * modified here and is updated by the data thread.
941 */
942 index->index_data.packet_size = data->packet_size;
943 index->index_data.content_size = data->content_size;
944 index->index_data.timestamp_begin = data->timestamp_begin;
945 index->index_data.timestamp_end = data->timestamp_end;
946 index->index_data.events_discarded = data->events_discarded;
947 index->index_data.stream_id = data->stream_id;
948 }
949
950 /*
951 * Handle the RELAYD_CREATE_SESSION command.
952 *
953 * On success, send back the session id or else return a negative value.
954 */
955 static
956 int relay_create_session(struct lttcomm_relayd_hdr *recv_hdr,
957 struct relay_command *cmd,
958 struct lttng_ht *sessions_ht)
959 {
960 int ret = 0, send_ret;
961 struct relay_session *session;
962 struct lttcomm_relayd_status_session reply;
963
964 assert(recv_hdr);
965 assert(cmd);
966
967 memset(&reply, 0, sizeof(reply));
968
969 session = zmalloc(sizeof(struct relay_session));
970 if (session == NULL) {
971 PERROR("relay session zmalloc");
972 ret = -1;
973 goto error;
974 }
975
976 session->id = ++last_relay_session_id;
977 session->sock = cmd->sock;
978 session->minor = cmd->minor;
979 session->major = cmd->major;
980 cmd->session = session;
981
982 reply.session_id = htobe64(session->id);
983
984 switch (cmd->minor) {
985 case 4: /* LTTng sessiond 2.4 */
986 default:
987 ret = cmd_create_session_2_4(cmd, session);
988 break;
989 }
990
991 lttng_ht_node_init_ulong(&session->session_n,
992 (unsigned long) session->id);
993 lttng_ht_add_unique_ulong(sessions_ht,
994 &session->session_n);
995
996 DBG("Created session %" PRIu64, session->id);
997
998 error:
999 if (ret < 0) {
1000 reply.ret_code = htobe32(LTTNG_ERR_FATAL);
1001 } else {
1002 reply.ret_code = htobe32(LTTNG_OK);
1003 }
1004
1005 send_ret = cmd->sock->ops->sendmsg(cmd->sock, &reply, sizeof(reply), 0);
1006 if (send_ret < 0) {
1007 ERR("Relayd sending session id");
1008 ret = send_ret;
1009 }
1010
1011 return ret;
1012 }
1013
1014 /*
1015 * When we have received all the streams and the metadata for a channel,
1016 * we make them visible to the viewer threads.
1017 */
1018 static
1019 void set_viewer_ready_flag(struct relay_command *cmd)
1020 {
1021 struct relay_stream_recv_handle *node, *tmp_node;
1022
1023 cds_list_for_each_entry_safe(node, tmp_node, &cmd->recv_head, node) {
1024 struct relay_stream *stream;
1025
1026 rcu_read_lock();
1027 stream = relay_stream_find_by_id(node->id);
1028 if (!stream) {
1029 /*
1030 * Stream is most probably being cleaned up by the data thread thus
1031 * simply continue to the next one.
1032 */
1033 continue;
1034 }
1035
1036 /*
1037 * If any of the streams in the list doesn't have a ctf_trace assigned,
1038 * it means that we never received the metadata stream, so we have to
1039 * wait until it arrives to make the streams available to the viewer.
1040 */
1041 if (!stream->ctf_trace) {
1042 goto end;
1043 }
1044
1045 stream->viewer_ready = 1;
1046 rcu_read_unlock();
1047
1048 /* Clean stream handle node. */
1049 cds_list_del(&node->node);
1050 free(node);
1051 }
1052
1053 end:
1054 return;
1055 }
1056
1057 /*
1058 * Add a recv handle node to the connection recv list with the given stream
1059 * handle. A new node is allocated thus must be freed when the node is deleted
1060 * from the list.
1061 */
1062 static void queue_stream_handle(uint64_t handle, struct relay_command *cmd)
1063 {
1064 struct relay_stream_recv_handle *node;
1065
1066 assert(cmd);
1067
1068 node = zmalloc(sizeof(*node));
1069 if (!node) {
1070 PERROR("zmalloc queue stream handle");
1071 return;
1072 }
1073
1074 node->id = handle;
1075 cds_list_add(&node->node, &cmd->recv_head);
1076 }
1077
1078 /*
1079 * relay_add_stream: allocate a new stream for a session
1080 */
1081 static
1082 int relay_add_stream(struct lttcomm_relayd_hdr *recv_hdr,
1083 struct relay_command *cmd, struct lttng_ht *sessions_ht)
1084 {
1085 struct relay_session *session = cmd->session;
1086 struct relay_stream *stream = NULL;
1087 struct lttcomm_relayd_status_stream reply;
1088 int ret, send_ret;
1089
1090 if (!session || cmd->version_check_done == 0) {
1091 ERR("Trying to add a stream before version check");
1092 ret = -1;
1093 goto end_no_session;
1094 }
1095
1096 stream = zmalloc(sizeof(struct relay_stream));
1097 if (stream == NULL) {
1098 PERROR("relay stream zmalloc");
1099 ret = -1;
1100 goto end_no_session;
1101 }
1102
1103 switch (cmd->minor) {
1104 case 1: /* LTTng sessiond 2.1 */
1105 ret = cmd_recv_stream_2_1(cmd, stream);
1106 break;
1107 case 2: /* LTTng sessiond 2.2 */
1108 default:
1109 ret = cmd_recv_stream_2_2(cmd, stream);
1110 break;
1111 }
1112 if (ret < 0) {
1113 goto err_free_stream;
1114 }
1115
1116 rcu_read_lock();
1117 stream->stream_handle = ++last_relay_stream_id;
1118 stream->prev_seq = -1ULL;
1119 stream->session = session;
1120 stream->index_fd = -1;
1121 stream->read_index_fd = -1;
1122 stream->ctf_trace = NULL;
1123 pthread_mutex_init(&stream->lock, NULL);
1124
1125 ret = utils_mkdir_recursive(stream->path_name, S_IRWXU | S_IRWXG);
1126 if (ret < 0) {
1127 ERR("relay creating output directory");
1128 goto end;
1129 }
1130
1131 /*
1132 * No need to use run_as API here because whatever we receives, the relayd
1133 * uses its own credentials for the stream files.
1134 */
1135 ret = utils_create_stream_file(stream->path_name, stream->channel_name,
1136 stream->tracefile_size, 0, relayd_uid, relayd_gid, NULL);
1137 if (ret < 0) {
1138 ERR("Create output file");
1139 goto end;
1140 }
1141 stream->fd = ret;
1142 if (stream->tracefile_size) {
1143 DBG("Tracefile %s/%s_0 created", stream->path_name, stream->channel_name);
1144 } else {
1145 DBG("Tracefile %s/%s created", stream->path_name, stream->channel_name);
1146 }
1147
1148 if (!strncmp(stream->channel_name, DEFAULT_METADATA_NAME, NAME_MAX)) {
1149 stream->metadata_flag = 1;
1150 /*
1151 * When we receive a new metadata stream, we create a new
1152 * ctf_trace and we assign this ctf_trace to all streams with
1153 * the same path.
1154 *
1155 * If later on we receive a new stream for the same ctf_trace,
1156 * we copy the information from the first hit in the HT to the
1157 * new stream.
1158 */
1159 stream->ctf_trace = ctf_trace_create();
1160 if (!stream->ctf_trace) {
1161 ret = -1;
1162 goto end;
1163 }
1164 stream->ctf_trace->refcount++;
1165 stream->ctf_trace->metadata_stream = stream;
1166 }
1167 ctf_trace_assign(cmd->ctf_traces_ht, stream);
1168 stream->ctf_traces_ht = cmd->ctf_traces_ht;
1169
1170 /*
1171 * Add the stream handle in the recv list of the connection. Once the end
1172 * stream message is received, this list is emptied and streams are set
1173 * with the viewer ready flag.
1174 */
1175 queue_stream_handle(stream->stream_handle, cmd);
1176
1177 lttng_ht_node_init_ulong(&stream->stream_n,
1178 (unsigned long) stream->stream_handle);
1179 lttng_ht_add_unique_ulong(relay_streams_ht,
1180 &stream->stream_n);
1181
1182 lttng_ht_node_init_str(&stream->ctf_trace_node, stream->path_name);
1183 lttng_ht_add_str(cmd->ctf_traces_ht, &stream->ctf_trace_node);
1184 session->stream_count++;
1185
1186 DBG("Relay new stream added %s with ID %" PRIu64, stream->channel_name,
1187 stream->stream_handle);
1188
1189 end:
1190 reply.handle = htobe64(stream->stream_handle);
1191 /* send the session id to the client or a negative return code on error */
1192 if (ret < 0) {
1193 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1194 /* stream was not properly added to the ht, so free it */
1195 free(stream);
1196 } else {
1197 reply.ret_code = htobe32(LTTNG_OK);
1198 }
1199
1200 send_ret = cmd->sock->ops->sendmsg(cmd->sock, &reply,
1201 sizeof(struct lttcomm_relayd_status_stream), 0);
1202 if (send_ret < 0) {
1203 ERR("Relay sending stream id");
1204 ret = send_ret;
1205 }
1206 rcu_read_unlock();
1207
1208 end_no_session:
1209 return ret;
1210
1211 err_free_stream:
1212 free(stream->path_name);
1213 free(stream->channel_name);
1214 free(stream);
1215 return ret;
1216 }
1217
1218 /*
1219 * relay_close_stream: close a specific stream
1220 */
1221 static
1222 int relay_close_stream(struct lttcomm_relayd_hdr *recv_hdr,
1223 struct relay_command *cmd)
1224 {
1225 int ret, send_ret;
1226 struct relay_session *session = cmd->session;
1227 struct lttcomm_relayd_close_stream stream_info;
1228 struct lttcomm_relayd_generic_reply reply;
1229 struct relay_stream *stream;
1230
1231 DBG("Close stream received");
1232
1233 if (!session || cmd->version_check_done == 0) {
1234 ERR("Trying to close a stream before version check");
1235 ret = -1;
1236 goto end_no_session;
1237 }
1238
1239 ret = cmd->sock->ops->recvmsg(cmd->sock, &stream_info,
1240 sizeof(struct lttcomm_relayd_close_stream), 0);
1241 if (ret < sizeof(struct lttcomm_relayd_close_stream)) {
1242 if (ret == 0) {
1243 /* Orderly shutdown. Not necessary to print an error. */
1244 DBG("Socket %d did an orderly shutdown", cmd->sock->fd);
1245 } else {
1246 ERR("Relay didn't receive valid add_stream struct size : %d", ret);
1247 }
1248 ret = -1;
1249 goto end_no_session;
1250 }
1251
1252 rcu_read_lock();
1253 stream = relay_stream_find_by_id(be64toh(stream_info.stream_id));
1254 if (!stream) {
1255 ret = -1;
1256 goto end_unlock;
1257 }
1258
1259 stream->last_net_seq_num = be64toh(stream_info.last_net_seq_num);
1260 stream->close_flag = 1;
1261 session->stream_count--;
1262 assert(session->stream_count >= 0);
1263
1264 if (close_stream_check(stream)) {
1265 destroy_stream(stream);
1266 }
1267
1268 end_unlock:
1269 rcu_read_unlock();
1270
1271 if (ret < 0) {
1272 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1273 } else {
1274 reply.ret_code = htobe32(LTTNG_OK);
1275 }
1276 send_ret = cmd->sock->ops->sendmsg(cmd->sock, &reply,
1277 sizeof(struct lttcomm_relayd_generic_reply), 0);
1278 if (send_ret < 0) {
1279 ERR("Relay sending stream id");
1280 ret = send_ret;
1281 }
1282
1283 end_no_session:
1284 return ret;
1285 }
1286
1287 /*
1288 * relay_unknown_command: send -1 if received unknown command
1289 */
1290 static
1291 void relay_unknown_command(struct relay_command *cmd)
1292 {
1293 struct lttcomm_relayd_generic_reply reply;
1294 int ret;
1295
1296 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1297 ret = cmd->sock->ops->sendmsg(cmd->sock, &reply,
1298 sizeof(struct lttcomm_relayd_generic_reply), 0);
1299 if (ret < 0) {
1300 ERR("Relay sending unknown command");
1301 }
1302 }
1303
1304 /*
1305 * relay_start: send an acknowledgment to the client to tell if we are
1306 * ready to receive data. We are ready if a session is established.
1307 */
1308 static
1309 int relay_start(struct lttcomm_relayd_hdr *recv_hdr,
1310 struct relay_command *cmd)
1311 {
1312 int ret = htobe32(LTTNG_OK);
1313 struct lttcomm_relayd_generic_reply reply;
1314 struct relay_session *session = cmd->session;
1315
1316 if (!session) {
1317 DBG("Trying to start the streaming without a session established");
1318 ret = htobe32(LTTNG_ERR_UNK);
1319 }
1320
1321 reply.ret_code = ret;
1322 ret = cmd->sock->ops->sendmsg(cmd->sock, &reply,
1323 sizeof(struct lttcomm_relayd_generic_reply), 0);
1324 if (ret < 0) {
1325 ERR("Relay sending start ack");
1326 }
1327
1328 return ret;
1329 }
1330
1331 /*
1332 * Append padding to the file pointed by the file descriptor fd.
1333 */
1334 static int write_padding_to_file(int fd, uint32_t size)
1335 {
1336 ssize_t ret = 0;
1337 char *zeros;
1338
1339 if (size == 0) {
1340 goto end;
1341 }
1342
1343 zeros = zmalloc(size);
1344 if (zeros == NULL) {
1345 PERROR("zmalloc zeros for padding");
1346 ret = -1;
1347 goto end;
1348 }
1349
1350 ret = lttng_write(fd, zeros, size);
1351 if (ret < size) {
1352 PERROR("write padding to file");
1353 }
1354
1355 free(zeros);
1356
1357 end:
1358 return ret;
1359 }
1360
1361 /*
1362 * relay_recv_metadata: receive the metada for the session.
1363 */
1364 static
1365 int relay_recv_metadata(struct lttcomm_relayd_hdr *recv_hdr,
1366 struct relay_command *cmd)
1367 {
1368 int ret = htobe32(LTTNG_OK);
1369 ssize_t size_ret;
1370 struct relay_session *session = cmd->session;
1371 struct lttcomm_relayd_metadata_payload *metadata_struct;
1372 struct relay_stream *metadata_stream;
1373 uint64_t data_size, payload_size;
1374
1375 if (!session) {
1376 ERR("Metadata sent before version check");
1377 ret = -1;
1378 goto end;
1379 }
1380
1381 data_size = payload_size = be64toh(recv_hdr->data_size);
1382 if (data_size < sizeof(struct lttcomm_relayd_metadata_payload)) {
1383 ERR("Incorrect data size");
1384 ret = -1;
1385 goto end;
1386 }
1387 payload_size -= sizeof(struct lttcomm_relayd_metadata_payload);
1388
1389 if (data_buffer_size < data_size) {
1390 /* In case the realloc fails, we can free the memory */
1391 char *tmp_data_ptr;
1392
1393 tmp_data_ptr = realloc(data_buffer, data_size);
1394 if (!tmp_data_ptr) {
1395 ERR("Allocating data buffer");
1396 free(data_buffer);
1397 ret = -1;
1398 goto end;
1399 }
1400 data_buffer = tmp_data_ptr;
1401 data_buffer_size = data_size;
1402 }
1403 memset(data_buffer, 0, data_size);
1404 DBG2("Relay receiving metadata, waiting for %" PRIu64 " bytes", data_size);
1405 ret = cmd->sock->ops->recvmsg(cmd->sock, data_buffer, data_size, 0);
1406 if (ret < 0 || ret != data_size) {
1407 if (ret == 0) {
1408 /* Orderly shutdown. Not necessary to print an error. */
1409 DBG("Socket %d did an orderly shutdown", cmd->sock->fd);
1410 } else {
1411 ERR("Relay didn't receive the whole metadata");
1412 }
1413 ret = -1;
1414 goto end;
1415 }
1416 metadata_struct = (struct lttcomm_relayd_metadata_payload *) data_buffer;
1417
1418 rcu_read_lock();
1419 metadata_stream = relay_stream_find_by_id(
1420 be64toh(metadata_struct->stream_id));
1421 if (!metadata_stream) {
1422 ret = -1;
1423 goto end_unlock;
1424 }
1425
1426 size_ret = lttng_write(metadata_stream->fd, metadata_struct->payload,
1427 payload_size);
1428 if (size_ret < payload_size) {
1429 ERR("Relay error writing metadata on file");
1430 ret = -1;
1431 goto end_unlock;
1432 }
1433
1434 ret = write_padding_to_file(metadata_stream->fd,
1435 be32toh(metadata_struct->padding_size));
1436 if (ret < 0) {
1437 goto end_unlock;
1438 }
1439 metadata_stream->ctf_trace->metadata_received +=
1440 payload_size + be32toh(metadata_struct->padding_size);
1441
1442 DBG2("Relay metadata written");
1443
1444 end_unlock:
1445 rcu_read_unlock();
1446 end:
1447 return ret;
1448 }
1449
1450 /*
1451 * relay_send_version: send relayd version number
1452 */
1453 static
1454 int relay_send_version(struct lttcomm_relayd_hdr *recv_hdr,
1455 struct relay_command *cmd, struct lttng_ht *sessions_ht)
1456 {
1457 int ret;
1458 struct lttcomm_relayd_version reply, msg;
1459
1460 assert(cmd);
1461
1462 cmd->version_check_done = 1;
1463
1464 /* Get version from the other side. */
1465 ret = cmd->sock->ops->recvmsg(cmd->sock, &msg, sizeof(msg), 0);
1466 if (ret < 0 || ret != sizeof(msg)) {
1467 if (ret == 0) {
1468 /* Orderly shutdown. Not necessary to print an error. */
1469 DBG("Socket %d did an orderly shutdown", cmd->sock->fd);
1470 } else {
1471 ERR("Relay failed to receive the version values.");
1472 }
1473 ret = -1;
1474 goto end;
1475 }
1476
1477 reply.major = RELAYD_VERSION_COMM_MAJOR;
1478 reply.minor = RELAYD_VERSION_COMM_MINOR;
1479
1480 /* Major versions must be the same */
1481 if (reply.major != be32toh(msg.major)) {
1482 DBG("Incompatible major versions (%u vs %u), deleting session",
1483 reply.major, be32toh(msg.major));
1484 relay_delete_session(cmd, sessions_ht);
1485 ret = 0;
1486 goto end;
1487 }
1488
1489 cmd->major = reply.major;
1490 /* We adapt to the lowest compatible version */
1491 if (reply.minor <= be32toh(msg.minor)) {
1492 cmd->minor = reply.minor;
1493 } else {
1494 cmd->minor = be32toh(msg.minor);
1495 }
1496
1497 reply.major = htobe32(reply.major);
1498 reply.minor = htobe32(reply.minor);
1499 ret = cmd->sock->ops->sendmsg(cmd->sock, &reply,
1500 sizeof(struct lttcomm_relayd_version), 0);
1501 if (ret < 0) {
1502 ERR("Relay sending version");
1503 }
1504
1505 DBG("Version check done using protocol %u.%u", cmd->major,
1506 cmd->minor);
1507
1508 end:
1509 return ret;
1510 }
1511
1512 /*
1513 * Check for data pending for a given stream id from the session daemon.
1514 */
1515 static
1516 int relay_data_pending(struct lttcomm_relayd_hdr *recv_hdr,
1517 struct relay_command *cmd)
1518 {
1519 struct relay_session *session = cmd->session;
1520 struct lttcomm_relayd_data_pending msg;
1521 struct lttcomm_relayd_generic_reply reply;
1522 struct relay_stream *stream;
1523 int ret;
1524 uint64_t last_net_seq_num, stream_id;
1525
1526 DBG("Data pending command received");
1527
1528 if (!session || cmd->version_check_done == 0) {
1529 ERR("Trying to check for data before version check");
1530 ret = -1;
1531 goto end_no_session;
1532 }
1533
1534 ret = cmd->sock->ops->recvmsg(cmd->sock, &msg, sizeof(msg), 0);
1535 if (ret < sizeof(msg)) {
1536 if (ret == 0) {
1537 /* Orderly shutdown. Not necessary to print an error. */
1538 DBG("Socket %d did an orderly shutdown", cmd->sock->fd);
1539 } else {
1540 ERR("Relay didn't receive valid data_pending struct size : %d",
1541 ret);
1542 }
1543 ret = -1;
1544 goto end_no_session;
1545 }
1546
1547 stream_id = be64toh(msg.stream_id);
1548 last_net_seq_num = be64toh(msg.last_net_seq_num);
1549
1550 rcu_read_lock();
1551 stream = relay_stream_find_by_id(stream_id);
1552 if (stream == NULL) {
1553 ret = -1;
1554 goto end_unlock;
1555 }
1556
1557 DBG("Data pending for stream id %" PRIu64 " prev_seq %" PRIu64
1558 " and last_seq %" PRIu64, stream_id, stream->prev_seq,
1559 last_net_seq_num);
1560
1561 /* Avoid wrapping issue */
1562 if (((int64_t) (stream->prev_seq - last_net_seq_num)) >= 0) {
1563 /* Data has in fact been written and is NOT pending */
1564 ret = 0;
1565 } else {
1566 /* Data still being streamed thus pending */
1567 ret = 1;
1568 }
1569
1570 /* Pending check is now done. */
1571 stream->data_pending_check_done = 1;
1572
1573 end_unlock:
1574 rcu_read_unlock();
1575
1576 reply.ret_code = htobe32(ret);
1577 ret = cmd->sock->ops->sendmsg(cmd->sock, &reply, sizeof(reply), 0);
1578 if (ret < 0) {
1579 ERR("Relay data pending ret code failed");
1580 }
1581
1582 end_no_session:
1583 return ret;
1584 }
1585
1586 /*
1587 * Wait for the control socket to reach a quiescent state.
1588 *
1589 * Note that for now, when receiving this command from the session daemon, this
1590 * means that every subsequent commands or data received on the control socket
1591 * has been handled. So, this is why we simply return OK here.
1592 */
1593 static
1594 int relay_quiescent_control(struct lttcomm_relayd_hdr *recv_hdr,
1595 struct relay_command *cmd)
1596 {
1597 int ret;
1598 uint64_t stream_id;
1599 struct relay_stream *stream;
1600 struct lttng_ht_iter iter;
1601 struct lttcomm_relayd_quiescent_control msg;
1602 struct lttcomm_relayd_generic_reply reply;
1603
1604 DBG("Checking quiescent state on control socket");
1605
1606 if (!cmd->session || cmd->version_check_done == 0) {
1607 ERR("Trying to check for data before version check");
1608 ret = -1;
1609 goto end_no_session;
1610 }
1611
1612 ret = cmd->sock->ops->recvmsg(cmd->sock, &msg, sizeof(msg), 0);
1613 if (ret < sizeof(msg)) {
1614 if (ret == 0) {
1615 /* Orderly shutdown. Not necessary to print an error. */
1616 DBG("Socket %d did an orderly shutdown", cmd->sock->fd);
1617 } else {
1618 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1619 ret);
1620 }
1621 ret = -1;
1622 goto end_no_session;
1623 }
1624
1625 stream_id = be64toh(msg.stream_id);
1626
1627 rcu_read_lock();
1628 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
1629 stream_n.node) {
1630 if (stream->stream_handle == stream_id) {
1631 stream->data_pending_check_done = 1;
1632 DBG("Relay quiescent control pending flag set to %" PRIu64,
1633 stream_id);
1634 break;
1635 }
1636 }
1637 rcu_read_unlock();
1638
1639 reply.ret_code = htobe32(LTTNG_OK);
1640 ret = cmd->sock->ops->sendmsg(cmd->sock, &reply, sizeof(reply), 0);
1641 if (ret < 0) {
1642 ERR("Relay data quiescent control ret code failed");
1643 }
1644
1645 end_no_session:
1646 return ret;
1647 }
1648
1649 /*
1650 * Initialize a data pending command. This means that a client is about to ask
1651 * for data pending for each stream he/she holds. Simply iterate over all
1652 * streams of a session and set the data_pending_check_done flag.
1653 *
1654 * This command returns to the client a LTTNG_OK code.
1655 */
1656 static
1657 int relay_begin_data_pending(struct lttcomm_relayd_hdr *recv_hdr,
1658 struct relay_command *cmd)
1659 {
1660 int ret;
1661 struct lttng_ht_iter iter;
1662 struct lttcomm_relayd_begin_data_pending msg;
1663 struct lttcomm_relayd_generic_reply reply;
1664 struct relay_stream *stream;
1665 uint64_t session_id;
1666
1667 assert(recv_hdr);
1668 assert(cmd);
1669
1670 DBG("Init streams for data pending");
1671
1672 if (!cmd->session || cmd->version_check_done == 0) {
1673 ERR("Trying to check for data before version check");
1674 ret = -1;
1675 goto end_no_session;
1676 }
1677
1678 ret = cmd->sock->ops->recvmsg(cmd->sock, &msg, sizeof(msg), 0);
1679 if (ret < sizeof(msg)) {
1680 if (ret == 0) {
1681 /* Orderly shutdown. Not necessary to print an error. */
1682 DBG("Socket %d did an orderly shutdown", cmd->sock->fd);
1683 } else {
1684 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1685 ret);
1686 }
1687 ret = -1;
1688 goto end_no_session;
1689 }
1690
1691 session_id = be64toh(msg.session_id);
1692
1693 /*
1694 * Iterate over all streams to set the begin data pending flag. For now, the
1695 * streams are indexed by stream handle so we have to iterate over all
1696 * streams to find the one associated with the right session_id.
1697 */
1698 rcu_read_lock();
1699 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
1700 stream_n.node) {
1701 if (stream->session->id == session_id) {
1702 stream->data_pending_check_done = 0;
1703 DBG("Set begin data pending flag to stream %" PRIu64,
1704 stream->stream_handle);
1705 }
1706 }
1707 rcu_read_unlock();
1708
1709 /* All good, send back reply. */
1710 reply.ret_code = htobe32(LTTNG_OK);
1711
1712 ret = cmd->sock->ops->sendmsg(cmd->sock, &reply, sizeof(reply), 0);
1713 if (ret < 0) {
1714 ERR("Relay begin data pending send reply failed");
1715 }
1716
1717 end_no_session:
1718 return ret;
1719 }
1720
1721 /*
1722 * End data pending command. This will check, for a given session id, if each
1723 * stream associated with it has its data_pending_check_done flag set. If not,
1724 * this means that the client lost track of the stream but the data is still
1725 * being streamed on our side. In this case, we inform the client that data is
1726 * inflight.
1727 *
1728 * Return to the client if there is data in flight or not with a ret_code.
1729 */
1730 static
1731 int relay_end_data_pending(struct lttcomm_relayd_hdr *recv_hdr,
1732 struct relay_command *cmd)
1733 {
1734 int ret;
1735 struct lttng_ht_iter iter;
1736 struct lttcomm_relayd_end_data_pending msg;
1737 struct lttcomm_relayd_generic_reply reply;
1738 struct relay_stream *stream;
1739 uint64_t session_id;
1740 uint32_t is_data_inflight = 0;
1741
1742 assert(recv_hdr);
1743 assert(cmd);
1744
1745 DBG("End data pending command");
1746
1747 if (!cmd->session || cmd->version_check_done == 0) {
1748 ERR("Trying to check for data before version check");
1749 ret = -1;
1750 goto end_no_session;
1751 }
1752
1753 ret = cmd->sock->ops->recvmsg(cmd->sock, &msg, sizeof(msg), 0);
1754 if (ret < sizeof(msg)) {
1755 if (ret == 0) {
1756 /* Orderly shutdown. Not necessary to print an error. */
1757 DBG("Socket %d did an orderly shutdown", cmd->sock->fd);
1758 } else {
1759 ERR("Relay didn't receive valid end data_pending struct size: %d",
1760 ret);
1761 }
1762 ret = -1;
1763 goto end_no_session;
1764 }
1765
1766 session_id = be64toh(msg.session_id);
1767
1768 /* Iterate over all streams to see if the begin data pending flag is set. */
1769 rcu_read_lock();
1770 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
1771 stream_n.node) {
1772 if (stream->session->id == session_id &&
1773 !stream->data_pending_check_done) {
1774 is_data_inflight = 1;
1775 DBG("Data is still in flight for stream %" PRIu64,
1776 stream->stream_handle);
1777 break;
1778 }
1779 }
1780 rcu_read_unlock();
1781
1782 /* All good, send back reply. */
1783 reply.ret_code = htobe32(is_data_inflight);
1784
1785 ret = cmd->sock->ops->sendmsg(cmd->sock, &reply, sizeof(reply), 0);
1786 if (ret < 0) {
1787 ERR("Relay end data pending send reply failed");
1788 }
1789
1790 end_no_session:
1791 return ret;
1792 }
1793
1794 /*
1795 * Receive an index for a specific stream.
1796 *
1797 * Return 0 on success else a negative value.
1798 */
1799 static
1800 int relay_recv_index(struct lttcomm_relayd_hdr *recv_hdr,
1801 struct relay_command *cmd)
1802 {
1803 int ret, send_ret, index_created = 0;
1804 struct relay_session *session = cmd->session;
1805 struct lttcomm_relayd_index index_info;
1806 struct relay_index *index, *wr_index = NULL;
1807 struct lttcomm_relayd_generic_reply reply;
1808 struct relay_stream *stream;
1809 uint64_t net_seq_num;
1810
1811 assert(cmd);
1812
1813 DBG("Relay receiving index");
1814
1815 if (!session || cmd->version_check_done == 0) {
1816 ERR("Trying to close a stream before version check");
1817 ret = -1;
1818 goto end_no_session;
1819 }
1820
1821 ret = cmd->sock->ops->recvmsg(cmd->sock, &index_info,
1822 sizeof(index_info), 0);
1823 if (ret < sizeof(index_info)) {
1824 if (ret == 0) {
1825 /* Orderly shutdown. Not necessary to print an error. */
1826 DBG("Socket %d did an orderly shutdown", cmd->sock->fd);
1827 } else {
1828 ERR("Relay didn't receive valid index struct size : %d", ret);
1829 }
1830 ret = -1;
1831 goto end_no_session;
1832 }
1833
1834 net_seq_num = be64toh(index_info.net_seq_num);
1835
1836 rcu_read_lock();
1837 stream = relay_stream_find_by_id(be64toh(index_info.relay_stream_id));
1838 if (!stream) {
1839 ret = -1;
1840 goto end_rcu_unlock;
1841 }
1842
1843 /* Live beacon handling */
1844 if (index_info.packet_size == 0) {
1845 DBG("Received live beacon for stream %" PRIu64, stream->stream_handle);
1846
1847 /*
1848 * Only flag a stream inactive when it has already received data.
1849 */
1850 if (stream->total_index_received > 0) {
1851 stream->beacon_ts_end = be64toh(index_info.timestamp_end);
1852 }
1853 ret = 0;
1854 goto end_rcu_unlock;
1855 } else {
1856 stream->beacon_ts_end = -1ULL;
1857 }
1858
1859 index = relay_index_find(stream->stream_handle, net_seq_num);
1860 if (!index) {
1861 /* A successful creation will add the object to the HT. */
1862 index = relay_index_create(stream->stream_handle, net_seq_num);
1863 if (!index) {
1864 goto end_rcu_unlock;
1865 }
1866 index_created = 1;
1867 }
1868
1869 copy_index_control_data(index, &index_info);
1870
1871 if (index_created) {
1872 /*
1873 * Try to add the relay index object to the hash table. If an object
1874 * already exist, destroy back the index created, set the data in this
1875 * object and write it on disk.
1876 */
1877 relay_index_add(index, &wr_index);
1878 if (wr_index) {
1879 copy_index_control_data(wr_index, &index_info);
1880 free(index);
1881 }
1882 } else {
1883 /* The index already exists so write it on disk. */
1884 wr_index = index;
1885 }
1886
1887 /* Do we have a writable ready index to write on disk. */
1888 if (wr_index) {
1889 /* Starting at 2.4, create the index file if none available. */
1890 if (cmd->minor >= 4 && stream->index_fd < 0) {
1891 ret = index_create_file(stream->path_name, stream->channel_name,
1892 relayd_uid, relayd_gid, stream->tracefile_size,
1893 stream->tracefile_count_current);
1894 if (ret < 0) {
1895 goto end_rcu_unlock;
1896 }
1897 stream->index_fd = ret;
1898 }
1899
1900 ret = relay_index_write(wr_index->fd, wr_index);
1901 if (ret < 0) {
1902 goto end_rcu_unlock;
1903 }
1904 stream->total_index_received++;
1905 }
1906
1907 end_rcu_unlock:
1908 rcu_read_unlock();
1909
1910 if (ret < 0) {
1911 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1912 } else {
1913 reply.ret_code = htobe32(LTTNG_OK);
1914 }
1915 send_ret = cmd->sock->ops->sendmsg(cmd->sock, &reply, sizeof(reply), 0);
1916 if (send_ret < 0) {
1917 ERR("Relay sending close index id reply");
1918 ret = send_ret;
1919 }
1920
1921 end_no_session:
1922 return ret;
1923 }
1924
1925 /*
1926 * Receive the streams_sent message.
1927 *
1928 * Return 0 on success else a negative value.
1929 */
1930 static
1931 int relay_streams_sent(struct lttcomm_relayd_hdr *recv_hdr,
1932 struct relay_command *cmd)
1933 {
1934 int ret, send_ret;
1935 struct lttcomm_relayd_generic_reply reply;
1936
1937 assert(cmd);
1938
1939 DBG("Relay receiving streams_sent");
1940
1941 if (!cmd->session || cmd->version_check_done == 0) {
1942 ERR("Trying to close a stream before version check");
1943 ret = -1;
1944 goto end_no_session;
1945 }
1946
1947 /*
1948 * Flag every pending stream in the connection recv list that they are
1949 * ready to be used by the viewer.
1950 */
1951 set_viewer_ready_flag(cmd);
1952
1953 reply.ret_code = htobe32(LTTNG_OK);
1954 send_ret = cmd->sock->ops->sendmsg(cmd->sock, &reply, sizeof(reply), 0);
1955 if (send_ret < 0) {
1956 ERR("Relay sending sent_stream reply");
1957 ret = send_ret;
1958 } else {
1959 /* Success. */
1960 ret = 0;
1961 }
1962
1963 end_no_session:
1964 return ret;
1965 }
1966
1967 /*
1968 * Process the commands received on the control socket
1969 */
1970 static
1971 int relay_process_control(struct lttcomm_relayd_hdr *recv_hdr,
1972 struct relay_command *cmd, struct relay_local_data *ctx)
1973 {
1974 int ret = 0;
1975
1976 switch (be32toh(recv_hdr->cmd)) {
1977 case RELAYD_CREATE_SESSION:
1978 ret = relay_create_session(recv_hdr, cmd, ctx->sessions_ht);
1979 break;
1980 case RELAYD_ADD_STREAM:
1981 ret = relay_add_stream(recv_hdr, cmd, ctx->sessions_ht);
1982 break;
1983 case RELAYD_START_DATA:
1984 ret = relay_start(recv_hdr, cmd);
1985 break;
1986 case RELAYD_SEND_METADATA:
1987 ret = relay_recv_metadata(recv_hdr, cmd);
1988 break;
1989 case RELAYD_VERSION:
1990 ret = relay_send_version(recv_hdr, cmd, ctx->sessions_ht);
1991 break;
1992 case RELAYD_CLOSE_STREAM:
1993 ret = relay_close_stream(recv_hdr, cmd);
1994 break;
1995 case RELAYD_DATA_PENDING:
1996 ret = relay_data_pending(recv_hdr, cmd);
1997 break;
1998 case RELAYD_QUIESCENT_CONTROL:
1999 ret = relay_quiescent_control(recv_hdr, cmd);
2000 break;
2001 case RELAYD_BEGIN_DATA_PENDING:
2002 ret = relay_begin_data_pending(recv_hdr, cmd);
2003 break;
2004 case RELAYD_END_DATA_PENDING:
2005 ret = relay_end_data_pending(recv_hdr, cmd);
2006 break;
2007 case RELAYD_SEND_INDEX:
2008 ret = relay_recv_index(recv_hdr, cmd);
2009 break;
2010 case RELAYD_STREAMS_SENT:
2011 ret = relay_streams_sent(recv_hdr, cmd);
2012 break;
2013 case RELAYD_UPDATE_SYNC_INFO:
2014 default:
2015 ERR("Received unknown command (%u)", be32toh(recv_hdr->cmd));
2016 relay_unknown_command(cmd);
2017 ret = -1;
2018 goto end;
2019 }
2020
2021 end:
2022 return ret;
2023 }
2024
2025 /*
2026 * Handle index for a data stream.
2027 *
2028 * RCU read side lock MUST be acquired.
2029 *
2030 * Return 0 on success else a negative value.
2031 */
2032 static int handle_index_data(struct relay_stream *stream, uint64_t net_seq_num,
2033 int rotate_index)
2034 {
2035 int ret = 0, index_created = 0;
2036 uint64_t stream_id, data_offset;
2037 struct relay_index *index, *wr_index = NULL;
2038
2039 assert(stream);
2040
2041 stream_id = stream->stream_handle;
2042 /* Get data offset because we are about to update the index. */
2043 data_offset = htobe64(stream->tracefile_size_current);
2044
2045 /*
2046 * Lookup for an existing index for that stream id/sequence number. If on
2047 * exists, the control thread already received the data for it thus we need
2048 * to write it on disk.
2049 */
2050 index = relay_index_find(stream_id, net_seq_num);
2051 if (!index) {
2052 /* A successful creation will add the object to the HT. */
2053 index = relay_index_create(stream_id, net_seq_num);
2054 if (!index) {
2055 ret = -1;
2056 goto error;
2057 }
2058 index_created = 1;
2059 }
2060
2061 if (rotate_index || stream->index_fd < 0) {
2062 index->to_close_fd = stream->index_fd;
2063 ret = index_create_file(stream->path_name, stream->channel_name,
2064 relayd_uid, relayd_gid, stream->tracefile_size,
2065 stream->tracefile_count_current);
2066 if (ret < 0) {
2067 /* This will close the stream's index fd if one. */
2068 relay_index_free_safe(index);
2069 goto error;
2070 }
2071 stream->index_fd = ret;
2072 }
2073 index->fd = stream->index_fd;
2074 index->index_data.offset = data_offset;
2075
2076 if (index_created) {
2077 /*
2078 * Try to add the relay index object to the hash table. If an object
2079 * already exist, destroy back the index created and set the data.
2080 */
2081 relay_index_add(index, &wr_index);
2082 if (wr_index) {
2083 /* Copy back data from the created index. */
2084 wr_index->fd = index->fd;
2085 wr_index->to_close_fd = index->to_close_fd;
2086 wr_index->index_data.offset = data_offset;
2087 free(index);
2088 }
2089 } else {
2090 /* The index already exists so write it on disk. */
2091 wr_index = index;
2092 }
2093
2094 /* Do we have a writable ready index to write on disk. */
2095 if (wr_index) {
2096 ret = relay_index_write(wr_index->fd, wr_index);
2097 if (ret < 0) {
2098 goto error;
2099 }
2100 stream->total_index_received++;
2101 }
2102
2103 error:
2104 return ret;
2105 }
2106
2107 /*
2108 * relay_process_data: Process the data received on the data socket
2109 */
2110 static
2111 int relay_process_data(struct relay_command *cmd)
2112 {
2113 int ret = 0, rotate_index = 0;
2114 ssize_t size_ret;
2115 struct relay_stream *stream;
2116 struct lttcomm_relayd_data_hdr data_hdr;
2117 uint64_t stream_id;
2118 uint64_t net_seq_num;
2119 uint32_t data_size;
2120
2121 ret = cmd->sock->ops->recvmsg(cmd->sock, &data_hdr,
2122 sizeof(struct lttcomm_relayd_data_hdr), 0);
2123 if (ret <= 0) {
2124 if (ret == 0) {
2125 /* Orderly shutdown. Not necessary to print an error. */
2126 DBG("Socket %d did an orderly shutdown", cmd->sock->fd);
2127 } else {
2128 ERR("Unable to receive data header on sock %d", cmd->sock->fd);
2129 }
2130 ret = -1;
2131 goto end;
2132 }
2133
2134 stream_id = be64toh(data_hdr.stream_id);
2135
2136 rcu_read_lock();
2137 stream = relay_stream_find_by_id(stream_id);
2138 if (!stream) {
2139 ret = -1;
2140 goto end_rcu_unlock;
2141 }
2142
2143 data_size = be32toh(data_hdr.data_size);
2144 if (data_buffer_size < data_size) {
2145 char *tmp_data_ptr;
2146
2147 tmp_data_ptr = realloc(data_buffer, data_size);
2148 if (!tmp_data_ptr) {
2149 ERR("Allocating data buffer");
2150 free(data_buffer);
2151 ret = -1;
2152 goto end_rcu_unlock;
2153 }
2154 data_buffer = tmp_data_ptr;
2155 data_buffer_size = data_size;
2156 }
2157 memset(data_buffer, 0, data_size);
2158
2159 net_seq_num = be64toh(data_hdr.net_seq_num);
2160
2161 DBG3("Receiving data of size %u for stream id %" PRIu64 " seqnum %" PRIu64,
2162 data_size, stream_id, net_seq_num);
2163 ret = cmd->sock->ops->recvmsg(cmd->sock, data_buffer, data_size, 0);
2164 if (ret <= 0) {
2165 if (ret == 0) {
2166 /* Orderly shutdown. Not necessary to print an error. */
2167 DBG("Socket %d did an orderly shutdown", cmd->sock->fd);
2168 }
2169 ret = -1;
2170 goto end_rcu_unlock;
2171 }
2172
2173 /* Check if a rotation is needed. */
2174 if (stream->tracefile_size > 0 &&
2175 (stream->tracefile_size_current + data_size) >
2176 stream->tracefile_size) {
2177 struct relay_viewer_stream *vstream;
2178 uint64_t new_id;
2179
2180 new_id = (stream->tracefile_count_current + 1) %
2181 stream->tracefile_count;
2182 /*
2183 * When we wrap-around back to 0, we start overwriting old
2184 * trace data.
2185 */
2186 if (!stream->tracefile_overwrite && new_id == 0) {
2187 stream->tracefile_overwrite = 1;
2188 }
2189 pthread_mutex_lock(&stream->viewer_stream_rotation_lock);
2190 if (stream->tracefile_overwrite) {
2191 stream->oldest_tracefile_id =
2192 (stream->oldest_tracefile_id + 1) %
2193 stream->tracefile_count;
2194 }
2195 vstream = live_find_viewer_stream_by_id(stream->stream_handle);
2196 if (vstream) {
2197 /*
2198 * The viewer is reading a file about to be
2199 * overwritten. Close the FDs it is
2200 * currently using and let it handle the fault.
2201 */
2202 if (vstream->tracefile_count_current == new_id) {
2203 pthread_mutex_lock(&vstream->overwrite_lock);
2204 vstream->abort_flag = 1;
2205 pthread_mutex_unlock(&vstream->overwrite_lock);
2206 DBG("Streaming side setting abort_flag on stream %s_%lu\n",
2207 stream->channel_name, new_id);
2208 } else if (vstream->tracefile_count_current ==
2209 stream->tracefile_count_current) {
2210 /*
2211 * The reader and writer were in the
2212 * same trace file, inform the viewer
2213 * that no new index will ever be added
2214 * to this file.
2215 */
2216 vstream->close_write_flag = 1;
2217 }
2218 }
2219 ret = utils_rotate_stream_file(stream->path_name, stream->channel_name,
2220 stream->tracefile_size, stream->tracefile_count,
2221 relayd_uid, relayd_gid, stream->fd,
2222 &(stream->tracefile_count_current), &stream->fd);
2223 stream->total_index_received = 0;
2224 pthread_mutex_unlock(&stream->viewer_stream_rotation_lock);
2225 if (ret < 0) {
2226 ERR("Rotating stream output file");
2227 goto end_rcu_unlock;
2228 }
2229 /* Reset current size because we just perform a stream rotation. */
2230 stream->tracefile_size_current = 0;
2231 rotate_index = 1;
2232 }
2233
2234 /*
2235 * Index are handled in protocol version 2.4 and above. Also, snapshot and
2236 * index are NOT supported.
2237 */
2238 if (stream->session->minor >= 4 && !stream->session->snapshot) {
2239 ret = handle_index_data(stream, net_seq_num, rotate_index);
2240 if (ret < 0) {
2241 goto end_rcu_unlock;
2242 }
2243 }
2244
2245 /* Write data to stream output fd. */
2246 size_ret = lttng_write(stream->fd, data_buffer, data_size);
2247 if (size_ret < data_size) {
2248 ERR("Relay error writing data to file");
2249 ret = -1;
2250 goto end_rcu_unlock;
2251 }
2252
2253 DBG2("Relay wrote %d bytes to tracefile for stream id %" PRIu64,
2254 ret, stream->stream_handle);
2255
2256 ret = write_padding_to_file(stream->fd, be32toh(data_hdr.padding_size));
2257 if (ret < 0) {
2258 goto end_rcu_unlock;
2259 }
2260 stream->tracefile_size_current += data_size + be32toh(data_hdr.padding_size);
2261
2262 stream->prev_seq = net_seq_num;
2263
2264 /* Check if we need to close the FD */
2265 if (close_stream_check(stream)) {
2266 destroy_stream(stream);
2267 }
2268
2269 end_rcu_unlock:
2270 rcu_read_unlock();
2271 end:
2272 return ret;
2273 }
2274
2275 static
2276 void relay_cleanup_poll_connection(struct lttng_poll_event *events, int pollfd)
2277 {
2278 int ret;
2279
2280 lttng_poll_del(events, pollfd);
2281
2282 ret = close(pollfd);
2283 if (ret < 0) {
2284 ERR("Closing pollfd %d", pollfd);
2285 }
2286 }
2287
2288 static
2289 int relay_add_connection(int fd, struct lttng_poll_event *events,
2290 struct lttng_ht *relay_connections_ht)
2291 {
2292 struct relay_command *relay_connection;
2293 ssize_t ret;
2294
2295 relay_connection = zmalloc(sizeof(struct relay_command));
2296 if (relay_connection == NULL) {
2297 PERROR("Relay command zmalloc");
2298 goto error;
2299 }
2300 ret = lttng_read(fd, relay_connection, sizeof(struct relay_command));
2301 if (ret < sizeof(struct relay_command)) {
2302 PERROR("read relay cmd pipe");
2303 goto error_read;
2304 }
2305 CDS_INIT_LIST_HEAD(&relay_connection->recv_head);
2306
2307 /*
2308 * Only used by the control side and the reference is copied inside each
2309 * stream from that connection. Thus a destroy HT must be done after every
2310 * stream has been destroyed.
2311 */
2312 if (relay_connection->type == RELAY_CONTROL) {
2313 relay_connection->ctf_traces_ht = lttng_ht_new(0,
2314 LTTNG_HT_TYPE_STRING);
2315 if (!relay_connection->ctf_traces_ht) {
2316 goto error_read;
2317 }
2318 }
2319
2320 lttng_ht_node_init_ulong(&relay_connection->sock_n,
2321 (unsigned long) relay_connection->sock->fd);
2322 rcu_read_lock();
2323 lttng_ht_add_unique_ulong(relay_connections_ht,
2324 &relay_connection->sock_n);
2325 rcu_read_unlock();
2326 return lttng_poll_add(events,
2327 relay_connection->sock->fd,
2328 LPOLLIN | LPOLLRDHUP);
2329
2330 error_read:
2331 free(relay_connection);
2332 error:
2333 return -1;
2334 }
2335
2336 static
2337 void deferred_free_connection(struct rcu_head *head)
2338 {
2339 struct relay_command *relay_connection =
2340 caa_container_of(head, struct relay_command, rcu_node);
2341
2342 lttcomm_destroy_sock(relay_connection->sock);
2343 free(relay_connection);
2344 }
2345
2346 static
2347 void relay_del_connection(struct lttng_ht *relay_connections_ht,
2348 struct lttng_ht_iter *iter, struct relay_command *relay_connection,
2349 struct lttng_ht *sessions_ht)
2350 {
2351 int ret;
2352
2353 ret = lttng_ht_del(relay_connections_ht, iter);
2354 assert(!ret);
2355
2356 if (relay_connection->type == RELAY_CONTROL) {
2357 struct relay_stream_recv_handle *node, *tmp_node;
2358
2359 relay_delete_session(relay_connection, sessions_ht);
2360 lttng_ht_destroy(relay_connection->ctf_traces_ht);
2361
2362 /* Clean up recv list. */
2363 cds_list_for_each_entry_safe(node, tmp_node,
2364 &relay_connection->recv_head, node) {
2365 cds_list_del(&node->node);
2366 free(node);
2367 }
2368 }
2369
2370 call_rcu(&relay_connection->rcu_node, deferred_free_connection);
2371 }
2372
2373 /*
2374 * This thread does the actual work
2375 */
2376 static
2377 void *relay_thread_worker(void *data)
2378 {
2379 int ret, err = -1, last_seen_data_fd = -1;
2380 uint32_t nb_fd;
2381 struct relay_command *relay_connection;
2382 struct lttng_poll_event events;
2383 struct lttng_ht *relay_connections_ht;
2384 struct lttng_ht_node_ulong *node;
2385 struct lttng_ht_iter iter;
2386 struct lttcomm_relayd_hdr recv_hdr;
2387 struct relay_local_data *relay_ctx = (struct relay_local_data *) data;
2388 struct lttng_ht *sessions_ht = relay_ctx->sessions_ht;
2389
2390 DBG("[thread] Relay worker started");
2391
2392 rcu_register_thread();
2393
2394 health_register(health_relayd, HEALTH_RELAYD_TYPE_WORKER);
2395
2396 health_code_update();
2397
2398 /* table of connections indexed on socket */
2399 relay_connections_ht = lttng_ht_new(0, LTTNG_HT_TYPE_ULONG);
2400 if (!relay_connections_ht) {
2401 goto relay_connections_ht_error;
2402 }
2403
2404 /* Tables of received indexes indexed by index handle and net_seq_num. */
2405 indexes_ht = lttng_ht_new(0, LTTNG_HT_TYPE_TWO_U64);
2406 if (!indexes_ht) {
2407 goto indexes_ht_error;
2408 }
2409
2410 ret = create_thread_poll_set(&events, 2);
2411 if (ret < 0) {
2412 goto error_poll_create;
2413 }
2414
2415 ret = lttng_poll_add(&events, relay_cmd_pipe[0], LPOLLIN | LPOLLRDHUP);
2416 if (ret < 0) {
2417 goto error;
2418 }
2419
2420 restart:
2421 while (1) {
2422 int idx = -1, i, seen_control = 0, last_notdel_data_fd = -1;
2423
2424 health_code_update();
2425
2426 /* Infinite blocking call, waiting for transmission */
2427 DBG3("Relayd worker thread polling...");
2428 health_poll_entry();
2429 ret = lttng_poll_wait(&events, -1);
2430 health_poll_exit();
2431 if (ret < 0) {
2432 /*
2433 * Restart interrupted system call.
2434 */
2435 if (errno == EINTR) {
2436 goto restart;
2437 }
2438 goto error;
2439 }
2440
2441 nb_fd = ret;
2442
2443 /*
2444 * Process control. The control connection is prioritised so we don't
2445 * starve it with high throughout put tracing data on the data
2446 * connection.
2447 */
2448 for (i = 0; i < nb_fd; i++) {
2449 /* Fetch once the poll data */
2450 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
2451 int pollfd = LTTNG_POLL_GETFD(&events, i);
2452
2453 health_code_update();
2454
2455 /* Thread quit pipe has been closed. Killing thread. */
2456 ret = check_thread_quit_pipe(pollfd, revents);
2457 if (ret) {
2458 err = 0;
2459 goto exit;
2460 }
2461
2462 /* Inspect the relay cmd pipe for new connection */
2463 if (pollfd == relay_cmd_pipe[0]) {
2464 if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2465 ERR("Relay pipe error");
2466 goto error;
2467 } else if (revents & LPOLLIN) {
2468 DBG("Relay command received");
2469 ret = relay_add_connection(relay_cmd_pipe[0],
2470 &events, relay_connections_ht);
2471 if (ret < 0) {
2472 goto error;
2473 }
2474 }
2475 } else if (revents) {
2476 rcu_read_lock();
2477 lttng_ht_lookup(relay_connections_ht,
2478 (void *)((unsigned long) pollfd),
2479 &iter);
2480 node = lttng_ht_iter_get_node_ulong(&iter);
2481 if (node == NULL) {
2482 DBG2("Relay sock %d not found", pollfd);
2483 rcu_read_unlock();
2484 goto error;
2485 }
2486 relay_connection = caa_container_of(node,
2487 struct relay_command, sock_n);
2488
2489 if (revents & (LPOLLERR)) {
2490 ERR("POLL ERROR");
2491 relay_cleanup_poll_connection(&events, pollfd);
2492 relay_del_connection(relay_connections_ht,
2493 &iter, relay_connection, sessions_ht);
2494 if (last_seen_data_fd == pollfd) {
2495 last_seen_data_fd = last_notdel_data_fd;
2496 }
2497 } else if (revents & (LPOLLHUP | LPOLLRDHUP)) {
2498 DBG("Socket %d hung up", pollfd);
2499 relay_cleanup_poll_connection(&events, pollfd);
2500 relay_del_connection(relay_connections_ht,
2501 &iter, relay_connection, sessions_ht);
2502 if (last_seen_data_fd == pollfd) {
2503 last_seen_data_fd = last_notdel_data_fd;
2504 }
2505 } else if (revents & LPOLLIN) {
2506 /* control socket */
2507 if (relay_connection->type == RELAY_CONTROL) {
2508 ret = relay_connection->sock->ops->recvmsg(
2509 relay_connection->sock, &recv_hdr,
2510 sizeof(struct lttcomm_relayd_hdr), 0);
2511 /* connection closed */
2512 if (ret <= 0) {
2513 relay_cleanup_poll_connection(&events, pollfd);
2514 relay_del_connection(relay_connections_ht,
2515 &iter, relay_connection, sessions_ht);
2516 DBG("Control connection closed with %d", pollfd);
2517 } else {
2518 if (relay_connection->session) {
2519 DBG2("Relay worker receiving data for session : %" PRIu64,
2520 relay_connection->session->id);
2521 }
2522 ret = relay_process_control(&recv_hdr,
2523 relay_connection, relay_ctx);
2524 if (ret < 0) {
2525 /* Clear the session on error. */
2526 relay_cleanup_poll_connection(&events, pollfd);
2527 relay_del_connection(relay_connections_ht,
2528 &iter, relay_connection, sessions_ht);
2529 DBG("Connection closed with %d", pollfd);
2530 }
2531 seen_control = 1;
2532 }
2533 } else {
2534 /*
2535 * Flag the last seen data fd not deleted. It will be
2536 * used as the last seen fd if any fd gets deleted in
2537 * this first loop.
2538 */
2539 last_notdel_data_fd = pollfd;
2540 }
2541 }
2542 rcu_read_unlock();
2543 }
2544 }
2545
2546 /*
2547 * The last loop handled a control request, go back to poll to make
2548 * sure we prioritise the control socket.
2549 */
2550 if (seen_control) {
2551 continue;
2552 }
2553
2554 if (last_seen_data_fd >= 0) {
2555 for (i = 0; i < nb_fd; i++) {
2556 int pollfd = LTTNG_POLL_GETFD(&events, i);
2557
2558 health_code_update();
2559
2560 if (last_seen_data_fd == pollfd) {
2561 idx = i;
2562 break;
2563 }
2564 }
2565 }
2566
2567 /* Process data connection. */
2568 for (i = idx + 1; i < nb_fd; i++) {
2569 /* Fetch the poll data. */
2570 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
2571 int pollfd = LTTNG_POLL_GETFD(&events, i);
2572
2573 health_code_update();
2574
2575 /* Skip the command pipe. It's handled in the first loop. */
2576 if (pollfd == relay_cmd_pipe[0]) {
2577 continue;
2578 }
2579
2580 if (revents) {
2581 rcu_read_lock();
2582 lttng_ht_lookup(relay_connections_ht,
2583 (void *)((unsigned long) pollfd),
2584 &iter);
2585 node = lttng_ht_iter_get_node_ulong(&iter);
2586 if (node == NULL) {
2587 /* Skip it. Might be removed before. */
2588 rcu_read_unlock();
2589 continue;
2590 }
2591 relay_connection = caa_container_of(node,
2592 struct relay_command, sock_n);
2593
2594 if (revents & LPOLLIN) {
2595 if (relay_connection->type != RELAY_DATA) {
2596 continue;
2597 }
2598
2599 ret = relay_process_data(relay_connection);
2600 /* connection closed */
2601 if (ret < 0) {
2602 relay_cleanup_poll_connection(&events, pollfd);
2603 relay_del_connection(relay_connections_ht,
2604 &iter, relay_connection, sessions_ht);
2605 DBG("Data connection closed with %d", pollfd);
2606 /*
2607 * Every goto restart call sets the last seen fd where
2608 * here we don't really care since we gracefully
2609 * continue the loop after the connection is deleted.
2610 */
2611 } else {
2612 /* Keep last seen port. */
2613 last_seen_data_fd = pollfd;
2614 rcu_read_unlock();
2615 goto restart;
2616 }
2617 }
2618 rcu_read_unlock();
2619 }
2620 }
2621 last_seen_data_fd = -1;
2622 }
2623
2624 /* Normal exit, no error */
2625 ret = 0;
2626
2627 exit:
2628 error:
2629 lttng_poll_clean(&events);
2630
2631 /* empty the hash table and free the memory */
2632 rcu_read_lock();
2633 cds_lfht_for_each_entry(relay_connections_ht->ht, &iter.iter, node, node) {
2634 health_code_update();
2635
2636 node = lttng_ht_iter_get_node_ulong(&iter);
2637 if (node) {
2638 relay_connection = caa_container_of(node,
2639 struct relay_command, sock_n);
2640 relay_del_connection(relay_connections_ht,
2641 &iter, relay_connection, sessions_ht);
2642 }
2643 }
2644 rcu_read_unlock();
2645 error_poll_create:
2646 lttng_ht_destroy(indexes_ht);
2647 indexes_ht_error:
2648 lttng_ht_destroy(relay_connections_ht);
2649 relay_connections_ht_error:
2650 /* Close relay cmd pipes */
2651 utils_close_pipe(relay_cmd_pipe);
2652 if (err) {
2653 DBG("Thread exited with error");
2654 }
2655 DBG("Worker thread cleanup complete");
2656 free(data_buffer);
2657 if (err) {
2658 health_error();
2659 ERR("Health error occurred in %s", __func__);
2660 }
2661 health_unregister(health_relayd);
2662 rcu_unregister_thread();
2663 stop_threads();
2664 return NULL;
2665 }
2666
2667 /*
2668 * Create the relay command pipe to wake thread_manage_apps.
2669 * Closed in cleanup().
2670 */
2671 static int create_relay_cmd_pipe(void)
2672 {
2673 int ret;
2674
2675 ret = utils_create_pipe_cloexec(relay_cmd_pipe);
2676
2677 return ret;
2678 }
2679
2680 /*
2681 * main
2682 */
2683 int main(int argc, char **argv)
2684 {
2685 int ret = 0;
2686 void *status;
2687 struct relay_local_data *relay_ctx;
2688
2689 /* Create thread quit pipe */
2690 if ((ret = init_thread_quit_pipe()) < 0) {
2691 goto error;
2692 }
2693
2694 /* Parse arguments */
2695 progname = argv[0];
2696 if ((ret = parse_args(argc, argv)) < 0) {
2697 goto exit;
2698 }
2699
2700 if ((ret = set_signal_handler()) < 0) {
2701 goto exit;
2702 }
2703
2704 /* Try to create directory if -o, --output is specified. */
2705 if (opt_output_path) {
2706 if (*opt_output_path != '/') {
2707 ERR("Please specify an absolute path for -o, --output PATH");
2708 goto exit;
2709 }
2710
2711 ret = utils_mkdir_recursive(opt_output_path, S_IRWXU | S_IRWXG);
2712 if (ret < 0) {
2713 ERR("Unable to create %s", opt_output_path);
2714 goto exit;
2715 }
2716 }
2717
2718 /* Daemonize */
2719 if (opt_daemon) {
2720 ret = daemon(0, 0);
2721 if (ret < 0) {
2722 PERROR("daemon");
2723 goto exit;
2724 }
2725 }
2726
2727 /* We need those values for the file/dir creation. */
2728 relayd_uid = getuid();
2729 relayd_gid = getgid();
2730
2731 /* Check if daemon is UID = 0 */
2732 if (relayd_uid == 0) {
2733 if (control_uri->port < 1024 || data_uri->port < 1024 ||
2734 live_uri->port < 1024) {
2735 ERR("Need to be root to use ports < 1024");
2736 ret = -1;
2737 goto exit;
2738 }
2739 }
2740
2741 /* Setup the thread apps communication pipe. */
2742 if ((ret = create_relay_cmd_pipe()) < 0) {
2743 goto exit;
2744 }
2745
2746 /* Init relay command queue. */
2747 cds_wfq_init(&relay_cmd_queue.queue);
2748
2749 /* Set up max poll set size */
2750 lttng_poll_set_max_size();
2751
2752 /* Initialize communication library */
2753 lttcomm_init();
2754
2755 relay_ctx = zmalloc(sizeof(struct relay_local_data));
2756 if (!relay_ctx) {
2757 PERROR("relay_ctx");
2758 goto exit;
2759 }
2760
2761 /* tables of sessions indexed by session ID */
2762 relay_ctx->sessions_ht = lttng_ht_new(0, LTTNG_HT_TYPE_ULONG);
2763 if (!relay_ctx->sessions_ht) {
2764 goto exit_relay_ctx_sessions;
2765 }
2766
2767 /* tables of streams indexed by stream ID */
2768 relay_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_ULONG);
2769 if (!relay_streams_ht) {
2770 goto exit_relay_ctx_streams;
2771 }
2772
2773 /* tables of streams indexed by stream ID */
2774 viewer_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
2775 if (!viewer_streams_ht) {
2776 goto exit_relay_ctx_viewer_streams;
2777 }
2778
2779 /* Initialize thread health monitoring */
2780 health_relayd = health_app_create(NR_HEALTH_RELAYD_TYPES);
2781 if (!health_relayd) {
2782 PERROR("health_app_create error");
2783 goto exit_health_app_create;
2784 }
2785
2786 ret = utils_create_pipe(health_quit_pipe);
2787 if (ret < 0) {
2788 goto error_health_pipe;
2789 }
2790
2791 /* Create thread to manage the client socket */
2792 ret = pthread_create(&health_thread, NULL,
2793 thread_manage_health, (void *) NULL);
2794 if (ret != 0) {
2795 PERROR("pthread_create health");
2796 goto health_error;
2797 }
2798
2799 /* Setup the dispatcher thread */
2800 ret = pthread_create(&dispatcher_thread, NULL,
2801 relay_thread_dispatcher, (void *) NULL);
2802 if (ret != 0) {
2803 PERROR("pthread_create dispatcher");
2804 goto exit_dispatcher;
2805 }
2806
2807 /* Setup the worker thread */
2808 ret = pthread_create(&worker_thread, NULL,
2809 relay_thread_worker, (void *) relay_ctx);
2810 if (ret != 0) {
2811 PERROR("pthread_create worker");
2812 goto exit_worker;
2813 }
2814
2815 /* Setup the listener thread */
2816 ret = pthread_create(&listener_thread, NULL,
2817 relay_thread_listener, (void *) NULL);
2818 if (ret != 0) {
2819 PERROR("pthread_create listener");
2820 goto exit_listener;
2821 }
2822
2823 ret = live_start_threads(live_uri, relay_ctx, thread_quit_pipe);
2824 if (ret != 0) {
2825 ERR("Starting live viewer threads");
2826 goto exit_live;
2827 }
2828
2829 exit_live:
2830 ret = pthread_join(listener_thread, &status);
2831 if (ret != 0) {
2832 PERROR("pthread_join");
2833 goto error; /* join error, exit without cleanup */
2834 }
2835
2836 exit_listener:
2837 ret = pthread_join(worker_thread, &status);
2838 if (ret != 0) {
2839 PERROR("pthread_join");
2840 goto error; /* join error, exit without cleanup */
2841 }
2842
2843 exit_worker:
2844 ret = pthread_join(dispatcher_thread, &status);
2845 if (ret != 0) {
2846 PERROR("pthread_join");
2847 goto error; /* join error, exit without cleanup */
2848 }
2849
2850 exit_dispatcher:
2851 ret = pthread_join(health_thread, &status);
2852 if (ret != 0) {
2853 PERROR("pthread_join health thread");
2854 goto error; /* join error, exit without cleanup */
2855 }
2856
2857 /*
2858 * Stop live threads only after joining other threads.
2859 */
2860 live_stop_threads();
2861
2862 health_error:
2863 utils_close_pipe(health_quit_pipe);
2864
2865 error_health_pipe:
2866 health_app_destroy(health_relayd);
2867
2868 exit_health_app_create:
2869 lttng_ht_destroy(viewer_streams_ht);
2870
2871 exit_relay_ctx_viewer_streams:
2872 lttng_ht_destroy(relay_streams_ht);
2873
2874 exit_relay_ctx_streams:
2875 lttng_ht_destroy(relay_ctx->sessions_ht);
2876
2877 exit_relay_ctx_sessions:
2878 free(relay_ctx);
2879
2880 exit:
2881 cleanup();
2882 if (!ret) {
2883 exit(EXIT_SUCCESS);
2884 }
2885
2886 error:
2887 exit(EXIT_FAILURE);
2888 }
This page took 0.088197 seconds and 5 git commands to generate.