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