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