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