7728696625016b7083bc41f43bf4aee62e4bfa1b
[deliverable/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 _LGPL_SOURCE
22 #include <getopt.h>
23 #include <grp.h>
24 #include <limits.h>
25 #include <pthread.h>
26 #include <signal.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <sys/mman.h>
31 #include <sys/mount.h>
32 #include <sys/resource.h>
33 #include <sys/socket.h>
34 #include <sys/stat.h>
35 #include <sys/types.h>
36 #include <sys/wait.h>
37 #include <sys/resource.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 <ctype.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/align.h>
60 #include <common/config/session-config.h>
61 #include <common/dynamic-buffer.h>
62 #include <common/buffer-view.h>
63 #include <common/fd-tracker/utils.h>
64 #include <urcu/rculist.h>
65
66 #include "cmd.h"
67 #include "ctf-trace.h"
68 #include "index.h"
69 #include "utils.h"
70 #include "lttng-relayd.h"
71 #include "live.h"
72 #include "health-relayd.h"
73 #include "testpoint.h"
74 #include "viewer-stream.h"
75 #include "session.h"
76 #include "stream.h"
77 #include "connection.h"
78 #include "tracefile-array.h"
79 #include "tcp_keep_alive.h"
80
81 static const char *help_msg =
82 #ifdef LTTNG_EMBED_HELP
83 #include <lttng-relayd.8.h>
84 #else
85 NULL
86 #endif
87 ;
88
89 enum relay_connection_status {
90 RELAY_CONNECTION_STATUS_OK,
91 /* An error occured while processing an event on the connection. */
92 RELAY_CONNECTION_STATUS_ERROR,
93 /* Connection closed/shutdown cleanly. */
94 RELAY_CONNECTION_STATUS_CLOSED,
95 };
96
97 /* command line options */
98 char *opt_output_path;
99 static int opt_daemon, opt_background;
100
101 /*
102 * We need to wait for listener and live listener threads, as well as
103 * health check thread, before being ready to signal readiness.
104 */
105 #define NR_LTTNG_RELAY_READY 3
106 static int lttng_relay_ready = NR_LTTNG_RELAY_READY;
107
108 /* Size of receive buffer. */
109 #define RECV_DATA_BUFFER_SIZE 65536
110 #define FILE_COPY_BUFFER_SIZE 65536
111
112 static int recv_child_signal; /* Set to 1 when a SIGUSR1 signal is received. */
113 static pid_t child_ppid; /* Internal parent PID use with daemonize. */
114
115 static struct lttng_uri *control_uri;
116 static struct lttng_uri *data_uri;
117 static struct lttng_uri *live_uri;
118
119 const char *progname;
120
121 const char *tracing_group_name = DEFAULT_TRACING_GROUP;
122 static int tracing_group_name_override;
123
124 const char * const config_section_name = "relayd";
125
126 /*
127 * Quit pipe for all threads. This permits a single cancellation point
128 * for all threads when receiving an event on the pipe.
129 */
130 int thread_quit_pipe[2] = { -1, -1 };
131
132 /*
133 * This pipe is used to inform the worker thread that a command is queued and
134 * ready to be processed.
135 */
136 static int relay_conn_pipe[2] = { -1, -1 };
137
138 /* Shared between threads */
139 static int dispatch_thread_exit;
140
141 static pthread_t listener_thread;
142 static pthread_t dispatcher_thread;
143 static pthread_t worker_thread;
144 static pthread_t health_thread;
145
146 /*
147 * last_relay_stream_id_lock protects last_relay_stream_id increment
148 * atomicity on 32-bit architectures.
149 */
150 static pthread_mutex_t last_relay_stream_id_lock = PTHREAD_MUTEX_INITIALIZER;
151 static uint64_t last_relay_stream_id;
152
153 /*
154 * Relay command queue.
155 *
156 * The relay_thread_listener and relay_thread_dispatcher communicate with this
157 * queue.
158 */
159 static struct relay_conn_queue relay_conn_queue;
160
161 /* Cap of file desriptors to be in simultaneous use by the relay daemon. */
162 static unsigned int lttng_opt_fd_pool_size = -1;
163
164 /* Global relay stream hash table. */
165 struct lttng_ht *relay_streams_ht;
166
167 /* Global relay viewer stream hash table. */
168 struct lttng_ht *viewer_streams_ht;
169
170 /* Global relay sessions hash table. */
171 struct lttng_ht *sessions_ht;
172
173 /* Relayd health monitoring */
174 struct health_app *health_relayd;
175
176 /* Global fd tracker. */
177 struct fd_tracker *the_fd_tracker;
178
179 static struct option long_options[] = {
180 { "control-port", 1, 0, 'C', },
181 { "data-port", 1, 0, 'D', },
182 { "live-port", 1, 0, 'L', },
183 { "daemonize", 0, 0, 'd', },
184 { "background", 0, 0, 'b', },
185 { "group", 1, 0, 'g', },
186 { "fd-pool-size", 1, 0, '\0', },
187 { "help", 0, 0, 'h', },
188 { "output", 1, 0, 'o', },
189 { "verbose", 0, 0, 'v', },
190 { "config", 1, 0, 'f' },
191 { "version", 0, 0, 'V' },
192 { NULL, 0, 0, 0, },
193 };
194
195 static const char *config_ignore_options[] = { "help", "config", "version" };
196
197 /*
198 * Take an option from the getopt output and set it in the right variable to be
199 * used later.
200 *
201 * Return 0 on success else a negative value.
202 */
203 static int set_option(int opt, const char *arg, const char *optname)
204 {
205 int ret;
206
207 switch (opt) {
208 case 0:
209 if (!strcmp(optname, "fd-pool-size")) {
210 unsigned long v;
211
212 errno = 0;
213 v = strtoul(arg, NULL, 0);
214 if (errno != 0 || !isdigit(arg[0])) {
215 ERR("Wrong value in --fd-pool-size parameter: %s", arg);
216 ret = -1;
217 goto end;
218 }
219 if (v >= UINT_MAX) {
220 ERR("File descriptor cap overflow in --fd-pool-size parameter: %s", arg);
221 ret = -1;
222 goto end;
223 }
224 lttng_opt_fd_pool_size = (unsigned int) v;
225 } else {
226 fprintf(stderr, "unknown option %s", optname);
227 if (arg) {
228 fprintf(stderr, " with arg %s\n", arg);
229 }
230 }
231 break;
232 case 'C':
233 if (lttng_is_setuid_setgid()) {
234 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
235 "-C, --control-port");
236 } else {
237 ret = uri_parse(arg, &control_uri);
238 if (ret < 0) {
239 ERR("Invalid control URI specified");
240 goto end;
241 }
242 if (control_uri->port == 0) {
243 control_uri->port = DEFAULT_NETWORK_CONTROL_PORT;
244 }
245 }
246 break;
247 case 'D':
248 if (lttng_is_setuid_setgid()) {
249 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
250 "-D, -data-port");
251 } else {
252 ret = uri_parse(arg, &data_uri);
253 if (ret < 0) {
254 ERR("Invalid data URI specified");
255 goto end;
256 }
257 if (data_uri->port == 0) {
258 data_uri->port = DEFAULT_NETWORK_DATA_PORT;
259 }
260 }
261 break;
262 case 'L':
263 if (lttng_is_setuid_setgid()) {
264 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
265 "-L, -live-port");
266 } else {
267 ret = uri_parse(arg, &live_uri);
268 if (ret < 0) {
269 ERR("Invalid live URI specified");
270 goto end;
271 }
272 if (live_uri->port == 0) {
273 live_uri->port = DEFAULT_NETWORK_VIEWER_PORT;
274 }
275 }
276 break;
277 case 'd':
278 opt_daemon = 1;
279 break;
280 case 'b':
281 opt_background = 1;
282 break;
283 case 'g':
284 if (lttng_is_setuid_setgid()) {
285 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
286 "-g, --group");
287 } else {
288 tracing_group_name = strdup(arg);
289 if (tracing_group_name == NULL) {
290 ret = -errno;
291 PERROR("strdup");
292 goto end;
293 }
294 tracing_group_name_override = 1;
295 }
296 break;
297 case 'h':
298 ret = utils_show_help(8, "lttng-relayd", help_msg);
299 if (ret) {
300 ERR("Cannot show --help for `lttng-relayd`");
301 perror("exec");
302 }
303 exit(EXIT_FAILURE);
304 case 'V':
305 fprintf(stdout, "%s\n", VERSION);
306 exit(EXIT_SUCCESS);
307 case 'o':
308 if (lttng_is_setuid_setgid()) {
309 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
310 "-o, --output");
311 } else {
312 ret = asprintf(&opt_output_path, "%s", arg);
313 if (ret < 0) {
314 ret = -errno;
315 PERROR("asprintf opt_output_path");
316 goto end;
317 }
318 }
319 break;
320 case 'v':
321 /* Verbose level can increase using multiple -v */
322 if (arg) {
323 lttng_opt_verbose = config_parse_value(arg);
324 } else {
325 /* Only 3 level of verbosity (-vvv). */
326 if (lttng_opt_verbose < 3) {
327 lttng_opt_verbose += 1;
328 }
329 }
330 break;
331 default:
332 /* Unknown option or other error.
333 * Error is printed by getopt, just return */
334 ret = -1;
335 goto end;
336 }
337
338 /* All good. */
339 ret = 0;
340
341 end:
342 return ret;
343 }
344
345 /*
346 * config_entry_handler_cb used to handle options read from a config file.
347 * See config_entry_handler_cb comment in common/config/session-config.h for the
348 * return value conventions.
349 */
350 static int config_entry_handler(const struct config_entry *entry, void *unused)
351 {
352 int ret = 0, i;
353
354 if (!entry || !entry->name || !entry->value) {
355 ret = -EINVAL;
356 goto end;
357 }
358
359 /* Check if the option is to be ignored */
360 for (i = 0; i < sizeof(config_ignore_options) / sizeof(char *); i++) {
361 if (!strcmp(entry->name, config_ignore_options[i])) {
362 goto end;
363 }
364 }
365
366 for (i = 0; i < (sizeof(long_options) / sizeof(struct option)) - 1; i++) {
367 /* Ignore if entry name is not fully matched. */
368 if (strcmp(entry->name, long_options[i].name)) {
369 continue;
370 }
371
372 /*
373 * If the option takes no argument on the command line,
374 * we have to check if the value is "true". We support
375 * non-zero numeric values, true, on and yes.
376 */
377 if (!long_options[i].has_arg) {
378 ret = config_parse_value(entry->value);
379 if (ret <= 0) {
380 if (ret) {
381 WARN("Invalid configuration value \"%s\" for option %s",
382 entry->value, entry->name);
383 }
384 /* False, skip boolean config option. */
385 goto end;
386 }
387 }
388
389 ret = set_option(long_options[i].val, entry->value, entry->name);
390 goto end;
391 }
392
393 WARN("Unrecognized option \"%s\" in daemon configuration file.",
394 entry->name);
395
396 end:
397 return ret;
398 }
399
400 static int set_fd_pool_size(void)
401 {
402 int ret = 0;
403 struct rlimit rlimit;
404
405 ret = getrlimit(RLIMIT_NOFILE, &rlimit);
406 if (ret) {
407 PERROR("Failed to get file descriptor limit");
408 ret = -1;
409 goto end;
410 }
411
412 DBG("File descriptor count limits are %lu (soft) and %lu (hard)",
413 rlimit.rlim_cur, rlimit.rlim_max);
414 if (lttng_opt_fd_pool_size == -1) {
415 /* Use default value (soft limit - reserve). */
416 if (rlimit.rlim_cur < DEFAULT_RELAYD_MIN_FD_POOL_SIZE) {
417 ERR("The process' file number limit is too low (%lu). The process' file number limit must be set to at least %i.",
418 rlimit.rlim_cur, DEFAULT_RELAYD_MIN_FD_POOL_SIZE);
419 ret = -1;
420 goto end;
421 }
422 lttng_opt_fd_pool_size = rlimit.rlim_cur -
423 DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE;
424 goto end;
425 }
426
427 if (lttng_opt_fd_pool_size < DEFAULT_RELAYD_MIN_FD_POOL_SIZE) {
428 ERR("File descriptor pool size must be set to at least %d",
429 DEFAULT_RELAYD_MIN_FD_POOL_SIZE);
430 ret = -1;
431 goto end;
432 }
433
434 if (lttng_opt_fd_pool_size > rlimit.rlim_cur) {
435 ERR("File descriptor pool size argument (%u) exceeds the process' soft limit (%lu).",
436 lttng_opt_fd_pool_size, rlimit.rlim_cur);
437 ret = -1;
438 goto end;
439 }
440
441
442 DBG("File descriptor pool size argument (%u) adjusted to %u to accomodate transient fd uses",
443 lttng_opt_fd_pool_size,
444 lttng_opt_fd_pool_size - DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE);
445 lttng_opt_fd_pool_size -= DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE;
446 end:
447 return ret;
448 }
449
450 static int set_options(int argc, char **argv)
451 {
452 int c, ret = 0, option_index = 0, retval = 0;
453 int orig_optopt = optopt, orig_optind = optind;
454 char *default_address, *optstring;
455 const char *config_path = NULL;
456
457 optstring = utils_generate_optstring(long_options,
458 sizeof(long_options) / sizeof(struct option));
459 if (!optstring) {
460 retval = -ENOMEM;
461 goto exit;
462 }
463
464 /* Check for the --config option */
465
466 while ((c = getopt_long(argc, argv, optstring, long_options,
467 &option_index)) != -1) {
468 if (c == '?') {
469 retval = -EINVAL;
470 goto exit;
471 } else if (c != 'f') {
472 continue;
473 }
474
475 if (lttng_is_setuid_setgid()) {
476 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
477 "-f, --config");
478 } else {
479 config_path = utils_expand_path(optarg);
480 if (!config_path) {
481 ERR("Failed to resolve path: %s", optarg);
482 }
483 }
484 }
485
486 ret = config_get_section_entries(config_path, config_section_name,
487 config_entry_handler, NULL);
488 if (ret) {
489 if (ret > 0) {
490 ERR("Invalid configuration option at line %i", ret);
491 }
492 retval = -1;
493 goto exit;
494 }
495
496 /* Reset getopt's global state */
497 optopt = orig_optopt;
498 optind = orig_optind;
499 while (1) {
500 c = getopt_long(argc, argv, optstring, long_options, &option_index);
501 if (c == -1) {
502 break;
503 }
504
505 ret = set_option(c, optarg, long_options[option_index].name);
506 if (ret < 0) {
507 retval = -1;
508 goto exit;
509 }
510 }
511
512 /* assign default values */
513 if (control_uri == NULL) {
514 ret = asprintf(&default_address,
515 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS ":%d",
516 DEFAULT_NETWORK_CONTROL_PORT);
517 if (ret < 0) {
518 PERROR("asprintf default data address");
519 retval = -1;
520 goto exit;
521 }
522
523 ret = uri_parse(default_address, &control_uri);
524 free(default_address);
525 if (ret < 0) {
526 ERR("Invalid control URI specified");
527 retval = -1;
528 goto exit;
529 }
530 }
531 if (data_uri == NULL) {
532 ret = asprintf(&default_address,
533 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS ":%d",
534 DEFAULT_NETWORK_DATA_PORT);
535 if (ret < 0) {
536 PERROR("asprintf default data address");
537 retval = -1;
538 goto exit;
539 }
540
541 ret = uri_parse(default_address, &data_uri);
542 free(default_address);
543 if (ret < 0) {
544 ERR("Invalid data URI specified");
545 retval = -1;
546 goto exit;
547 }
548 }
549 if (live_uri == NULL) {
550 ret = asprintf(&default_address,
551 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS ":%d",
552 DEFAULT_NETWORK_VIEWER_PORT);
553 if (ret < 0) {
554 PERROR("asprintf default viewer control address");
555 retval = -1;
556 goto exit;
557 }
558
559 ret = uri_parse(default_address, &live_uri);
560 free(default_address);
561 if (ret < 0) {
562 ERR("Invalid viewer control URI specified");
563 retval = -1;
564 goto exit;
565 }
566 }
567 ret = set_fd_pool_size();
568 if (ret) {
569 retval = -1;
570 goto exit;
571 }
572
573 exit:
574 free(optstring);
575 return retval;
576 }
577
578 static void print_global_objects(void)
579 {
580 print_viewer_streams();
581 print_relay_streams();
582 print_sessions();
583 }
584
585 /*
586 * Cleanup the daemon
587 */
588 static void relayd_cleanup(void)
589 {
590 print_global_objects();
591
592 DBG("Cleaning up");
593
594 if (viewer_streams_ht)
595 lttng_ht_destroy(viewer_streams_ht);
596 if (relay_streams_ht)
597 lttng_ht_destroy(relay_streams_ht);
598 if (sessions_ht)
599 lttng_ht_destroy(sessions_ht);
600
601 /* free the dynamically allocated opt_output_path */
602 free(opt_output_path);
603
604 /* Close thread quit pipes */
605 (void) fd_tracker_util_pipe_close(the_fd_tracker, thread_quit_pipe);
606
607 uri_free(control_uri);
608 uri_free(data_uri);
609 /* Live URI is freed in the live thread. */
610
611 if (tracing_group_name_override) {
612 free((void *) tracing_group_name);
613 }
614 }
615
616 /*
617 * Write to writable pipe used to notify a thread.
618 */
619 static int notify_thread_pipe(int wpipe)
620 {
621 ssize_t ret;
622
623 ret = lttng_write(wpipe, "!", 1);
624 if (ret < 1) {
625 PERROR("write poll pipe");
626 goto end;
627 }
628 ret = 0;
629 end:
630 return ret;
631 }
632
633 static int notify_health_quit_pipe(int *pipe)
634 {
635 ssize_t ret;
636
637 ret = lttng_write(pipe[1], "4", 1);
638 if (ret < 1) {
639 PERROR("write relay health quit");
640 goto end;
641 }
642 ret = 0;
643 end:
644 return ret;
645 }
646
647 /*
648 * Stop all relayd and relayd-live threads.
649 */
650 int lttng_relay_stop_threads(void)
651 {
652 int retval = 0;
653
654 /* Stopping all threads */
655 DBG("Terminating all threads");
656 if (notify_thread_pipe(thread_quit_pipe[1])) {
657 ERR("write error on thread quit pipe");
658 retval = -1;
659 }
660
661 if (notify_health_quit_pipe(health_quit_pipe)) {
662 ERR("write error on health quit pipe");
663 }
664
665 /* Dispatch thread */
666 CMM_STORE_SHARED(dispatch_thread_exit, 1);
667 futex_nto1_wake(&relay_conn_queue.futex);
668
669 if (relayd_live_stop()) {
670 ERR("Error stopping live threads");
671 retval = -1;
672 }
673 return retval;
674 }
675
676 /*
677 * Signal handler for the daemon
678 *
679 * Simply stop all worker threads, leaving main() return gracefully after
680 * joining all threads and calling cleanup().
681 */
682 static void sighandler(int sig)
683 {
684 switch (sig) {
685 case SIGINT:
686 DBG("SIGINT caught");
687 if (lttng_relay_stop_threads()) {
688 ERR("Error stopping threads");
689 }
690 break;
691 case SIGTERM:
692 DBG("SIGTERM caught");
693 if (lttng_relay_stop_threads()) {
694 ERR("Error stopping threads");
695 }
696 break;
697 case SIGUSR1:
698 CMM_STORE_SHARED(recv_child_signal, 1);
699 break;
700 default:
701 break;
702 }
703 }
704
705 /*
706 * Setup signal handler for :
707 * SIGINT, SIGTERM, SIGPIPE
708 */
709 static int set_signal_handler(void)
710 {
711 int ret = 0;
712 struct sigaction sa;
713 sigset_t sigset;
714
715 if ((ret = sigemptyset(&sigset)) < 0) {
716 PERROR("sigemptyset");
717 return ret;
718 }
719
720 sa.sa_mask = sigset;
721 sa.sa_flags = 0;
722
723 sa.sa_handler = sighandler;
724 if ((ret = sigaction(SIGTERM, &sa, NULL)) < 0) {
725 PERROR("sigaction");
726 return ret;
727 }
728
729 if ((ret = sigaction(SIGINT, &sa, NULL)) < 0) {
730 PERROR("sigaction");
731 return ret;
732 }
733
734 if ((ret = sigaction(SIGUSR1, &sa, NULL)) < 0) {
735 PERROR("sigaction");
736 return ret;
737 }
738
739 sa.sa_handler = SIG_IGN;
740 if ((ret = sigaction(SIGPIPE, &sa, NULL)) < 0) {
741 PERROR("sigaction");
742 return ret;
743 }
744
745 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
746
747 return ret;
748 }
749
750 void lttng_relay_notify_ready(void)
751 {
752 /* Notify the parent of the fork() process that we are ready. */
753 if (opt_daemon || opt_background) {
754 if (uatomic_sub_return(&lttng_relay_ready, 1) == 0) {
755 kill(child_ppid, SIGUSR1);
756 }
757 }
758 }
759
760 /*
761 * Init thread quit pipe.
762 *
763 * Return -1 on error or 0 if all pipes are created.
764 */
765 static int init_thread_quit_pipe(void)
766 {
767 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker,
768 "Quit pipe", thread_quit_pipe);
769 }
770
771 /*
772 * Init health quit pipe.
773 *
774 * Return -1 on error or 0 if all pipes are created.
775 */
776 static int init_health_quit_pipe(void)
777 {
778 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker,
779 "Health quit pipe", health_quit_pipe);
780 }
781
782 /*
783 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
784 */
785 static int create_named_thread_poll_set(struct lttng_poll_event *events,
786 int size, const char *name)
787 {
788 int ret;
789
790 if (events == NULL || size == 0) {
791 ret = -1;
792 goto error;
793 }
794
795 ret = fd_tracker_util_poll_create(the_fd_tracker,
796 name, events, 1, LTTNG_CLOEXEC);
797
798 /* Add quit pipe */
799 ret = lttng_poll_add(events, thread_quit_pipe[0], LPOLLIN | LPOLLERR);
800 if (ret < 0) {
801 goto error;
802 }
803
804 return 0;
805
806 error:
807 return ret;
808 }
809
810 /*
811 * Check if the thread quit pipe was triggered.
812 *
813 * Return 1 if it was triggered else 0;
814 */
815 static int check_thread_quit_pipe(int fd, uint32_t events)
816 {
817 if (fd == thread_quit_pipe[0] && (events & LPOLLIN)) {
818 return 1;
819 }
820
821 return 0;
822 }
823
824 static int create_sock(void *data, int *out_fd)
825 {
826 int ret;
827 struct lttcomm_sock *sock = data;
828
829 ret = lttcomm_create_sock(sock);
830 if (ret < 0) {
831 goto end;
832 }
833
834 *out_fd = sock->fd;
835 end:
836 return ret;
837 }
838
839 static int close_sock(void *data, int *in_fd)
840 {
841 struct lttcomm_sock *sock = data;
842
843 return sock->ops->close(sock);
844 }
845
846 static int accept_sock(void *data, int *out_fd)
847 {
848 int ret = 0;
849 /* Socks is an array of in_sock, out_sock. */
850 struct lttcomm_sock **socks = data;
851 struct lttcomm_sock *in_sock = socks[0];
852
853 socks[1] = in_sock->ops->accept(in_sock);
854 if (!socks[1]) {
855 ret = -1;
856 goto end;
857 }
858 *out_fd = socks[1]->fd;
859 end:
860 return ret;
861 }
862
863 /*
864 * Create and init socket from uri.
865 */
866 static struct lttcomm_sock *relay_socket_create(struct lttng_uri *uri,
867 const char *name)
868 {
869 int ret, sock_fd;
870 struct lttcomm_sock *sock = NULL;
871 char uri_str[PATH_MAX];
872 char *formated_name = NULL;
873
874 sock = lttcomm_alloc_sock_from_uri(uri);
875 if (sock == NULL) {
876 ERR("Allocating socket");
877 goto error;
878 }
879
880 /*
881 * Don't fail to create the socket if the name can't be built as it is
882 * only used for debugging purposes.
883 */
884 ret = uri_to_str_url(uri, uri_str, sizeof(uri_str));
885 uri_str[sizeof(uri_str) - 1] = '\0';
886 if (ret >= 0) {
887 ret = asprintf(&formated_name, "%s socket @ %s", name,
888 uri_str);
889 if (ret < 0) {
890 formated_name = NULL;
891 }
892 }
893
894 ret = fd_tracker_open_unsuspendable_fd(the_fd_tracker, &sock_fd,
895 (const char **) (formated_name ? &formated_name : NULL),
896 1, create_sock, sock);
897 free(formated_name);
898 DBG("Listening on %s socket %d", name, sock->fd);
899
900 ret = sock->ops->bind(sock);
901 if (ret < 0) {
902 PERROR("Failed to bind socket");
903 goto error;
904 }
905
906 ret = sock->ops->listen(sock, -1);
907 if (ret < 0) {
908 goto error;
909
910 }
911
912 return sock;
913
914 error:
915 if (sock) {
916 lttcomm_destroy_sock(sock);
917 }
918 return NULL;
919 }
920
921 static
922 struct lttcomm_sock *accept_relayd_sock(struct lttcomm_sock *listening_sock,
923 const char *name)
924 {
925 int out_fd, ret;
926 struct lttcomm_sock *socks[2] = { listening_sock, NULL };
927 struct lttcomm_sock *new_sock = NULL;
928
929 ret = fd_tracker_open_unsuspendable_fd(
930 the_fd_tracker, &out_fd,
931 (const char **) &name,
932 1, accept_sock, &socks);
933 if (ret) {
934 goto end;
935 }
936 new_sock = socks[1];
937 DBG("%s accepted, socket %d", name, new_sock->fd);
938 end:
939 return new_sock;
940 }
941
942 /*
943 * This thread manages the listening for new connections on the network
944 */
945 static void *relay_thread_listener(void *data)
946 {
947 int i, ret, pollfd, err = -1;
948 uint32_t revents, nb_fd;
949 struct lttng_poll_event events;
950 struct lttcomm_sock *control_sock, *data_sock;
951
952 DBG("[thread] Relay listener started");
953
954 health_register(health_relayd, HEALTH_RELAYD_TYPE_LISTENER);
955
956 health_code_update();
957
958 control_sock = relay_socket_create(control_uri, "Control listener");
959 if (!control_sock) {
960 goto error_sock_control;
961 }
962
963 data_sock = relay_socket_create(data_uri, "Data listener");
964 if (!data_sock) {
965 goto error_sock_relay;
966 }
967
968 /*
969 * Pass 3 as size here for the thread quit pipe, control and
970 * data socket.
971 */
972 ret = create_named_thread_poll_set(&events, 3, "Listener thread epoll");
973 if (ret < 0) {
974 goto error_create_poll;
975 }
976
977 /* Add the control socket */
978 ret = lttng_poll_add(&events, control_sock->fd, LPOLLIN | LPOLLRDHUP);
979 if (ret < 0) {
980 goto error_poll_add;
981 }
982
983 /* Add the data socket */
984 ret = lttng_poll_add(&events, data_sock->fd, LPOLLIN | LPOLLRDHUP);
985 if (ret < 0) {
986 goto error_poll_add;
987 }
988
989 lttng_relay_notify_ready();
990
991 if (testpoint(relayd_thread_listener)) {
992 goto error_testpoint;
993 }
994
995 while (1) {
996 health_code_update();
997
998 DBG("Listener accepting connections");
999
1000 restart:
1001 health_poll_entry();
1002 ret = lttng_poll_wait(&events, -1);
1003 health_poll_exit();
1004 if (ret < 0) {
1005 /*
1006 * Restart interrupted system call.
1007 */
1008 if (errno == EINTR) {
1009 goto restart;
1010 }
1011 goto error;
1012 }
1013
1014 nb_fd = ret;
1015
1016 DBG("Relay new connection received");
1017 for (i = 0; i < nb_fd; i++) {
1018 health_code_update();
1019
1020 /* Fetch once the poll data */
1021 revents = LTTNG_POLL_GETEV(&events, i);
1022 pollfd = LTTNG_POLL_GETFD(&events, i);
1023
1024 if (!revents) {
1025 /*
1026 * No activity for this FD (poll
1027 * implementation).
1028 */
1029 continue;
1030 }
1031
1032 /* Thread quit pipe has been closed. Killing thread. */
1033 ret = check_thread_quit_pipe(pollfd, revents);
1034 if (ret) {
1035 err = 0;
1036 goto exit;
1037 }
1038
1039 if (revents & LPOLLIN) {
1040 /*
1041 * A new connection is requested, therefore a
1042 * sessiond/consumerd connection is allocated in
1043 * this thread, enqueued to a global queue and
1044 * dequeued (and freed) in the worker thread.
1045 */
1046 int val = 1;
1047 struct relay_connection *new_conn;
1048 struct lttcomm_sock *newsock = NULL;
1049 enum connection_type type;
1050
1051 if (pollfd == data_sock->fd) {
1052 type = RELAY_DATA;
1053 newsock = accept_relayd_sock(data_sock,
1054 "Data socket to relayd");
1055 } else {
1056 assert(pollfd == control_sock->fd);
1057 type = RELAY_CONTROL;
1058 newsock = accept_relayd_sock(control_sock,
1059 "Control socket to relayd");
1060 }
1061 if (!newsock) {
1062 PERROR("accepting sock");
1063 goto error;
1064 }
1065
1066 ret = setsockopt(newsock->fd, SOL_SOCKET, SO_REUSEADDR, &val,
1067 sizeof(val));
1068 if (ret < 0) {
1069 PERROR("setsockopt inet");
1070 lttcomm_destroy_sock(newsock);
1071 goto error;
1072 }
1073
1074 ret = socket_apply_keep_alive_config(newsock->fd);
1075 if (ret < 0) {
1076 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
1077 newsock->fd);
1078 lttcomm_destroy_sock(newsock);
1079 goto error;
1080 }
1081
1082 new_conn = connection_create(newsock, type);
1083 if (!new_conn) {
1084 lttcomm_destroy_sock(newsock);
1085 goto error;
1086 }
1087
1088 /* Enqueue request for the dispatcher thread. */
1089 cds_wfcq_enqueue(&relay_conn_queue.head, &relay_conn_queue.tail,
1090 &new_conn->qnode);
1091
1092 /*
1093 * Wake the dispatch queue futex.
1094 * Implicit memory barrier with the
1095 * exchange in cds_wfcq_enqueue.
1096 */
1097 futex_nto1_wake(&relay_conn_queue.futex);
1098 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
1099 ERR("socket poll error");
1100 goto error;
1101 } else {
1102 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
1103 goto error;
1104 }
1105 }
1106 }
1107
1108 exit:
1109 error:
1110 error_poll_add:
1111 error_testpoint:
1112 (void) fd_tracker_util_poll_clean(the_fd_tracker, &events);
1113 error_create_poll:
1114 if (data_sock->fd >= 0) {
1115 ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker,
1116 &data_sock->fd, 1, close_sock,
1117 data_sock);
1118 if (ret) {
1119 PERROR("close");
1120 }
1121 }
1122 lttcomm_destroy_sock(data_sock);
1123 error_sock_relay:
1124 if (control_sock->fd >= 0) {
1125 ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker,
1126 &control_sock->fd, 1, close_sock,
1127 control_sock);
1128 if (ret) {
1129 PERROR("close");
1130 }
1131 }
1132 lttcomm_destroy_sock(control_sock);
1133 error_sock_control:
1134 if (err) {
1135 health_error();
1136 ERR("Health error occurred in %s", __func__);
1137 }
1138 health_unregister(health_relayd);
1139 DBG("Relay listener thread cleanup complete");
1140 lttng_relay_stop_threads();
1141 return NULL;
1142 }
1143
1144 /*
1145 * This thread manages the dispatching of the requests to worker threads
1146 */
1147 static void *relay_thread_dispatcher(void *data)
1148 {
1149 int err = -1;
1150 ssize_t ret;
1151 struct cds_wfcq_node *node;
1152 struct relay_connection *new_conn = NULL;
1153
1154 DBG("[thread] Relay dispatcher started");
1155
1156 health_register(health_relayd, HEALTH_RELAYD_TYPE_DISPATCHER);
1157
1158 if (testpoint(relayd_thread_dispatcher)) {
1159 goto error_testpoint;
1160 }
1161
1162 health_code_update();
1163
1164 for (;;) {
1165 health_code_update();
1166
1167 /* Atomically prepare the queue futex */
1168 futex_nto1_prepare(&relay_conn_queue.futex);
1169
1170 if (CMM_LOAD_SHARED(dispatch_thread_exit)) {
1171 break;
1172 }
1173
1174 do {
1175 health_code_update();
1176
1177 /* Dequeue commands */
1178 node = cds_wfcq_dequeue_blocking(&relay_conn_queue.head,
1179 &relay_conn_queue.tail);
1180 if (node == NULL) {
1181 DBG("Woken up but nothing in the relay command queue");
1182 /* Continue thread execution */
1183 break;
1184 }
1185 new_conn = caa_container_of(node, struct relay_connection, qnode);
1186
1187 DBG("Dispatching request waiting on sock %d", new_conn->sock->fd);
1188
1189 /*
1190 * Inform worker thread of the new request. This
1191 * call is blocking so we can be assured that
1192 * the data will be read at some point in time
1193 * or wait to the end of the world :)
1194 */
1195 ret = lttng_write(relay_conn_pipe[1], &new_conn, sizeof(new_conn));
1196 if (ret < 0) {
1197 PERROR("write connection pipe");
1198 connection_put(new_conn);
1199 goto error;
1200 }
1201 } while (node != NULL);
1202
1203 /* Futex wait on queue. Blocking call on futex() */
1204 health_poll_entry();
1205 futex_nto1_wait(&relay_conn_queue.futex);
1206 health_poll_exit();
1207 }
1208
1209 /* Normal exit, no error */
1210 err = 0;
1211
1212 error:
1213 error_testpoint:
1214 if (err) {
1215 health_error();
1216 ERR("Health error occurred in %s", __func__);
1217 }
1218 health_unregister(health_relayd);
1219 DBG("Dispatch thread dying");
1220 lttng_relay_stop_threads();
1221 return NULL;
1222 }
1223
1224 /*
1225 * Set index data from the control port to a given index object.
1226 */
1227 static int set_index_control_data(struct relay_index *index,
1228 struct lttcomm_relayd_index *data,
1229 struct relay_connection *conn)
1230 {
1231 struct ctf_packet_index index_data;
1232
1233 /*
1234 * The index on disk is encoded in big endian.
1235 */
1236 index_data.packet_size = htobe64(data->packet_size);
1237 index_data.content_size = htobe64(data->content_size);
1238 index_data.timestamp_begin = htobe64(data->timestamp_begin);
1239 index_data.timestamp_end = htobe64(data->timestamp_end);
1240 index_data.events_discarded = htobe64(data->events_discarded);
1241 index_data.stream_id = htobe64(data->stream_id);
1242
1243 if (conn->minor >= 8) {
1244 index->index_data.stream_instance_id = htobe64(data->stream_instance_id);
1245 index->index_data.packet_seq_num = htobe64(data->packet_seq_num);
1246 }
1247
1248 return relay_index_set_data(index, &index_data);
1249 }
1250
1251 /*
1252 * Handle the RELAYD_CREATE_SESSION command.
1253 *
1254 * On success, send back the session id or else return a negative value.
1255 */
1256 static int relay_create_session(const struct lttcomm_relayd_hdr *recv_hdr,
1257 struct relay_connection *conn,
1258 const struct lttng_buffer_view *payload)
1259 {
1260 int ret = 0;
1261 ssize_t send_ret;
1262 struct relay_session *session;
1263 struct lttcomm_relayd_status_session reply;
1264 char session_name[LTTNG_NAME_MAX];
1265 char hostname[LTTNG_HOST_NAME_MAX];
1266 uint32_t live_timer = 0;
1267 bool snapshot = false;
1268
1269 memset(session_name, 0, LTTNG_NAME_MAX);
1270 memset(hostname, 0, LTTNG_HOST_NAME_MAX);
1271
1272 memset(&reply, 0, sizeof(reply));
1273
1274 if (conn->minor < 4) {
1275 /* From 2.1 to 2.3 */
1276 ret = 0;
1277 } else if (conn->minor >= 4 && conn->minor < 11) {
1278 /* From 2.4 to 2.10 */
1279 ret = cmd_create_session_2_4(payload, session_name,
1280 hostname, &live_timer, &snapshot);
1281 } else {
1282 /* From 2.11 to ... */
1283 ret = cmd_create_session_2_11(payload, session_name,
1284 hostname, &live_timer, &snapshot);
1285 }
1286
1287 if (ret < 0) {
1288 goto send_reply;
1289 }
1290
1291 session = session_create(session_name, hostname, live_timer,
1292 snapshot, conn->major, conn->minor);
1293 if (!session) {
1294 ret = -1;
1295 goto send_reply;
1296 }
1297 assert(!conn->session);
1298 conn->session = session;
1299 DBG("Created session %" PRIu64, session->id);
1300
1301 reply.session_id = htobe64(session->id);
1302
1303 send_reply:
1304 if (ret < 0) {
1305 reply.ret_code = htobe32(LTTNG_ERR_FATAL);
1306 } else {
1307 reply.ret_code = htobe32(LTTNG_OK);
1308 }
1309
1310 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1311 if (send_ret < (ssize_t) sizeof(reply)) {
1312 ERR("Failed to send \"create session\" command reply (ret = %zd)",
1313 send_ret);
1314 ret = -1;
1315 }
1316
1317 return ret;
1318 }
1319
1320 /*
1321 * When we have received all the streams and the metadata for a channel,
1322 * we make them visible to the viewer threads.
1323 */
1324 static void publish_connection_local_streams(struct relay_connection *conn)
1325 {
1326 struct relay_stream *stream;
1327 struct relay_session *session = conn->session;
1328
1329 /*
1330 * We publish all streams belonging to a session atomically wrt
1331 * session lock.
1332 */
1333 pthread_mutex_lock(&session->lock);
1334 rcu_read_lock();
1335 cds_list_for_each_entry_rcu(stream, &session->recv_list,
1336 recv_node) {
1337 stream_publish(stream);
1338 }
1339 rcu_read_unlock();
1340
1341 /*
1342 * Inform the viewer that there are new streams in the session.
1343 */
1344 if (session->viewer_attached) {
1345 uatomic_set(&session->new_streams, 1);
1346 }
1347 pthread_mutex_unlock(&session->lock);
1348 }
1349
1350 /*
1351 * relay_add_stream: allocate a new stream for a session
1352 */
1353 static int relay_add_stream(const struct lttcomm_relayd_hdr *recv_hdr,
1354 struct relay_connection *conn,
1355 const struct lttng_buffer_view *payload)
1356 {
1357 int ret;
1358 ssize_t send_ret;
1359 struct relay_session *session = conn->session;
1360 struct relay_stream *stream = NULL;
1361 struct lttcomm_relayd_status_stream reply;
1362 struct ctf_trace *trace = NULL;
1363 uint64_t stream_handle = -1ULL;
1364 char *path_name = NULL, *channel_name = NULL;
1365 uint64_t tracefile_size = 0, tracefile_count = 0;
1366 struct relay_stream_chunk_id stream_chunk_id = { 0 };
1367
1368 if (!session || !conn->version_check_done) {
1369 ERR("Trying to add a stream before version check");
1370 ret = -1;
1371 goto end_no_session;
1372 }
1373
1374 if (session->minor == 1) {
1375 /* For 2.1 */
1376 ret = cmd_recv_stream_2_1(payload, &path_name,
1377 &channel_name);
1378 } else if (session->minor > 1 && session->minor < 11) {
1379 /* From 2.2 to 2.10 */
1380 ret = cmd_recv_stream_2_2(payload, &path_name,
1381 &channel_name, &tracefile_size, &tracefile_count);
1382 } else {
1383 /* From 2.11 to ... */
1384 ret = cmd_recv_stream_2_11(payload, &path_name,
1385 &channel_name, &tracefile_size, &tracefile_count,
1386 &stream_chunk_id.value);
1387 stream_chunk_id.is_set = true;
1388 }
1389
1390 if (ret < 0) {
1391 goto send_reply;
1392 }
1393
1394 trace = ctf_trace_get_by_path_or_create(session, path_name);
1395 if (!trace) {
1396 goto send_reply;
1397 }
1398 /* This stream here has one reference on the trace. */
1399
1400 pthread_mutex_lock(&last_relay_stream_id_lock);
1401 stream_handle = ++last_relay_stream_id;
1402 pthread_mutex_unlock(&last_relay_stream_id_lock);
1403
1404 /* We pass ownership of path_name and channel_name. */
1405 stream = stream_create(trace, stream_handle, path_name,
1406 channel_name, tracefile_size, tracefile_count,
1407 &stream_chunk_id);
1408 path_name = NULL;
1409 channel_name = NULL;
1410
1411 /*
1412 * Streams are the owners of their trace. Reference to trace is
1413 * kept within stream_create().
1414 */
1415 ctf_trace_put(trace);
1416
1417 send_reply:
1418 memset(&reply, 0, sizeof(reply));
1419 reply.handle = htobe64(stream_handle);
1420 if (!stream) {
1421 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1422 } else {
1423 reply.ret_code = htobe32(LTTNG_OK);
1424 }
1425
1426 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1427 sizeof(struct lttcomm_relayd_status_stream), 0);
1428 if (send_ret < (ssize_t) sizeof(reply)) {
1429 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1430 send_ret);
1431 ret = -1;
1432 }
1433
1434 end_no_session:
1435 free(path_name);
1436 free(channel_name);
1437 return ret;
1438 }
1439
1440 /*
1441 * relay_close_stream: close a specific stream
1442 */
1443 static int relay_close_stream(const struct lttcomm_relayd_hdr *recv_hdr,
1444 struct relay_connection *conn,
1445 const struct lttng_buffer_view *payload)
1446 {
1447 int ret;
1448 ssize_t send_ret;
1449 struct relay_session *session = conn->session;
1450 struct lttcomm_relayd_close_stream stream_info;
1451 struct lttcomm_relayd_generic_reply reply;
1452 struct relay_stream *stream;
1453
1454 DBG("Close stream received");
1455
1456 if (!session || !conn->version_check_done) {
1457 ERR("Trying to close a stream before version check");
1458 ret = -1;
1459 goto end_no_session;
1460 }
1461
1462 if (payload->size < sizeof(stream_info)) {
1463 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1464 sizeof(stream_info), payload->size);
1465 ret = -1;
1466 goto end_no_session;
1467 }
1468 memcpy(&stream_info, payload->data, sizeof(stream_info));
1469 stream_info.stream_id = be64toh(stream_info.stream_id);
1470 stream_info.last_net_seq_num = be64toh(stream_info.last_net_seq_num);
1471
1472 stream = stream_get_by_id(stream_info.stream_id);
1473 if (!stream) {
1474 ret = -1;
1475 goto end;
1476 }
1477
1478 /*
1479 * Set last_net_seq_num before the close flag. Required by data
1480 * pending check.
1481 */
1482 pthread_mutex_lock(&stream->lock);
1483 stream->last_net_seq_num = stream_info.last_net_seq_num;
1484 pthread_mutex_unlock(&stream->lock);
1485
1486 /*
1487 * This is one of the conditions which may trigger a stream close
1488 * with the others being:
1489 * 1) A close command is received for a stream
1490 * 2) The control connection owning the stream is closed
1491 * 3) We have received all of the stream's data _after_ a close
1492 * request.
1493 */
1494 try_stream_close(stream);
1495 if (stream->is_metadata) {
1496 struct relay_viewer_stream *vstream;
1497
1498 vstream = viewer_stream_get_by_id(stream->stream_handle);
1499 if (vstream) {
1500 if (vstream->metadata_sent == stream->metadata_received) {
1501 /*
1502 * Since all the metadata has been sent to the
1503 * viewer and that we have a request to close
1504 * its stream, we can safely teardown the
1505 * corresponding metadata viewer stream.
1506 */
1507 viewer_stream_put(vstream);
1508 }
1509 /* Put local reference. */
1510 viewer_stream_put(vstream);
1511 }
1512 }
1513 stream_put(stream);
1514 ret = 0;
1515
1516 end:
1517 memset(&reply, 0, sizeof(reply));
1518 if (ret < 0) {
1519 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1520 } else {
1521 reply.ret_code = htobe32(LTTNG_OK);
1522 }
1523 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1524 sizeof(struct lttcomm_relayd_generic_reply), 0);
1525 if (send_ret < (ssize_t) sizeof(reply)) {
1526 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1527 send_ret);
1528 ret = -1;
1529 }
1530
1531 end_no_session:
1532 return ret;
1533 }
1534
1535 /*
1536 * relay_reset_metadata: reset a metadata stream
1537 */
1538 static
1539 int relay_reset_metadata(const struct lttcomm_relayd_hdr *recv_hdr,
1540 struct relay_connection *conn,
1541 const struct lttng_buffer_view *payload)
1542 {
1543 int ret;
1544 ssize_t send_ret;
1545 struct relay_session *session = conn->session;
1546 struct lttcomm_relayd_reset_metadata stream_info;
1547 struct lttcomm_relayd_generic_reply reply;
1548 struct relay_stream *stream;
1549
1550 DBG("Reset metadata received");
1551
1552 if (!session || !conn->version_check_done) {
1553 ERR("Trying to reset a metadata stream before version check");
1554 ret = -1;
1555 goto end_no_session;
1556 }
1557
1558 if (payload->size < sizeof(stream_info)) {
1559 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1560 sizeof(stream_info), payload->size);
1561 ret = -1;
1562 goto end_no_session;
1563 }
1564 memcpy(&stream_info, payload->data, sizeof(stream_info));
1565 stream_info.stream_id = be64toh(stream_info.stream_id);
1566 stream_info.version = be64toh(stream_info.version);
1567
1568 DBG("Update metadata to version %" PRIu64, stream_info.version);
1569
1570 /* Unsupported for live sessions for now. */
1571 if (session->live_timer != 0) {
1572 ret = -1;
1573 goto end;
1574 }
1575
1576 stream = stream_get_by_id(stream_info.stream_id);
1577 if (!stream) {
1578 ret = -1;
1579 goto end;
1580 }
1581 pthread_mutex_lock(&stream->lock);
1582 if (!stream->is_metadata) {
1583 ret = -1;
1584 goto end_unlock;
1585 }
1586
1587 ret = stream_fd_rotate(stream->stream_fd,
1588 stream->path_name, stream->channel_name, 0, 0, NULL);
1589 if (ret < 0) {
1590 ERR("Failed to rotate metadata file %s of channel %s",
1591 stream->path_name, stream->channel_name);
1592 goto end_unlock;
1593 }
1594
1595 end_unlock:
1596 pthread_mutex_unlock(&stream->lock);
1597 stream_put(stream);
1598
1599 end:
1600 memset(&reply, 0, sizeof(reply));
1601 if (ret < 0) {
1602 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1603 } else {
1604 reply.ret_code = htobe32(LTTNG_OK);
1605 }
1606 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1607 sizeof(struct lttcomm_relayd_generic_reply), 0);
1608 if (send_ret < (ssize_t) sizeof(reply)) {
1609 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1610 send_ret);
1611 ret = -1;
1612 }
1613
1614 end_no_session:
1615 return ret;
1616 }
1617
1618 /*
1619 * relay_unknown_command: send -1 if received unknown command
1620 */
1621 static void relay_unknown_command(struct relay_connection *conn)
1622 {
1623 struct lttcomm_relayd_generic_reply reply;
1624 ssize_t send_ret;
1625
1626 memset(&reply, 0, sizeof(reply));
1627 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1628 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1629 if (send_ret < sizeof(reply)) {
1630 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret);
1631 }
1632 }
1633
1634 /*
1635 * relay_start: send an acknowledgment to the client to tell if we are
1636 * ready to receive data. We are ready if a session is established.
1637 */
1638 static int relay_start(const struct lttcomm_relayd_hdr *recv_hdr,
1639 struct relay_connection *conn,
1640 const struct lttng_buffer_view *payload)
1641 {
1642 int ret = 0;
1643 ssize_t send_ret;
1644 struct lttcomm_relayd_generic_reply reply;
1645 struct relay_session *session = conn->session;
1646
1647 if (!session) {
1648 DBG("Trying to start the streaming without a session established");
1649 ret = htobe32(LTTNG_ERR_UNK);
1650 }
1651
1652 memset(&reply, 0, sizeof(reply));
1653 reply.ret_code = htobe32(LTTNG_OK);
1654 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1655 sizeof(reply), 0);
1656 if (send_ret < (ssize_t) sizeof(reply)) {
1657 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1658 send_ret);
1659 ret = -1;
1660 }
1661
1662 return ret;
1663 }
1664
1665 /*
1666 * Append padding to the file pointed by the file descriptor fd.
1667 */
1668 static int write_padding_to_file(int fd, uint32_t size)
1669 {
1670 ssize_t ret = 0;
1671 char *zeros;
1672
1673 if (size == 0) {
1674 goto end;
1675 }
1676
1677 zeros = zmalloc(size);
1678 if (zeros == NULL) {
1679 PERROR("zmalloc zeros for padding");
1680 ret = -1;
1681 goto end;
1682 }
1683
1684 ret = lttng_write(fd, zeros, size);
1685 if (ret < size) {
1686 PERROR("write padding to file");
1687 }
1688
1689 free(zeros);
1690
1691 end:
1692 return ret;
1693 }
1694
1695 /*
1696 * Close the current index file if it is open, and create a new one.
1697 *
1698 * Return 0 on success, -1 on error.
1699 */
1700 static
1701 int create_rotate_index_file(struct relay_stream *stream)
1702 {
1703 int ret;
1704 uint32_t major, minor;
1705
1706 /* Put ref on previous index_file. */
1707 if (stream->index_file) {
1708 relay_index_file_put(stream->index_file);
1709 stream->index_file = NULL;
1710 }
1711 major = stream->trace->session->major;
1712 minor = stream->trace->session->minor;
1713 stream->index_file = relay_index_file_create(stream->path_name,
1714 stream->channel_name,
1715 stream->tracefile_size,
1716 tracefile_array_get_file_index_head(stream->tfa),
1717 lttng_to_index_major(major, minor),
1718 lttng_to_index_minor(major, minor));
1719 if (!stream->index_file) {
1720 ret = -1;
1721 goto end;
1722 }
1723
1724 ret = 0;
1725
1726 end:
1727 return ret;
1728 }
1729
1730 static
1731 int do_rotate_stream(struct relay_stream *stream)
1732 {
1733 int ret;
1734
1735 /* Perform the stream rotation. */
1736 ret = stream_fd_rotate(stream->stream_fd, stream->path_name,
1737 stream->channel_name, stream->tracefile_size,
1738 stream->tracefile_count, NULL);
1739 if (ret < 0) {
1740 ERR("Rotating stream output file");
1741 goto end;
1742 }
1743 stream->tracefile_size_current = 0;
1744
1745 /* Rotate also the index if the stream is not a metadata stream. */
1746 if (!stream->is_metadata) {
1747 ret = create_rotate_index_file(stream);
1748 if (ret < 0) {
1749 ERR("Failed to rotate index file");
1750 goto end;
1751 }
1752 }
1753
1754 stream->rotate_at_seq_num = -1ULL;
1755 stream->pos_after_last_complete_data_index = 0;
1756
1757 end:
1758 return ret;
1759 }
1760
1761 /*
1762 * If too much data has been written in a tracefile before we received the
1763 * rotation command, we have to move the excess data to the new tracefile and
1764 * perform the rotation. This can happen because the control and data
1765 * connections are separate, the indexes as well as the commands arrive from
1766 * the control connection and we have no control over the order so we could be
1767 * in a situation where too much data has been received on the data connection
1768 * before the rotation command on the control connection arrives. We don't need
1769 * to update the index because its order is guaranteed with the rotation
1770 * command message.
1771 */
1772 static
1773 int rotate_truncate_stream(struct relay_stream *stream)
1774 {
1775 int ret, old_fd = -1, new_fd = -1;
1776 off_t lseek_ret;
1777 uint64_t diff, pos = 0;
1778 char buf[FILE_COPY_BUFFER_SIZE];
1779 struct stream_fd *new_stream_fd = NULL;
1780
1781 assert(!stream->is_metadata);
1782
1783 assert(stream->tracefile_size_current >
1784 stream->pos_after_last_complete_data_index);
1785 diff = stream->tracefile_size_current -
1786 stream->pos_after_last_complete_data_index;
1787
1788 /* Create the new tracefile. */
1789 new_stream_fd = stream_fd_create(stream->path_name, stream->channel_name,
1790 stream->tracefile_size, stream->tracefile_count, NULL);
1791 if (new_stream_fd < 0) {
1792 ERR("Failed to create new stream file at path %s for channel %s",
1793 stream->path_name, stream->channel_name);
1794 ret = -1;
1795 goto end;
1796 }
1797
1798 old_fd = stream_fd_get_fd(stream->stream_fd);
1799 if (old_fd < 0) {
1800 ret = -1;
1801 goto end;
1802 }
1803
1804 new_fd = stream_fd_get_fd(new_stream_fd);
1805 if (new_fd < 0) {
1806 ret = -1;
1807 goto end;
1808 }
1809
1810 /*
1811 * Rewind the current tracefile to the position at which the rotation
1812 * should have occured.
1813 */
1814 lseek_ret = lseek(old_fd, stream->pos_after_last_complete_data_index,
1815 SEEK_SET);
1816 if (lseek_ret < 0) {
1817 PERROR("seek truncate stream");
1818 ret = -1;
1819 goto end;
1820 }
1821
1822 /* Move data from the old file to the new file. */
1823 while (pos < diff) {
1824 uint64_t count, bytes_left;
1825 ssize_t io_ret;
1826
1827 bytes_left = diff - pos;
1828 count = bytes_left > sizeof(buf) ? sizeof(buf) : bytes_left;
1829 assert(count <= SIZE_MAX);
1830
1831 io_ret = lttng_read(old_fd, buf, count);
1832 if (io_ret < (ssize_t) count) {
1833 char error_string[256];
1834
1835 snprintf(error_string, sizeof(error_string),
1836 "Failed to read %" PRIu64 " bytes from in rotate_truncate_stream(), returned %zi",
1837 count, io_ret);
1838 if (io_ret == -1) {
1839 PERROR("%s", error_string);
1840 } else {
1841 ERR("%s", error_string);
1842 }
1843 ret = -1;
1844 goto end;
1845 }
1846
1847 io_ret = lttng_write(new_fd, buf, count);
1848 if (io_ret < (ssize_t) count) {
1849 char error_string[256];
1850
1851 snprintf(error_string, sizeof(error_string),
1852 "Failed to write %" PRIu64 " bytes from fd %i in rotate_truncate_stream(), returned %zi",
1853 count, new_fd, io_ret);
1854 if (io_ret == -1) {
1855 PERROR("%s", error_string);
1856 } else {
1857 ERR("%s", error_string);
1858 }
1859 ret = -1;
1860 goto end;
1861 }
1862
1863 pos += count;
1864 }
1865
1866 stream_fd_put_fd(new_stream_fd);
1867 new_fd = -1;
1868
1869 /* Truncate the file to get rid of the excess data. */
1870 ret = ftruncate(old_fd, stream->pos_after_last_complete_data_index);
1871 if (ret) {
1872 PERROR("ftruncate");
1873 goto end;
1874 }
1875
1876 stream_fd_put_fd(stream->stream_fd);
1877 old_fd = -1;
1878
1879 /*
1880 * Swap the old stream_fd with the new, releasing the stream's
1881 * reference.
1882 */
1883 stream_fd_put(stream->stream_fd);
1884 stream->stream_fd = new_stream_fd;
1885
1886 ret = create_rotate_index_file(stream);
1887 if (ret < 0) {
1888 ERR("Rotate stream index file");
1889 goto end;
1890 }
1891
1892 /*
1893 * Update the offset and FD of all the eventual indexes created by the
1894 * data connection before the rotation command arrived.
1895 */
1896 ret = relay_index_switch_all_files(stream);
1897 if (ret < 0) {
1898 ERR("Failed to rotate index file");
1899 goto end;
1900 }
1901
1902 stream->tracefile_size_current = diff;
1903 stream->pos_after_last_complete_data_index = 0;
1904 stream->rotate_at_seq_num = -1ULL;
1905
1906 ret = 0;
1907
1908 end:
1909 if (old_fd != -1) {
1910 stream_fd_put_fd(stream->stream_fd);
1911 }
1912 if (new_fd != -1) {
1913 stream_fd_put_fd(new_stream_fd);
1914 }
1915
1916 return ret;
1917 }
1918
1919 /*
1920 * Check if a stream should perform a rotation (for session rotation).
1921 * Must be called with the stream lock held.
1922 *
1923 * Return 0 on success, a negative value on error.
1924 */
1925 static
1926 int try_rotate_stream(struct relay_stream *stream)
1927 {
1928 int ret = 0;
1929
1930 /* No rotation expected. */
1931 if (stream->rotate_at_seq_num == -1ULL) {
1932 goto end;
1933 }
1934
1935 if (stream->prev_seq < stream->rotate_at_seq_num ||
1936 stream->prev_seq == -1ULL) {
1937 DBG("Stream %" PRIu64 " no yet ready for rotation",
1938 stream->stream_handle);
1939 goto end;
1940 } else if (stream->prev_seq > stream->rotate_at_seq_num) {
1941 DBG("Rotation after too much data has been written in tracefile "
1942 "for stream %" PRIu64 ", need to truncate before "
1943 "rotating", stream->stream_handle);
1944 ret = rotate_truncate_stream(stream);
1945 if (ret) {
1946 ERR("Failed to truncate stream");
1947 goto end;
1948 }
1949 } else {
1950 /* stream->prev_seq == stream->rotate_at_seq_num */
1951 DBG("Stream %" PRIu64 " ready for rotation",
1952 stream->stream_handle);
1953 ret = do_rotate_stream(stream);
1954 }
1955
1956 end:
1957 return ret;
1958 }
1959
1960 /*
1961 * relay_recv_metadata: receive the metadata for the session.
1962 */
1963 static int relay_recv_metadata(const struct lttcomm_relayd_hdr *recv_hdr,
1964 struct relay_connection *conn,
1965 const struct lttng_buffer_view *payload)
1966 {
1967 int ret = 0;
1968 ssize_t size_ret;
1969 struct relay_session *session = conn->session;
1970 struct lttcomm_relayd_metadata_payload metadata_payload_header;
1971 struct relay_stream *metadata_stream;
1972 uint64_t metadata_payload_size;
1973 int metadata_fd = -1;
1974
1975 if (!session) {
1976 ERR("Metadata sent before version check");
1977 ret = -1;
1978 goto end;
1979 }
1980
1981 if (recv_hdr->data_size < sizeof(struct lttcomm_relayd_metadata_payload)) {
1982 ERR("Incorrect data size");
1983 ret = -1;
1984 goto end;
1985 }
1986 metadata_payload_size = recv_hdr->data_size -
1987 sizeof(struct lttcomm_relayd_metadata_payload);
1988
1989 memcpy(&metadata_payload_header, payload->data,
1990 sizeof(metadata_payload_header));
1991 metadata_payload_header.stream_id = be64toh(
1992 metadata_payload_header.stream_id);
1993 metadata_payload_header.padding_size = be32toh(
1994 metadata_payload_header.padding_size);
1995
1996 metadata_stream = stream_get_by_id(metadata_payload_header.stream_id);
1997 if (!metadata_stream) {
1998 ret = -1;
1999 goto end;
2000 }
2001
2002 pthread_mutex_lock(&metadata_stream->lock);
2003
2004 metadata_fd = stream_fd_get_fd(metadata_stream->stream_fd);
2005 if (metadata_fd < 0) {
2006 goto end_put;
2007 }
2008 size_ret = lttng_write(metadata_fd,
2009 payload->data + sizeof(metadata_payload_header),
2010 metadata_payload_size);
2011 if (size_ret < metadata_payload_size) {
2012 ERR("Relay error writing metadata on file");
2013 ret = -1;
2014 goto end_put_fd;
2015 }
2016
2017 size_ret = write_padding_to_file(metadata_fd,
2018 metadata_payload_header.padding_size);
2019 if (size_ret < (int64_t) metadata_payload_header.padding_size) {
2020 ret = -1;
2021 goto end_put_fd;
2022 }
2023
2024 metadata_stream->metadata_received +=
2025 metadata_payload_size + metadata_payload_header.padding_size;
2026 DBG2("Relay metadata written. Updated metadata_received %" PRIu64,
2027 metadata_stream->metadata_received);
2028
2029 ret = try_rotate_stream(metadata_stream);
2030 if (ret < 0) {
2031 goto end_put_fd;
2032 }
2033
2034 end_put_fd:
2035 stream_fd_put_fd(metadata_stream->stream_fd);
2036 end_put:
2037 pthread_mutex_unlock(&metadata_stream->lock);
2038 stream_put(metadata_stream);
2039 end:
2040 return ret;
2041 }
2042
2043 /*
2044 * relay_send_version: send relayd version number
2045 */
2046 static int relay_send_version(const struct lttcomm_relayd_hdr *recv_hdr,
2047 struct relay_connection *conn,
2048 const struct lttng_buffer_view *payload)
2049 {
2050 int ret;
2051 ssize_t send_ret;
2052 struct lttcomm_relayd_version reply, msg;
2053 bool compatible = true;
2054
2055 conn->version_check_done = true;
2056
2057 /* Get version from the other side. */
2058 if (payload->size < sizeof(msg)) {
2059 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
2060 sizeof(msg), payload->size);
2061 ret = -1;
2062 goto end;
2063 }
2064
2065 memcpy(&msg, payload->data, sizeof(msg));
2066 msg.major = be32toh(msg.major);
2067 msg.minor = be32toh(msg.minor);
2068
2069 memset(&reply, 0, sizeof(reply));
2070 reply.major = RELAYD_VERSION_COMM_MAJOR;
2071 reply.minor = RELAYD_VERSION_COMM_MINOR;
2072
2073 /* Major versions must be the same */
2074 if (reply.major != msg.major) {
2075 DBG("Incompatible major versions (%u vs %u), deleting session",
2076 reply.major, msg.major);
2077 compatible = false;
2078 }
2079
2080 conn->major = reply.major;
2081 /* We adapt to the lowest compatible version */
2082 if (reply.minor <= msg.minor) {
2083 conn->minor = reply.minor;
2084 } else {
2085 conn->minor = msg.minor;
2086 }
2087
2088 reply.major = htobe32(reply.major);
2089 reply.minor = htobe32(reply.minor);
2090 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
2091 sizeof(reply), 0);
2092 if (send_ret < (ssize_t) sizeof(reply)) {
2093 ERR("Failed to send \"send version\" command reply (ret = %zd)",
2094 send_ret);
2095 ret = -1;
2096 goto end;
2097 } else {
2098 ret = 0;
2099 }
2100
2101 if (!compatible) {
2102 ret = -1;
2103 goto end;
2104 }
2105
2106 DBG("Version check done using protocol %u.%u", conn->major,
2107 conn->minor);
2108
2109 end:
2110 return ret;
2111 }
2112
2113 /*
2114 * Check for data pending for a given stream id from the session daemon.
2115 */
2116 static int relay_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
2117 struct relay_connection *conn,
2118 const struct lttng_buffer_view *payload)
2119 {
2120 struct relay_session *session = conn->session;
2121 struct lttcomm_relayd_data_pending msg;
2122 struct lttcomm_relayd_generic_reply reply;
2123 struct relay_stream *stream;
2124 ssize_t send_ret;
2125 int ret;
2126
2127 DBG("Data pending command received");
2128
2129 if (!session || !conn->version_check_done) {
2130 ERR("Trying to check for data before version check");
2131 ret = -1;
2132 goto end_no_session;
2133 }
2134
2135 if (payload->size < sizeof(msg)) {
2136 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
2137 sizeof(msg), payload->size);
2138 ret = -1;
2139 goto end_no_session;
2140 }
2141 memcpy(&msg, payload->data, sizeof(msg));
2142 msg.stream_id = be64toh(msg.stream_id);
2143 msg.last_net_seq_num = be64toh(msg.last_net_seq_num);
2144
2145 stream = stream_get_by_id(msg.stream_id);
2146 if (stream == NULL) {
2147 ret = -1;
2148 goto end;
2149 }
2150
2151 pthread_mutex_lock(&stream->lock);
2152
2153 DBG("Data pending for stream id %" PRIu64 " prev_seq %" PRIu64
2154 " and last_seq %" PRIu64, msg.stream_id,
2155 stream->prev_seq, msg.last_net_seq_num);
2156
2157 /* Avoid wrapping issue */
2158 if (((int64_t) (stream->prev_seq - msg.last_net_seq_num)) >= 0) {
2159 /* Data has in fact been written and is NOT pending */
2160 ret = 0;
2161 } else {
2162 /* Data still being streamed thus pending */
2163 ret = 1;
2164 }
2165
2166 stream->data_pending_check_done = true;
2167 pthread_mutex_unlock(&stream->lock);
2168
2169 stream_put(stream);
2170 end:
2171
2172 memset(&reply, 0, sizeof(reply));
2173 reply.ret_code = htobe32(ret);
2174 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2175 if (send_ret < (ssize_t) sizeof(reply)) {
2176 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
2177 send_ret);
2178 ret = -1;
2179 }
2180
2181 end_no_session:
2182 return ret;
2183 }
2184
2185 /*
2186 * Wait for the control socket to reach a quiescent state.
2187 *
2188 * Note that for now, when receiving this command from the session
2189 * daemon, this means that every subsequent commands or data received on
2190 * the control socket has been handled. So, this is why we simply return
2191 * OK here.
2192 */
2193 static int relay_quiescent_control(const struct lttcomm_relayd_hdr *recv_hdr,
2194 struct relay_connection *conn,
2195 const struct lttng_buffer_view *payload)
2196 {
2197 int ret;
2198 ssize_t send_ret;
2199 struct relay_stream *stream;
2200 struct lttcomm_relayd_quiescent_control msg;
2201 struct lttcomm_relayd_generic_reply reply;
2202
2203 DBG("Checking quiescent state on control socket");
2204
2205 if (!conn->session || !conn->version_check_done) {
2206 ERR("Trying to check for data before version check");
2207 ret = -1;
2208 goto end_no_session;
2209 }
2210
2211 if (payload->size < sizeof(msg)) {
2212 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2213 sizeof(msg), payload->size);
2214 ret = -1;
2215 goto end_no_session;
2216 }
2217 memcpy(&msg, payload->data, sizeof(msg));
2218 msg.stream_id = be64toh(msg.stream_id);
2219
2220 stream = stream_get_by_id(msg.stream_id);
2221 if (!stream) {
2222 goto reply;
2223 }
2224 pthread_mutex_lock(&stream->lock);
2225 stream->data_pending_check_done = true;
2226 pthread_mutex_unlock(&stream->lock);
2227
2228 DBG("Relay quiescent control pending flag set to %" PRIu64, msg.stream_id);
2229 stream_put(stream);
2230 reply:
2231 memset(&reply, 0, sizeof(reply));
2232 reply.ret_code = htobe32(LTTNG_OK);
2233 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2234 if (send_ret < (ssize_t) sizeof(reply)) {
2235 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
2236 send_ret);
2237 ret = -1;
2238 } else {
2239 ret = 0;
2240 }
2241
2242 end_no_session:
2243 return ret;
2244 }
2245
2246 /*
2247 * Initialize a data pending command. This means that a consumer is about
2248 * to ask for data pending for each stream it holds. Simply iterate over
2249 * all streams of a session and set the data_pending_check_done flag.
2250 *
2251 * This command returns to the client a LTTNG_OK code.
2252 */
2253 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
2254 struct relay_connection *conn,
2255 const struct lttng_buffer_view *payload)
2256 {
2257 int ret;
2258 ssize_t send_ret;
2259 struct lttng_ht_iter iter;
2260 struct lttcomm_relayd_begin_data_pending msg;
2261 struct lttcomm_relayd_generic_reply reply;
2262 struct relay_stream *stream;
2263
2264 assert(recv_hdr);
2265 assert(conn);
2266
2267 DBG("Init streams for data pending");
2268
2269 if (!conn->session || !conn->version_check_done) {
2270 ERR("Trying to check for data before version check");
2271 ret = -1;
2272 goto end_no_session;
2273 }
2274
2275 if (payload->size < sizeof(msg)) {
2276 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2277 sizeof(msg), payload->size);
2278 ret = -1;
2279 goto end_no_session;
2280 }
2281 memcpy(&msg, payload->data, sizeof(msg));
2282 msg.session_id = be64toh(msg.session_id);
2283
2284 /*
2285 * Iterate over all streams to set the begin data pending flag.
2286 * For now, the streams are indexed by stream handle so we have
2287 * to iterate over all streams to find the one associated with
2288 * the right session_id.
2289 */
2290 rcu_read_lock();
2291 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2292 node.node) {
2293 if (!stream_get(stream)) {
2294 continue;
2295 }
2296 if (stream->trace->session->id == msg.session_id) {
2297 pthread_mutex_lock(&stream->lock);
2298 stream->data_pending_check_done = false;
2299 pthread_mutex_unlock(&stream->lock);
2300 DBG("Set begin data pending flag to stream %" PRIu64,
2301 stream->stream_handle);
2302 }
2303 stream_put(stream);
2304 }
2305 rcu_read_unlock();
2306
2307 memset(&reply, 0, sizeof(reply));
2308 /* All good, send back reply. */
2309 reply.ret_code = htobe32(LTTNG_OK);
2310
2311 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2312 if (send_ret < (ssize_t) sizeof(reply)) {
2313 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2314 send_ret);
2315 ret = -1;
2316 } else {
2317 ret = 0;
2318 }
2319
2320 end_no_session:
2321 return ret;
2322 }
2323
2324 /*
2325 * End data pending command. This will check, for a given session id, if
2326 * each stream associated with it has its data_pending_check_done flag
2327 * set. If not, this means that the client lost track of the stream but
2328 * the data is still being streamed on our side. In this case, we inform
2329 * the client that data is in flight.
2330 *
2331 * Return to the client if there is data in flight or not with a ret_code.
2332 */
2333 static int relay_end_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
2334 struct relay_connection *conn,
2335 const struct lttng_buffer_view *payload)
2336 {
2337 int ret;
2338 ssize_t send_ret;
2339 struct lttng_ht_iter iter;
2340 struct lttcomm_relayd_end_data_pending msg;
2341 struct lttcomm_relayd_generic_reply reply;
2342 struct relay_stream *stream;
2343 uint32_t is_data_inflight = 0;
2344
2345 DBG("End data pending command");
2346
2347 if (!conn->session || !conn->version_check_done) {
2348 ERR("Trying to check for data before version check");
2349 ret = -1;
2350 goto end_no_session;
2351 }
2352
2353 if (payload->size < sizeof(msg)) {
2354 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2355 sizeof(msg), payload->size);
2356 ret = -1;
2357 goto end_no_session;
2358 }
2359 memcpy(&msg, payload->data, sizeof(msg));
2360 msg.session_id = be64toh(msg.session_id);
2361
2362 /*
2363 * Iterate over all streams to see if the begin data pending
2364 * flag is set.
2365 */
2366 rcu_read_lock();
2367 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2368 node.node) {
2369 if (!stream_get(stream)) {
2370 continue;
2371 }
2372 if (stream->trace->session->id != msg.session_id) {
2373 stream_put(stream);
2374 continue;
2375 }
2376 pthread_mutex_lock(&stream->lock);
2377 if (!stream->data_pending_check_done) {
2378 if (!stream->closed || !(((int64_t) (stream->prev_seq - stream->last_net_seq_num)) >= 0)) {
2379 is_data_inflight = 1;
2380 DBG("Data is still in flight for stream %" PRIu64,
2381 stream->stream_handle);
2382 pthread_mutex_unlock(&stream->lock);
2383 stream_put(stream);
2384 break;
2385 }
2386 }
2387 pthread_mutex_unlock(&stream->lock);
2388 stream_put(stream);
2389 }
2390 rcu_read_unlock();
2391
2392 memset(&reply, 0, sizeof(reply));
2393 /* All good, send back reply. */
2394 reply.ret_code = htobe32(is_data_inflight);
2395
2396 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2397 if (send_ret < (ssize_t) sizeof(reply)) {
2398 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2399 send_ret);
2400 ret = -1;
2401 } else {
2402 ret = 0;
2403 }
2404
2405 end_no_session:
2406 return ret;
2407 }
2408
2409 /*
2410 * Receive an index for a specific stream.
2411 *
2412 * Return 0 on success else a negative value.
2413 */
2414 static int relay_recv_index(const struct lttcomm_relayd_hdr *recv_hdr,
2415 struct relay_connection *conn,
2416 const struct lttng_buffer_view *payload)
2417 {
2418 int ret;
2419 ssize_t send_ret;
2420 struct relay_session *session = conn->session;
2421 struct lttcomm_relayd_index index_info;
2422 struct relay_index *index;
2423 struct lttcomm_relayd_generic_reply reply;
2424 struct relay_stream *stream;
2425 size_t msg_len;
2426
2427 assert(conn);
2428
2429 DBG("Relay receiving index");
2430
2431 if (!session || !conn->version_check_done) {
2432 ERR("Trying to close a stream before version check");
2433 ret = -1;
2434 goto end_no_session;
2435 }
2436
2437 msg_len = lttcomm_relayd_index_len(
2438 lttng_to_index_major(conn->major, conn->minor),
2439 lttng_to_index_minor(conn->major, conn->minor));
2440 if (payload->size < msg_len) {
2441 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2442 msg_len, payload->size);
2443 ret = -1;
2444 goto end_no_session;
2445 }
2446 memcpy(&index_info, payload->data, msg_len);
2447 index_info.relay_stream_id = be64toh(index_info.relay_stream_id);
2448 index_info.net_seq_num = be64toh(index_info.net_seq_num);
2449 index_info.packet_size = be64toh(index_info.packet_size);
2450 index_info.content_size = be64toh(index_info.content_size);
2451 index_info.timestamp_begin = be64toh(index_info.timestamp_begin);
2452 index_info.timestamp_end = be64toh(index_info.timestamp_end);
2453 index_info.events_discarded = be64toh(index_info.events_discarded);
2454 index_info.stream_id = be64toh(index_info.stream_id);
2455
2456 if (conn->minor >= 8) {
2457 index_info.stream_instance_id =
2458 be64toh(index_info.stream_instance_id);
2459 index_info.packet_seq_num = be64toh(index_info.packet_seq_num);
2460 }
2461
2462 stream = stream_get_by_id(index_info.relay_stream_id);
2463 if (!stream) {
2464 ERR("stream_get_by_id not found");
2465 ret = -1;
2466 goto end;
2467 }
2468 pthread_mutex_lock(&stream->lock);
2469
2470 /* Live beacon handling */
2471 if (index_info.packet_size == 0) {
2472 DBG("Received live beacon for stream %" PRIu64,
2473 stream->stream_handle);
2474
2475 /*
2476 * Only flag a stream inactive when it has already
2477 * received data and no indexes are in flight.
2478 */
2479 if (stream->index_received_seqcount > 0
2480 && stream->indexes_in_flight == 0) {
2481 stream->beacon_ts_end = index_info.timestamp_end;
2482 }
2483 ret = 0;
2484 goto end_stream_put;
2485 } else {
2486 stream->beacon_ts_end = -1ULL;
2487 }
2488
2489 if (stream->ctf_stream_id == -1ULL) {
2490 stream->ctf_stream_id = index_info.stream_id;
2491 }
2492 index = relay_index_get_by_id_or_create(stream, index_info.net_seq_num);
2493 if (!index) {
2494 ret = -1;
2495 ERR("relay_index_get_by_id_or_create index NULL");
2496 goto end_stream_put;
2497 }
2498 if (set_index_control_data(index, &index_info, conn)) {
2499 ERR("set_index_control_data error");
2500 relay_index_put(index);
2501 ret = -1;
2502 goto end_stream_put;
2503 }
2504 ret = relay_index_try_flush(index);
2505 if (ret == 0) {
2506 tracefile_array_commit_seq(stream->tfa);
2507 stream->index_received_seqcount++;
2508 stream->pos_after_last_complete_data_index += index->total_size;
2509 } else if (ret > 0) {
2510 /* no flush. */
2511 ret = 0;
2512 } else {
2513 ERR("relay_index_try_flush error %d", ret);
2514 relay_index_put(index);
2515 ret = -1;
2516 }
2517
2518 end_stream_put:
2519 pthread_mutex_unlock(&stream->lock);
2520 stream_put(stream);
2521
2522 end:
2523
2524 memset(&reply, 0, sizeof(reply));
2525 if (ret < 0) {
2526 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2527 } else {
2528 reply.ret_code = htobe32(LTTNG_OK);
2529 }
2530 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2531 if (send_ret < (ssize_t) sizeof(reply)) {
2532 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret);
2533 ret = -1;
2534 }
2535
2536 end_no_session:
2537 return ret;
2538 }
2539
2540 /*
2541 * Receive the streams_sent message.
2542 *
2543 * Return 0 on success else a negative value.
2544 */
2545 static int relay_streams_sent(const struct lttcomm_relayd_hdr *recv_hdr,
2546 struct relay_connection *conn,
2547 const struct lttng_buffer_view *payload)
2548 {
2549 int ret;
2550 ssize_t send_ret;
2551 struct lttcomm_relayd_generic_reply reply;
2552
2553 assert(conn);
2554
2555 DBG("Relay receiving streams_sent");
2556
2557 if (!conn->session || !conn->version_check_done) {
2558 ERR("Trying to close a stream before version check");
2559 ret = -1;
2560 goto end_no_session;
2561 }
2562
2563 /*
2564 * Publish every pending stream in the connection recv list which are
2565 * now ready to be used by the viewer.
2566 */
2567 publish_connection_local_streams(conn);
2568
2569 memset(&reply, 0, sizeof(reply));
2570 reply.ret_code = htobe32(LTTNG_OK);
2571 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2572 if (send_ret < (ssize_t) sizeof(reply)) {
2573 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2574 send_ret);
2575 ret = -1;
2576 } else {
2577 /* Success. */
2578 ret = 0;
2579 }
2580
2581 end_no_session:
2582 return ret;
2583 }
2584
2585 /*
2586 * relay_rotate_session_stream: rotate a stream to a new tracefile for the session
2587 * rotation feature (not the tracefile rotation feature).
2588 */
2589 static int relay_rotate_session_stream(const struct lttcomm_relayd_hdr *recv_hdr,
2590 struct relay_connection *conn,
2591 const struct lttng_buffer_view *payload)
2592 {
2593 int ret;
2594 ssize_t send_ret;
2595 struct relay_session *session = conn->session;
2596 struct lttcomm_relayd_rotate_stream stream_info;
2597 struct lttcomm_relayd_generic_reply reply;
2598 struct relay_stream *stream;
2599 size_t header_len;
2600 size_t path_len;
2601 struct lttng_buffer_view new_path_view;
2602
2603 DBG("Rotate stream received");
2604
2605 if (!session || !conn->version_check_done) {
2606 ERR("Trying to rotate a stream before version check");
2607 ret = -1;
2608 goto end_no_reply;
2609 }
2610
2611 if (session->major == 2 && session->minor < 11) {
2612 ERR("Unsupported feature before 2.11");
2613 ret = -1;
2614 goto end_no_reply;
2615 }
2616
2617 header_len = sizeof(struct lttcomm_relayd_rotate_stream);
2618
2619 if (payload->size < header_len) {
2620 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2621 header_len, payload->size);
2622 ret = -1;
2623 goto end_no_reply;
2624 }
2625
2626 memcpy(&stream_info, payload->data, header_len);
2627
2628 /* Convert to host */
2629 stream_info.pathname_length = be32toh(stream_info.pathname_length);
2630 stream_info.stream_id = be64toh(stream_info.stream_id);
2631 stream_info.new_chunk_id = be64toh(stream_info.new_chunk_id);
2632 stream_info.rotate_at_seq_num = be64toh(stream_info.rotate_at_seq_num);
2633
2634 path_len = stream_info.pathname_length;
2635 if (payload->size < header_len + path_len) {
2636 ERR("Unexpected payload size in \"relay_rotate_session_stream\" including path: expected >= %zu bytes, got %zu bytes",
2637 header_len + path_len, payload->size);
2638 ret = -1;
2639 goto end_no_reply;
2640 }
2641
2642 /* Ensure it fits in local filename length. */
2643 if (path_len >= LTTNG_PATH_MAX) {
2644 ret = -ENAMETOOLONG;
2645 ERR("Length of relay_rotate_session_stream command's path name (%zu bytes) exceeds the maximal allowed length of %i bytes",
2646 path_len, LTTNG_PATH_MAX);
2647 goto end;
2648 }
2649
2650 new_path_view = lttng_buffer_view_from_view(payload, header_len,
2651 stream_info.pathname_length);
2652
2653 stream = stream_get_by_id(stream_info.stream_id);
2654 if (!stream) {
2655 ret = -1;
2656 goto end;
2657 }
2658
2659 pthread_mutex_lock(&stream->lock);
2660
2661 /*
2662 * Update the trace path (just the folder, the stream name does not
2663 * change).
2664 */
2665 free(stream->path_name);
2666 stream->path_name = create_output_path(new_path_view.data);
2667 if (!stream->path_name) {
2668 ERR("Failed to create a new output path");
2669 ret = -1;
2670 goto end_stream_unlock;
2671 }
2672 ret = utils_mkdir_recursive(stream->path_name, S_IRWXU | S_IRWXG,
2673 -1, -1);
2674 if (ret < 0) {
2675 ERR("relay creating output directory");
2676 ret = -1;
2677 goto end_stream_unlock;
2678 }
2679
2680 assert(stream->current_chunk_id.is_set);
2681 stream->current_chunk_id.value = stream_info.new_chunk_id;
2682
2683 if (stream->is_metadata) {
2684 /*
2685 * The metadata stream is sent only over the control connection
2686 * so we know we have all the data to perform the stream
2687 * rotation.
2688 */
2689 ret = do_rotate_stream(stream);
2690 } else {
2691 stream->rotate_at_seq_num = stream_info.rotate_at_seq_num;
2692 ret = try_rotate_stream(stream);
2693 }
2694 if (ret < 0) {
2695 goto end_stream_unlock;
2696 }
2697
2698 end_stream_unlock:
2699 pthread_mutex_unlock(&stream->lock);
2700 stream_put(stream);
2701 end:
2702 memset(&reply, 0, sizeof(reply));
2703 if (ret < 0) {
2704 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2705 } else {
2706 reply.ret_code = htobe32(LTTNG_OK);
2707 }
2708 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
2709 sizeof(struct lttcomm_relayd_generic_reply), 0);
2710 if (send_ret < (ssize_t) sizeof(reply)) {
2711 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2712 send_ret);
2713 ret = -1;
2714 }
2715
2716 end_no_reply:
2717 return ret;
2718 }
2719
2720 /*
2721 * relay_mkdir: Create a folder on the disk.
2722 */
2723 static int relay_mkdir(const struct lttcomm_relayd_hdr *recv_hdr,
2724 struct relay_connection *conn,
2725 const struct lttng_buffer_view *payload)
2726 {
2727 int ret;
2728 struct relay_session *session = conn->session;
2729 struct lttcomm_relayd_mkdir path_info_header;
2730 struct lttcomm_relayd_generic_reply reply;
2731 char *path = NULL;
2732 size_t header_len;
2733 ssize_t send_ret;
2734 struct lttng_buffer_view path_view;
2735
2736 if (!session || !conn->version_check_done) {
2737 ERR("Trying to create a directory before version check");
2738 ret = -1;
2739 goto end_no_session;
2740 }
2741
2742 if (session->major == 2 && session->minor < 11) {
2743 /*
2744 * This client is not supposed to use this command since
2745 * it predates its introduction.
2746 */
2747 ERR("relay_mkdir command is unsupported before LTTng 2.11");
2748 ret = -1;
2749 goto end_no_session;
2750 }
2751
2752 header_len = sizeof(path_info_header);
2753 if (payload->size < header_len) {
2754 ERR("Unexpected payload size in \"relay_mkdir\": expected >= %zu bytes, got %zu bytes",
2755 header_len, payload->size);
2756 ret = -1;
2757 goto end_no_session;
2758 }
2759
2760 memcpy(&path_info_header, payload->data, header_len);
2761
2762 path_info_header.length = be32toh(path_info_header.length);
2763
2764 if (payload->size < header_len + path_info_header.length) {
2765 ERR("Unexpected payload size in \"relay_mkdir\" including path: expected >= %zu bytes, got %zu bytes",
2766 header_len + path_info_header.length, payload->size);
2767 ret = -1;
2768 goto end_no_session;
2769 }
2770
2771 /* Ensure that it fits in local path length. */
2772 if (path_info_header.length >= LTTNG_PATH_MAX) {
2773 ret = -ENAMETOOLONG;
2774 ERR("Path name argument of mkdir command (%" PRIu32 " bytes) exceeds the maximal length allowed (%d bytes)",
2775 path_info_header.length, LTTNG_PATH_MAX);
2776 goto end;
2777 }
2778
2779 path_view = lttng_buffer_view_from_view(payload, header_len,
2780 path_info_header.length);
2781
2782 path = create_output_path(path_view.data);
2783 if (!path) {
2784 ERR("Failed to create output path");
2785 ret = -1;
2786 goto end;
2787 }
2788
2789 ret = utils_mkdir_recursive(path, S_IRWXU | S_IRWXG, -1, -1);
2790 if (ret < 0) {
2791 ERR("relay creating output directory");
2792 goto end;
2793 }
2794
2795 ret = 0;
2796
2797 end:
2798 memset(&reply, 0, sizeof(reply));
2799 if (ret < 0) {
2800 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2801 } else {
2802 reply.ret_code = htobe32(LTTNG_OK);
2803 }
2804 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2805 if (send_ret < (ssize_t) sizeof(reply)) {
2806 ERR("Failed to send \"mkdir\" command reply (ret = %zd)", send_ret);
2807 ret = -1;
2808 }
2809
2810 end_no_session:
2811 free(path);
2812 return ret;
2813 }
2814
2815 static int validate_rotate_rename_path_length(const char *path_type,
2816 uint32_t path_length)
2817 {
2818 int ret = 0;
2819
2820 if (path_length > LTTNG_PATH_MAX) {
2821 ret = -ENAMETOOLONG;
2822 ERR("rotate rename \"%s\" path name length (%" PRIu32 " bytes) exceeds the allowed size of %i bytes",
2823 path_type, path_length, LTTNG_PATH_MAX);
2824 } else if (path_length == 0) {
2825 ret = -EINVAL;
2826 ERR("rotate rename \"%s\" path name has an illegal length of 0", path_type);
2827 }
2828 return ret;
2829 }
2830
2831 /*
2832 * relay_rotate_rename: rename the trace folder after a rotation is
2833 * completed. We are not closing any fd here, just moving the folder, so it
2834 * works even if data is still in-flight.
2835 */
2836 static int relay_rotate_rename(const struct lttcomm_relayd_hdr *recv_hdr,
2837 struct relay_connection *conn,
2838 const struct lttng_buffer_view *payload)
2839 {
2840 int ret;
2841 ssize_t send_ret;
2842 struct relay_session *session = conn->session;
2843 struct lttcomm_relayd_generic_reply reply;
2844 struct lttcomm_relayd_rotate_rename header;
2845 size_t header_len;
2846 size_t received_paths_size;
2847 char *complete_old_path = NULL, *complete_new_path = NULL;
2848 struct lttng_buffer_view old_path_view;
2849 struct lttng_buffer_view new_path_view;
2850
2851 if (!session || !conn->version_check_done) {
2852 ERR("Trying to rename a trace folder before version check");
2853 ret = -1;
2854 goto end_no_reply;
2855 }
2856
2857 if (session->major == 2 && session->minor < 11) {
2858 ERR("relay_rotate_rename command is unsupported before LTTng 2.11");
2859 ret = -1;
2860 goto end_no_reply;
2861 }
2862
2863 header_len = sizeof(header);
2864 if (payload->size < header_len) {
2865 ERR("Unexpected payload size in \"relay_rotate_rename\": expected >= %zu bytes, got %zu bytes",
2866 header_len, payload->size);
2867 ret = -1;
2868 goto end_no_reply;
2869 }
2870
2871 memcpy(&header, payload->data, header_len);
2872
2873 header.old_path_length = be32toh(header.old_path_length);
2874 header.new_path_length = be32toh(header.new_path_length);
2875 received_paths_size = header.old_path_length + header.new_path_length;
2876
2877 if (payload->size < header_len + received_paths_size) {
2878 ERR("Unexpected payload size in \"relay_rotate_rename\" including paths: expected >= %zu bytes, got %zu bytes",
2879 header_len, payload->size);
2880 ret = -1;
2881 goto end_no_reply;
2882 }
2883
2884 /* Ensure the paths don't exceed their allowed size. */
2885 ret = validate_rotate_rename_path_length("old", header.old_path_length);
2886 if (ret) {
2887 goto end;
2888 }
2889 ret = validate_rotate_rename_path_length("new", header.new_path_length);
2890 if (ret) {
2891 goto end;
2892 }
2893
2894 old_path_view = lttng_buffer_view_from_view(payload, header_len,
2895 header.old_path_length);
2896 new_path_view = lttng_buffer_view_from_view(payload,
2897 header_len + header.old_path_length,
2898 header.new_path_length);
2899
2900 /* Validate that both paths received are NULL terminated. */
2901 if (old_path_view.data[old_path_view.size - 1] != '\0') {
2902 ERR("relay_rotate_rename command's \"old\" path is invalid (not NULL terminated)");
2903 ret = -1;
2904 goto end;
2905 }
2906 if (new_path_view.data[new_path_view.size - 1] != '\0') {
2907 ERR("relay_rotate_rename command's \"new\" path is invalid (not NULL terminated)");
2908 ret = -1;
2909 goto end;
2910 }
2911
2912 complete_old_path = create_output_path(old_path_view.data);
2913 if (!complete_old_path) {
2914 ERR("Failed to build old output path in rotate_rename command");
2915 ret = -1;
2916 goto end;
2917 }
2918
2919 complete_new_path = create_output_path(new_path_view.data);
2920 if (!complete_new_path) {
2921 ERR("Failed to build new output path in rotate_rename command");
2922 ret = -1;
2923 goto end;
2924 }
2925
2926 ret = utils_mkdir_recursive(complete_new_path, S_IRWXU | S_IRWXG,
2927 -1, -1);
2928 if (ret < 0) {
2929 ERR("Failed to mkdir() rotate_rename's \"new\" output directory at \"%s\"",
2930 complete_new_path);
2931 goto end;
2932 }
2933
2934 /*
2935 * If a domain has not yet created its channel, the domain-specific
2936 * folder might not exist, but this is not an error.
2937 */
2938 ret = rename(complete_old_path, complete_new_path);
2939 if (ret < 0 && errno != ENOENT) {
2940 PERROR("Renaming chunk in rotate_rename command from \"%s\" to \"%s\"",
2941 complete_old_path, complete_new_path);
2942 goto end;
2943 }
2944 ret = 0;
2945
2946 end:
2947 memset(&reply, 0, sizeof(reply));
2948 if (ret < 0) {
2949 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2950 } else {
2951 reply.ret_code = htobe32(LTTNG_OK);
2952 }
2953 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
2954 sizeof(reply), 0);
2955 if (send_ret < sizeof(reply)) {
2956 ERR("Failed to send \"rotate rename\" command reply (ret = %zd)",
2957 send_ret);
2958 ret = -1;
2959 }
2960
2961 end_no_reply:
2962 free(complete_old_path);
2963 free(complete_new_path);
2964 return ret;
2965 }
2966
2967 /*
2968 * Check if all the streams in the session have completed the last rotation.
2969 * The chunk_id value is used to distinguish the cases where a stream was
2970 * closed on the consumerd before the rotation started but it still active on
2971 * the relayd, and the case where a stream appeared on the consumerd/relayd
2972 * after the last rotation started (in that case, it is already writing in the
2973 * new chunk folder).
2974 */
2975 static
2976 int relay_rotate_pending(const struct lttcomm_relayd_hdr *recv_hdr,
2977 struct relay_connection *conn,
2978 const struct lttng_buffer_view *payload)
2979 {
2980 struct relay_session *session = conn->session;
2981 struct lttcomm_relayd_rotate_pending msg;
2982 struct lttcomm_relayd_rotate_pending_reply reply;
2983 struct lttng_ht_iter iter;
2984 struct relay_stream *stream;
2985 int ret = 0;
2986 ssize_t send_ret;
2987 uint64_t chunk_id;
2988 bool rotate_pending = false;
2989
2990 DBG("Rotate pending command received");
2991
2992 if (!session || !conn->version_check_done) {
2993 ERR("Trying to check for data before version check");
2994 ret = -1;
2995 goto end_no_reply;
2996 }
2997
2998 if (session->major == 2 && session->minor < 11) {
2999 ERR("Unsupported feature before 2.11");
3000 ret = -1;
3001 goto end_no_reply;
3002 }
3003
3004 if (payload->size < sizeof(msg)) {
3005 ERR("Unexpected payload size in \"relay_rotate_pending\": expected >= %zu bytes, got %zu bytes",
3006 sizeof(msg), payload->size);
3007 ret = -1;
3008 goto end_no_reply;
3009 }
3010
3011 memcpy(&msg, payload->data, sizeof(msg));
3012
3013 chunk_id = be64toh(msg.chunk_id);
3014
3015 DBG("Evaluating rotate pending for session \"%s\" and chunk id %" PRIu64,
3016 session->session_name, chunk_id);
3017
3018 /*
3019 * Iterate over all the streams in the session and check if they are
3020 * still waiting for data to perform their rotation.
3021 */
3022 rcu_read_lock();
3023 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
3024 node.node) {
3025 if (!stream_get(stream)) {
3026 continue;
3027 }
3028 if (stream->trace->session != session) {
3029 stream_put(stream);
3030 continue;
3031 }
3032 pthread_mutex_lock(&stream->lock);
3033 if (stream->rotate_at_seq_num != -1ULL) {
3034 /* We have not yet performed the rotation. */
3035 rotate_pending = true;
3036 DBG("Stream %" PRIu64 " is still rotating",
3037 stream->stream_handle);
3038 } else if (stream->current_chunk_id.value < chunk_id) {
3039 /*
3040 * Stream closed on the consumer but still active on the
3041 * relay.
3042 */
3043 rotate_pending = true;
3044 DBG("Stream %" PRIu64 " did not exist on the consumer "
3045 "when the last rotation started, but is"
3046 "still waiting for data before getting"
3047 "closed",
3048 stream->stream_handle);
3049 }
3050 pthread_mutex_unlock(&stream->lock);
3051 stream_put(stream);
3052 if (rotate_pending) {
3053 goto send_reply;
3054 }
3055 }
3056
3057 send_reply:
3058 rcu_read_unlock();
3059 memset(&reply, 0, sizeof(reply));
3060 reply.generic.ret_code = htobe32((uint32_t) LTTNG_OK);
3061 reply.is_pending = (uint8_t) !!rotate_pending;
3062 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
3063 sizeof(reply), 0);
3064 if (send_ret < (ssize_t) sizeof(reply)) {
3065 ERR("Failed to send \"rotate pending\" command reply (ret = %zd)",
3066 send_ret);
3067 ret = -1;
3068 }
3069
3070 end_no_reply:
3071 return ret;
3072 }
3073
3074 #define DBG_CMD(cmd_name, conn) \
3075 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
3076
3077 static int relay_process_control_command(struct relay_connection *conn,
3078 const struct lttcomm_relayd_hdr *header,
3079 const struct lttng_buffer_view *payload)
3080 {
3081 int ret = 0;
3082
3083 switch (header->cmd) {
3084 case RELAYD_CREATE_SESSION:
3085 DBG_CMD("RELAYD_CREATE_SESSION", conn);
3086 ret = relay_create_session(header, conn, payload);
3087 break;
3088 case RELAYD_ADD_STREAM:
3089 DBG_CMD("RELAYD_ADD_STREAM", conn);
3090 ret = relay_add_stream(header, conn, payload);
3091 break;
3092 case RELAYD_START_DATA:
3093 DBG_CMD("RELAYD_START_DATA", conn);
3094 ret = relay_start(header, conn, payload);
3095 break;
3096 case RELAYD_SEND_METADATA:
3097 DBG_CMD("RELAYD_SEND_METADATA", conn);
3098 ret = relay_recv_metadata(header, conn, payload);
3099 break;
3100 case RELAYD_VERSION:
3101 DBG_CMD("RELAYD_VERSION", conn);
3102 ret = relay_send_version(header, conn, payload);
3103 break;
3104 case RELAYD_CLOSE_STREAM:
3105 DBG_CMD("RELAYD_CLOSE_STREAM", conn);
3106 ret = relay_close_stream(header, conn, payload);
3107 break;
3108 case RELAYD_DATA_PENDING:
3109 DBG_CMD("RELAYD_DATA_PENDING", conn);
3110 ret = relay_data_pending(header, conn, payload);
3111 break;
3112 case RELAYD_QUIESCENT_CONTROL:
3113 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn);
3114 ret = relay_quiescent_control(header, conn, payload);
3115 break;
3116 case RELAYD_BEGIN_DATA_PENDING:
3117 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn);
3118 ret = relay_begin_data_pending(header, conn, payload);
3119 break;
3120 case RELAYD_END_DATA_PENDING:
3121 DBG_CMD("RELAYD_END_DATA_PENDING", conn);
3122 ret = relay_end_data_pending(header, conn, payload);
3123 break;
3124 case RELAYD_SEND_INDEX:
3125 DBG_CMD("RELAYD_SEND_INDEX", conn);
3126 ret = relay_recv_index(header, conn, payload);
3127 break;
3128 case RELAYD_STREAMS_SENT:
3129 DBG_CMD("RELAYD_STREAMS_SENT", conn);
3130 ret = relay_streams_sent(header, conn, payload);
3131 break;
3132 case RELAYD_RESET_METADATA:
3133 DBG_CMD("RELAYD_RESET_METADATA", conn);
3134 ret = relay_reset_metadata(header, conn, payload);
3135 break;
3136 case RELAYD_ROTATE_STREAM:
3137 DBG_CMD("RELAYD_ROTATE_STREAM", conn);
3138 ret = relay_rotate_session_stream(header, conn, payload);
3139 break;
3140 case RELAYD_ROTATE_RENAME:
3141 DBG_CMD("RELAYD_ROTATE_RENAME", conn);
3142 ret = relay_rotate_rename(header, conn, payload);
3143 break;
3144 case RELAYD_ROTATE_PENDING:
3145 DBG_CMD("RELAYD_ROTATE_PENDING", conn);
3146 ret = relay_rotate_pending(header, conn, payload);
3147 break;
3148 case RELAYD_MKDIR:
3149 DBG_CMD("RELAYD_MKDIR", conn);
3150 ret = relay_mkdir(header, conn, payload);
3151 break;
3152 case RELAYD_UPDATE_SYNC_INFO:
3153 default:
3154 ERR("Received unknown command (%u)", header->cmd);
3155 relay_unknown_command(conn);
3156 ret = -1;
3157 goto end;
3158 }
3159
3160 end:
3161 return ret;
3162 }
3163
3164 static enum relay_connection_status relay_process_control_receive_payload(
3165 struct relay_connection *conn)
3166 {
3167 int ret = 0;
3168 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
3169 struct lttng_dynamic_buffer *reception_buffer =
3170 &conn->protocol.ctrl.reception_buffer;
3171 struct ctrl_connection_state_receive_payload *state =
3172 &conn->protocol.ctrl.state.receive_payload;
3173 struct lttng_buffer_view payload_view;
3174
3175 if (state->left_to_receive == 0) {
3176 /* Short-circuit for payload-less commands. */
3177 goto reception_complete;
3178 }
3179
3180 ret = conn->sock->ops->recvmsg(conn->sock,
3181 reception_buffer->data + state->received,
3182 state->left_to_receive, MSG_DONTWAIT);
3183 if (ret < 0) {
3184 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3185 PERROR("Unable to receive command payload on sock %d",
3186 conn->sock->fd);
3187 status = RELAY_CONNECTION_STATUS_ERROR;
3188 }
3189 goto end;
3190 } else if (ret == 0) {
3191 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
3192 status = RELAY_CONNECTION_STATUS_CLOSED;
3193 goto end;
3194 }
3195
3196 assert(ret > 0);
3197 assert(ret <= state->left_to_receive);
3198
3199 state->left_to_receive -= ret;
3200 state->received += ret;
3201
3202 if (state->left_to_receive > 0) {
3203 /*
3204 * Can't transition to the protocol's next state, wait to
3205 * receive the rest of the header.
3206 */
3207 DBG3("Partial reception of control connection protocol payload (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
3208 state->received, state->left_to_receive,
3209 conn->sock->fd);
3210 goto end;
3211 }
3212
3213 reception_complete:
3214 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64 " bytes",
3215 conn->sock->fd, state->received);
3216 /*
3217 * The payload required to process the command has been received.
3218 * A view to the reception buffer is forwarded to the various
3219 * commands and the state of the control is reset on success.
3220 *
3221 * Commands are responsible for sending their reply to the peer.
3222 */
3223 payload_view = lttng_buffer_view_from_dynamic_buffer(reception_buffer,
3224 0, -1);
3225 ret = relay_process_control_command(conn,
3226 &state->header, &payload_view);
3227 if (ret < 0) {
3228 status = RELAY_CONNECTION_STATUS_ERROR;
3229 goto end;
3230 }
3231
3232 ret = connection_reset_protocol_state(conn);
3233 if (ret) {
3234 status = RELAY_CONNECTION_STATUS_ERROR;
3235 }
3236 end:
3237 return status;
3238 }
3239
3240 static enum relay_connection_status relay_process_control_receive_header(
3241 struct relay_connection *conn)
3242 {
3243 int ret = 0;
3244 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
3245 struct lttcomm_relayd_hdr header;
3246 struct lttng_dynamic_buffer *reception_buffer =
3247 &conn->protocol.ctrl.reception_buffer;
3248 struct ctrl_connection_state_receive_header *state =
3249 &conn->protocol.ctrl.state.receive_header;
3250
3251 assert(state->left_to_receive != 0);
3252
3253 ret = conn->sock->ops->recvmsg(conn->sock,
3254 reception_buffer->data + state->received,
3255 state->left_to_receive, MSG_DONTWAIT);
3256 if (ret < 0) {
3257 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3258 PERROR("Unable to receive control command header on sock %d",
3259 conn->sock->fd);
3260 status = RELAY_CONNECTION_STATUS_ERROR;
3261 }
3262 goto end;
3263 } else if (ret == 0) {
3264 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
3265 status = RELAY_CONNECTION_STATUS_CLOSED;
3266 goto end;
3267 }
3268
3269 assert(ret > 0);
3270 assert(ret <= state->left_to_receive);
3271
3272 state->left_to_receive -= ret;
3273 state->received += ret;
3274
3275 if (state->left_to_receive > 0) {
3276 /*
3277 * Can't transition to the protocol's next state, wait to
3278 * receive the rest of the header.
3279 */
3280 DBG3("Partial reception of control connection protocol header (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
3281 state->received, state->left_to_receive,
3282 conn->sock->fd);
3283 goto end;
3284 }
3285
3286 /* Transition to next state: receiving the command's payload. */
3287 conn->protocol.ctrl.state_id =
3288 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD;
3289 memcpy(&header, reception_buffer->data, sizeof(header));
3290 header.circuit_id = be64toh(header.circuit_id);
3291 header.data_size = be64toh(header.data_size);
3292 header.cmd = be32toh(header.cmd);
3293 header.cmd_version = be32toh(header.cmd_version);
3294 memcpy(&conn->protocol.ctrl.state.receive_payload.header,
3295 &header, sizeof(header));
3296
3297 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32 ", cmd_version = %" PRIu32 ", payload size = %" PRIu64 " bytes",
3298 conn->sock->fd, header.cmd, header.cmd_version,
3299 header.data_size);
3300
3301 if (header.data_size > DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE) {
3302 ERR("Command header indicates a payload (%" PRIu64 " bytes) that exceeds the maximal payload size allowed on a control connection.",
3303 header.data_size);
3304 status = RELAY_CONNECTION_STATUS_ERROR;
3305 goto end;
3306 }
3307
3308 conn->protocol.ctrl.state.receive_payload.left_to_receive =
3309 header.data_size;
3310 conn->protocol.ctrl.state.receive_payload.received = 0;
3311 ret = lttng_dynamic_buffer_set_size(reception_buffer,
3312 header.data_size);
3313 if (ret) {
3314 status = RELAY_CONNECTION_STATUS_ERROR;
3315 goto end;
3316 }
3317
3318 if (header.data_size == 0) {
3319 /*
3320 * Manually invoke the next state as the poll loop
3321 * will not wake-up to allow us to proceed further.
3322 */
3323 status = relay_process_control_receive_payload(conn);
3324 }
3325 end:
3326 return status;
3327 }
3328
3329 /*
3330 * Process the commands received on the control socket
3331 */
3332 static enum relay_connection_status relay_process_control(
3333 struct relay_connection *conn)
3334 {
3335 enum relay_connection_status status;
3336
3337 switch (conn->protocol.ctrl.state_id) {
3338 case CTRL_CONNECTION_STATE_RECEIVE_HEADER:
3339 status = relay_process_control_receive_header(conn);
3340 break;
3341 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD:
3342 status = relay_process_control_receive_payload(conn);
3343 break;
3344 default:
3345 ERR("Unknown control connection protocol state encountered.");
3346 abort();
3347 }
3348
3349 return status;
3350 }
3351
3352 /*
3353 * Handle index for a data stream.
3354 *
3355 * Called with the stream lock held.
3356 *
3357 * Return 0 on success else a negative value.
3358 */
3359 static int handle_index_data(struct relay_stream *stream, uint64_t net_seq_num,
3360 bool rotate_index, bool *flushed, uint64_t total_size)
3361 {
3362 int ret = 0;
3363 uint64_t data_offset;
3364 struct relay_index *index;
3365
3366 /* Get data offset because we are about to update the index. */
3367 data_offset = htobe64(stream->tracefile_size_current);
3368
3369 DBG("handle_index_data: stream %" PRIu64 " net_seq_num %" PRIu64 " data offset %" PRIu64,
3370 stream->stream_handle, net_seq_num, stream->tracefile_size_current);
3371
3372 /*
3373 * Lookup for an existing index for that stream id/sequence
3374 * number. If it exists, the control thread has already received the
3375 * data for it, thus we need to write it to disk.
3376 */
3377 index = relay_index_get_by_id_or_create(stream, net_seq_num);
3378 if (!index) {
3379 ret = -1;
3380 goto end;
3381 }
3382
3383 if (rotate_index || !stream->index_file) {
3384 ret = create_rotate_index_file(stream);
3385 if (ret < 0) {
3386 ERR("Failed to rotate index");
3387 /* Put self-ref for this index due to error. */
3388 relay_index_put(index);
3389 index = NULL;
3390 goto end;
3391 }
3392 }
3393
3394 if (relay_index_set_file(index, stream->index_file, data_offset)) {
3395 ret = -1;
3396 /* Put self-ref for this index due to error. */
3397 relay_index_put(index);
3398 index = NULL;
3399 goto end;
3400 }
3401
3402 ret = relay_index_try_flush(index);
3403 if (ret == 0) {
3404 tracefile_array_commit_seq(stream->tfa);
3405 stream->index_received_seqcount++;
3406 *flushed = true;
3407 } else if (ret > 0) {
3408 index->total_size = total_size;
3409 /* No flush. */
3410 ret = 0;
3411 } else {
3412 /* Put self-ref for this index due to error. */
3413 relay_index_put(index);
3414 index = NULL;
3415 ret = -1;
3416 }
3417 end:
3418 return ret;
3419 }
3420
3421 static enum relay_connection_status relay_process_data_receive_header(
3422 struct relay_connection *conn)
3423 {
3424 int ret;
3425 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
3426 struct data_connection_state_receive_header *state =
3427 &conn->protocol.data.state.receive_header;
3428 struct lttcomm_relayd_data_hdr header;
3429 struct relay_stream *stream;
3430
3431 assert(state->left_to_receive != 0);
3432
3433 ret = conn->sock->ops->recvmsg(conn->sock,
3434 state->header_reception_buffer + state->received,
3435 state->left_to_receive, MSG_DONTWAIT);
3436 if (ret < 0) {
3437 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3438 PERROR("Unable to receive data header on sock %d", conn->sock->fd);
3439 status = RELAY_CONNECTION_STATUS_ERROR;
3440 }
3441 goto end;
3442 } else if (ret == 0) {
3443 /* Orderly shutdown. Not necessary to print an error. */
3444 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
3445 status = RELAY_CONNECTION_STATUS_CLOSED;
3446 goto end;
3447 }
3448
3449 assert(ret > 0);
3450 assert(ret <= state->left_to_receive);
3451
3452 state->left_to_receive -= ret;
3453 state->received += ret;
3454
3455 if (state->left_to_receive > 0) {
3456 /*
3457 * Can't transition to the protocol's next state, wait to
3458 * receive the rest of the header.
3459 */
3460 DBG3("Partial reception of data connection header (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
3461 state->received, state->left_to_receive,
3462 conn->sock->fd);
3463 goto end;
3464 }
3465
3466 /* Transition to next state: receiving the payload. */
3467 conn->protocol.data.state_id = DATA_CONNECTION_STATE_RECEIVE_PAYLOAD;
3468
3469 memcpy(&header, state->header_reception_buffer, sizeof(header));
3470 header.circuit_id = be64toh(header.circuit_id);
3471 header.stream_id = be64toh(header.stream_id);
3472 header.data_size = be32toh(header.data_size);
3473 header.net_seq_num = be64toh(header.net_seq_num);
3474 header.padding_size = be32toh(header.padding_size);
3475 memcpy(&conn->protocol.data.state.receive_payload.header, &header, sizeof(header));
3476
3477 conn->protocol.data.state.receive_payload.left_to_receive =
3478 header.data_size;
3479 conn->protocol.data.state.receive_payload.received = 0;
3480 conn->protocol.data.state.receive_payload.rotate_index = false;
3481
3482 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64 ", stream_id = %" PRIu64 ", data_size = %" PRIu32 ", net_seq_num = %" PRIu64 ", padding_size = %" PRIu32,
3483 conn->sock->fd, header.circuit_id,
3484 header.stream_id, header.data_size,
3485 header.net_seq_num, header.padding_size);
3486
3487 stream = stream_get_by_id(header.stream_id);
3488 if (!stream) {
3489 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64,
3490 header.stream_id);
3491 /* Protocol error. */
3492 status = RELAY_CONNECTION_STATUS_ERROR;
3493 goto end;
3494 }
3495
3496 pthread_mutex_lock(&stream->lock);
3497
3498 /* Check if a rotation is needed. */
3499 if (stream->tracefile_size > 0 &&
3500 (stream->tracefile_size_current + header.data_size) >
3501 stream->tracefile_size) {
3502 uint64_t old_id, new_id;
3503
3504 old_id = tracefile_array_get_file_index_head(stream->tfa);
3505 tracefile_array_file_rotate(stream->tfa);
3506
3507 /* new_id is updated by utils_rotate_stream_file. */
3508 new_id = old_id;
3509
3510 ret = stream_fd_rotate(stream->stream_fd, stream->path_name,
3511 stream->channel_name, stream->tracefile_size,
3512 stream->tracefile_count, &new_id);
3513 if (ret < 0) {
3514 ERR("Failed to rotate stream output file");
3515 status = RELAY_CONNECTION_STATUS_ERROR;
3516 goto end_stream_unlock;
3517 }
3518
3519 /*
3520 * Reset current size because we just performed a stream
3521 * rotation.
3522 */
3523 stream->tracefile_size_current = 0;
3524 conn->protocol.data.state.receive_payload.rotate_index = true;
3525 }
3526
3527 end_stream_unlock:
3528 pthread_mutex_unlock(&stream->lock);
3529 stream_put(stream);
3530 end:
3531 return status;
3532 }
3533
3534 static enum relay_connection_status relay_process_data_receive_payload(
3535 struct relay_connection *conn)
3536 {
3537 int ret;
3538 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
3539 struct relay_stream *stream;
3540 struct data_connection_state_receive_payload *state =
3541 &conn->protocol.data.state.receive_payload;
3542 const size_t chunk_size = RECV_DATA_BUFFER_SIZE;
3543 char data_buffer[chunk_size];
3544 bool partial_recv = false;
3545 bool new_stream = false, close_requested = false, index_flushed = false;
3546 uint64_t left_to_receive = state->left_to_receive;
3547 struct relay_session *session;
3548 int stream_fd = -1;
3549
3550 DBG3("Receiving data for stream id %" PRIu64 " seqnum %" PRIu64 ", %" PRIu64" bytes received, %" PRIu64 " bytes left to receive",
3551 state->header.stream_id, state->header.net_seq_num,
3552 state->received, left_to_receive);
3553
3554 stream = stream_get_by_id(state->header.stream_id);
3555 if (!stream) {
3556 /* Protocol error. */
3557 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64,
3558 state->header.stream_id);
3559 status = RELAY_CONNECTION_STATUS_ERROR;
3560 goto end;
3561 }
3562
3563 pthread_mutex_lock(&stream->lock);
3564 session = stream->trace->session;
3565 if (!conn->session) {
3566 ret = connection_set_session(conn, session);
3567 if (ret) {
3568 status = RELAY_CONNECTION_STATUS_ERROR;
3569 goto end_stream_unlock;
3570 }
3571 }
3572
3573 stream_fd = stream_fd_get_fd(stream->stream_fd);
3574 if (stream_fd < 0) {
3575 status = RELAY_CONNECTION_STATUS_ERROR;
3576 goto end_stream_unlock;
3577 }
3578
3579 /*
3580 * The size of the "chunk" received on any iteration is bounded by:
3581 * - the data left to receive,
3582 * - the data immediately available on the socket,
3583 * - the on-stack data buffer
3584 */
3585 while (left_to_receive > 0 && !partial_recv) {
3586 ssize_t write_ret;
3587 size_t recv_size = min(left_to_receive, chunk_size);
3588
3589 ret = conn->sock->ops->recvmsg(conn->sock, data_buffer,
3590 recv_size, MSG_DONTWAIT);
3591 if (ret < 0) {
3592 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3593 PERROR("Socket %d error", conn->sock->fd);
3594 status = RELAY_CONNECTION_STATUS_ERROR;
3595 }
3596 goto end_put_fd;
3597 } else if (ret == 0) {
3598 /* No more data ready to be consumed on socket. */
3599 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64,
3600 state->header.stream_id);
3601 status = RELAY_CONNECTION_STATUS_CLOSED;
3602 break;
3603 } else if (ret < (int) recv_size) {
3604 /*
3605 * All the data available on the socket has been
3606 * consumed.
3607 */
3608 partial_recv = true;
3609 }
3610
3611 recv_size = ret;
3612
3613 /* Write data to stream output fd. */
3614 write_ret = lttng_write(stream_fd, data_buffer,
3615 recv_size);
3616 if (write_ret < (ssize_t) recv_size) {
3617 ERR("Relay error writing data to file");
3618 status = RELAY_CONNECTION_STATUS_ERROR;
3619 goto end_put_fd;
3620 }
3621
3622 left_to_receive -= recv_size;
3623 state->received += recv_size;
3624 state->left_to_receive = left_to_receive;
3625
3626 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64,
3627 write_ret, stream->stream_handle);
3628 }
3629
3630 if (state->left_to_receive > 0) {
3631 /*
3632 * Did not receive all the data expected, wait for more data to
3633 * become available on the socket.
3634 */
3635 DBG3("Partial receive on data connection of stream id %" PRIu64 ", %" PRIu64 " bytes received, %" PRIu64 " bytes left to receive",
3636 state->header.stream_id, state->received,
3637 state->left_to_receive);
3638 goto end_put_fd;
3639 }
3640
3641 ret = write_padding_to_file(stream_fd,
3642 state->header.padding_size);
3643 if ((int64_t) ret < (int64_t) state->header.padding_size) {
3644 ERR("write_padding_to_file: fail stream %" PRIu64 " net_seq_num %" PRIu64 " ret %d",
3645 stream->stream_handle,
3646 state->header.net_seq_num, ret);
3647 status = RELAY_CONNECTION_STATUS_ERROR;
3648 goto end_put_fd;
3649 }
3650
3651
3652 if (session->minor >= 4 && !session->snapshot) {
3653 ret = handle_index_data(stream, state->header.net_seq_num,
3654 state->rotate_index, &index_flushed, state->header.data_size + state->header.padding_size);
3655 if (ret < 0) {
3656 ERR("handle_index_data: fail stream %" PRIu64 " net_seq_num %" PRIu64 " ret %d",
3657 stream->stream_handle,
3658 state->header.net_seq_num, ret);
3659 status = RELAY_CONNECTION_STATUS_ERROR;
3660 goto end_put_fd;
3661 }
3662 }
3663
3664 stream->tracefile_size_current += state->header.data_size +
3665 state->header.padding_size;
3666
3667 if (stream->prev_seq == -1ULL) {
3668 new_stream = true;
3669 }
3670 if (index_flushed) {
3671 stream->pos_after_last_complete_data_index =
3672 stream->tracefile_size_current;
3673 }
3674
3675 stream->prev_seq = state->header.net_seq_num;
3676
3677 /*
3678 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3679 * contents of *state which are aliased (union) to the same location as
3680 * the new state. Don't use it beyond this point.
3681 */
3682 connection_reset_protocol_state(conn);
3683 state = NULL;
3684
3685 ret = try_rotate_stream(stream);
3686 if (ret < 0) {
3687 status = RELAY_CONNECTION_STATUS_ERROR;
3688 goto end_put_fd;
3689 }
3690 end_put_fd:
3691 (void) stream_fd_put_fd(stream->stream_fd);
3692 end_stream_unlock:
3693 close_requested = stream->close_requested;
3694 pthread_mutex_unlock(&stream->lock);
3695 if (close_requested && left_to_receive == 0) {
3696 try_stream_close(stream);
3697 }
3698
3699 if (new_stream) {
3700 pthread_mutex_lock(&session->lock);
3701 uatomic_set(&session->new_streams, 1);
3702 pthread_mutex_unlock(&session->lock);
3703 }
3704
3705 stream_put(stream);
3706 end:
3707 return status;
3708 }
3709
3710 /*
3711 * relay_process_data: Process the data received on the data socket
3712 */
3713 static enum relay_connection_status relay_process_data(
3714 struct relay_connection *conn)
3715 {
3716 enum relay_connection_status status;
3717
3718 switch (conn->protocol.data.state_id) {
3719 case DATA_CONNECTION_STATE_RECEIVE_HEADER:
3720 status = relay_process_data_receive_header(conn);
3721 break;
3722 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD:
3723 status = relay_process_data_receive_payload(conn);
3724 break;
3725 default:
3726 ERR("Unexpected data connection communication state.");
3727 abort();
3728 }
3729
3730 return status;
3731 }
3732
3733 static void cleanup_connection_pollfd(struct lttng_poll_event *events, int pollfd)
3734 {
3735 int ret;
3736
3737 (void) lttng_poll_del(events, pollfd);
3738
3739 ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker, &pollfd, 1,
3740 fd_tracker_util_close_fd, NULL);
3741 if (ret < 0) {
3742 ERR("Closing pollfd %d", pollfd);
3743 }
3744 }
3745
3746 static void relay_thread_close_connection(struct lttng_poll_event *events,
3747 int pollfd, struct relay_connection *conn)
3748 {
3749 const char *type_str;
3750
3751 switch (conn->type) {
3752 case RELAY_DATA:
3753 type_str = "Data";
3754 break;
3755 case RELAY_CONTROL:
3756 type_str = "Control";
3757 break;
3758 case RELAY_VIEWER_COMMAND:
3759 type_str = "Viewer Command";
3760 break;
3761 case RELAY_VIEWER_NOTIFICATION:
3762 type_str = "Viewer Notification";
3763 break;
3764 default:
3765 type_str = "Unknown";
3766 }
3767 cleanup_connection_pollfd(events, pollfd);
3768 connection_put(conn);
3769 DBG("%s connection closed with %d", type_str, pollfd);
3770 }
3771
3772 /*
3773 * This thread does the actual work
3774 */
3775 static void *relay_thread_worker(void *data)
3776 {
3777 int ret, err = -1, last_seen_data_fd = -1;
3778 uint32_t nb_fd;
3779 struct lttng_poll_event events;
3780 struct lttng_ht *relay_connections_ht;
3781 struct lttng_ht_iter iter;
3782 struct relay_connection *destroy_conn = NULL;
3783
3784 DBG("[thread] Relay worker started");
3785
3786 rcu_register_thread();
3787
3788 health_register(health_relayd, HEALTH_RELAYD_TYPE_WORKER);
3789
3790 if (testpoint(relayd_thread_worker)) {
3791 goto error_testpoint;
3792 }
3793
3794 health_code_update();
3795
3796 /* table of connections indexed on socket */
3797 relay_connections_ht = lttng_ht_new(0, LTTNG_HT_TYPE_ULONG);
3798 if (!relay_connections_ht) {
3799 goto relay_connections_ht_error;
3800 }
3801
3802 ret = create_named_thread_poll_set(&events, 2, "Worker thread epoll");
3803 if (ret < 0) {
3804 goto error_poll_create;
3805 }
3806
3807 ret = lttng_poll_add(&events, relay_conn_pipe[0], LPOLLIN | LPOLLRDHUP);
3808 if (ret < 0) {
3809 goto error;
3810 }
3811
3812 restart:
3813 while (1) {
3814 int idx = -1, i, seen_control = 0, last_notdel_data_fd = -1;
3815
3816 health_code_update();
3817
3818 /* Infinite blocking call, waiting for transmission */
3819 DBG3("Relayd worker thread polling...");
3820 health_poll_entry();
3821 ret = lttng_poll_wait(&events, -1);
3822 health_poll_exit();
3823 if (ret < 0) {
3824 /*
3825 * Restart interrupted system call.
3826 */
3827 if (errno == EINTR) {
3828 goto restart;
3829 }
3830 goto error;
3831 }
3832
3833 nb_fd = ret;
3834
3835 /*
3836 * Process control. The control connection is
3837 * prioritized so we don't starve it with high
3838 * throughput tracing data on the data connection.
3839 */
3840 for (i = 0; i < nb_fd; i++) {
3841 /* Fetch once the poll data */
3842 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
3843 int pollfd = LTTNG_POLL_GETFD(&events, i);
3844
3845 health_code_update();
3846
3847 if (!revents) {
3848 /*
3849 * No activity for this FD (poll
3850 * implementation).
3851 */
3852 continue;
3853 }
3854
3855 /* Thread quit pipe has been closed. Killing thread. */
3856 ret = check_thread_quit_pipe(pollfd, revents);
3857 if (ret) {
3858 err = 0;
3859 goto exit;
3860 }
3861
3862 /* Inspect the relay conn pipe for new connection */
3863 if (pollfd == relay_conn_pipe[0]) {
3864 if (revents & LPOLLIN) {
3865 struct relay_connection *conn;
3866
3867 ret = lttng_read(relay_conn_pipe[0], &conn, sizeof(conn));
3868 if (ret < 0) {
3869 goto error;
3870 }
3871 lttng_poll_add(&events, conn->sock->fd,
3872 LPOLLIN | LPOLLRDHUP);
3873 connection_ht_add(relay_connections_ht, conn);
3874 DBG("Connection socket %d added", conn->sock->fd);
3875 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
3876 ERR("Relay connection pipe error");
3877 goto error;
3878 } else {
3879 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
3880 goto error;
3881 }
3882 } else {
3883 struct relay_connection *ctrl_conn;
3884
3885 ctrl_conn = connection_get_by_sock(relay_connections_ht, pollfd);
3886 /* If not found, there is a synchronization issue. */
3887 assert(ctrl_conn);
3888
3889 if (ctrl_conn->type == RELAY_DATA) {
3890 if (revents & LPOLLIN) {
3891 /*
3892 * Flag the last seen data fd not deleted. It will be
3893 * used as the last seen fd if any fd gets deleted in
3894 * this first loop.
3895 */
3896 last_notdel_data_fd = pollfd;
3897 }
3898 goto put_ctrl_connection;
3899 }
3900 assert(ctrl_conn->type == RELAY_CONTROL);
3901
3902 if (revents & LPOLLIN) {
3903 enum relay_connection_status status;
3904
3905 status = relay_process_control(ctrl_conn);
3906 if (status != RELAY_CONNECTION_STATUS_OK) {
3907 /*
3908 * On socket error flag the session as aborted to force
3909 * the cleanup of its stream otherwise it can leak
3910 * during the lifetime of the relayd.
3911 *
3912 * This prevents situations in which streams can be
3913 * left opened because an index was received, the
3914 * control connection is closed, and the data
3915 * connection is closed (uncleanly) before the packet's
3916 * data provided.
3917 *
3918 * Since the control connection encountered an error,
3919 * it is okay to be conservative and close the
3920 * session right now as we can't rely on the protocol
3921 * being respected anymore.
3922 */
3923 if (status == RELAY_CONNECTION_STATUS_ERROR) {
3924 session_abort(ctrl_conn->session);
3925 }
3926
3927 /* Clear the connection on error or close. */
3928 relay_thread_close_connection(&events,
3929 pollfd,
3930 ctrl_conn);
3931 }
3932 seen_control = 1;
3933 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
3934 relay_thread_close_connection(&events,
3935 pollfd, ctrl_conn);
3936 if (last_seen_data_fd == pollfd) {
3937 last_seen_data_fd = last_notdel_data_fd;
3938 }
3939 } else {
3940 ERR("Unexpected poll events %u for control sock %d",
3941 revents, pollfd);
3942 connection_put(ctrl_conn);
3943 goto error;
3944 }
3945 put_ctrl_connection:
3946 connection_put(ctrl_conn);
3947 }
3948 }
3949
3950 /*
3951 * The last loop handled a control request, go back to poll to make
3952 * sure we prioritise the control socket.
3953 */
3954 if (seen_control) {
3955 continue;
3956 }
3957
3958 if (last_seen_data_fd >= 0) {
3959 for (i = 0; i < nb_fd; i++) {
3960 int pollfd = LTTNG_POLL_GETFD(&events, i);
3961
3962 health_code_update();
3963
3964 if (last_seen_data_fd == pollfd) {
3965 idx = i;
3966 break;
3967 }
3968 }
3969 }
3970
3971 /* Process data connection. */
3972 for (i = idx + 1; i < nb_fd; i++) {
3973 /* Fetch the poll data. */
3974 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
3975 int pollfd = LTTNG_POLL_GETFD(&events, i);
3976 struct relay_connection *data_conn;
3977
3978 health_code_update();
3979
3980 if (!revents) {
3981 /* No activity for this FD (poll implementation). */
3982 continue;
3983 }
3984
3985 /* Skip the command pipe. It's handled in the first loop. */
3986 if (pollfd == relay_conn_pipe[0]) {
3987 continue;
3988 }
3989
3990 data_conn = connection_get_by_sock(relay_connections_ht, pollfd);
3991 if (!data_conn) {
3992 /* Skip it. Might be removed before. */
3993 continue;
3994 }
3995 if (data_conn->type == RELAY_CONTROL) {
3996 goto put_data_connection;
3997 }
3998 assert(data_conn->type == RELAY_DATA);
3999
4000 if (revents & LPOLLIN) {
4001 enum relay_connection_status status;
4002
4003 status = relay_process_data(data_conn);
4004 /* Connection closed or error. */
4005 if (status != RELAY_CONNECTION_STATUS_OK) {
4006 /*
4007 * On socket error flag the session as aborted to force
4008 * the cleanup of its stream otherwise it can leak
4009 * during the lifetime of the relayd.
4010 *
4011 * This prevents situations in which streams can be
4012 * left opened because an index was received, the
4013 * control connection is closed, and the data
4014 * connection is closed (uncleanly) before the packet's
4015 * data provided.
4016 *
4017 * Since the data connection encountered an error,
4018 * it is okay to be conservative and close the
4019 * session right now as we can't rely on the protocol
4020 * being respected anymore.
4021 */
4022 if (status == RELAY_CONNECTION_STATUS_ERROR) {
4023 session_abort(data_conn->session);
4024 }
4025 relay_thread_close_connection(&events, pollfd,
4026 data_conn);
4027 /*
4028 * Every goto restart call sets the last seen fd where
4029 * here we don't really care since we gracefully
4030 * continue the loop after the connection is deleted.
4031 */
4032 } else {
4033 /* Keep last seen port. */
4034 last_seen_data_fd = pollfd;
4035 connection_put(data_conn);
4036 goto restart;
4037 }
4038 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
4039 relay_thread_close_connection(&events, pollfd,
4040 data_conn);
4041 } else {
4042 ERR("Unknown poll events %u for data sock %d",
4043 revents, pollfd);
4044 }
4045 put_data_connection:
4046 connection_put(data_conn);
4047 }
4048 last_seen_data_fd = -1;
4049 }
4050
4051 /* Normal exit, no error */
4052 ret = 0;
4053
4054 exit:
4055 error:
4056 /* Cleanup remaining connection object. */
4057 rcu_read_lock();
4058 cds_lfht_for_each_entry(relay_connections_ht->ht, &iter.iter,
4059 destroy_conn,
4060 sock_n.node) {
4061 health_code_update();
4062
4063 session_abort(destroy_conn->session);
4064
4065 /*
4066 * No need to grab another ref, because we own
4067 * destroy_conn.
4068 */
4069 relay_thread_close_connection(&events, destroy_conn->sock->fd,
4070 destroy_conn);
4071 }
4072 rcu_read_unlock();
4073
4074 (void) fd_tracker_util_poll_clean(the_fd_tracker, &events);
4075 error_poll_create:
4076 lttng_ht_destroy(relay_connections_ht);
4077 relay_connections_ht_error:
4078 /* Close relay conn pipes */
4079 (void) fd_tracker_util_pipe_close(the_fd_tracker,
4080 relay_conn_pipe);
4081 if (err) {
4082 DBG("Thread exited with error");
4083 }
4084 DBG("Worker thread cleanup complete");
4085 error_testpoint:
4086 if (err) {
4087 health_error();
4088 ERR("Health error occurred in %s", __func__);
4089 }
4090 health_unregister(health_relayd);
4091 rcu_unregister_thread();
4092 lttng_relay_stop_threads();
4093 return NULL;
4094 }
4095
4096 /*
4097 * Create the relay command pipe to wake thread_manage_apps.
4098 * Closed in cleanup().
4099 */
4100 static int create_relay_conn_pipe(void)
4101 {
4102 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker,
4103 "Relayd connection pipe", relay_conn_pipe);
4104 }
4105
4106 static
4107 int stdio_open(void *data, int *fds)
4108 {
4109 fds[0] = fileno(stdout);
4110 fds[1] = fileno(stderr);
4111 return 0;
4112 }
4113
4114 static
4115 int noop_close(void *data, int *fds)
4116 {
4117 return 0;
4118 }
4119
4120 static
4121 int track_stdio(void)
4122 {
4123 int fds[2];
4124 const char *names[] = { "stdout", "stderr" };
4125
4126 return fd_tracker_open_unsuspendable_fd(the_fd_tracker, fds,
4127 names, 2, stdio_open, NULL);
4128 }
4129
4130 static
4131 void untrack_stdio(void)
4132 {
4133 int fds[] = { fileno(stdout), fileno(stderr) };
4134
4135 /*
4136 * noop_close is used since we don't really want to close
4137 * the stdio output fds; we merely want to stop tracking them.
4138 */
4139 (void) fd_tracker_close_unsuspendable_fd(the_fd_tracker,
4140 fds, 2, noop_close, NULL);
4141 }
4142
4143 /*
4144 * main
4145 */
4146 int main(int argc, char **argv)
4147 {
4148 int ret = 0, retval = 0;
4149 void *status;
4150
4151 /* Parse arguments */
4152 progname = argv[0];
4153 if (set_options(argc, argv)) {
4154 retval = -1;
4155 goto exit_options;
4156 }
4157
4158 if (set_signal_handler()) {
4159 retval = -1;
4160 goto exit_options;
4161 }
4162
4163 ret = fclose(stdin);
4164 if (ret) {
4165 PERROR("Failed to close stdin");
4166 goto exit_options;
4167 }
4168 /* Try to create directory if -o, --output is specified. */
4169 if (opt_output_path) {
4170 if (*opt_output_path != '/') {
4171 ERR("Please specify an absolute path for -o, --output PATH");
4172 retval = -1;
4173 goto exit_options;
4174 }
4175
4176 ret = utils_mkdir_recursive(opt_output_path, S_IRWXU | S_IRWXG,
4177 -1, -1);
4178 if (ret < 0) {
4179 ERR("Unable to create %s", opt_output_path);
4180 retval = -1;
4181 goto exit_options;
4182 }
4183 }
4184
4185 /* Daemonize */
4186 if (opt_daemon || opt_background) {
4187 ret = lttng_daemonize(&child_ppid, &recv_child_signal,
4188 !opt_background);
4189 if (ret < 0) {
4190 retval = -1;
4191 goto exit_options;
4192 }
4193 }
4194
4195 /*
4196 * The RCU thread registration (and use, through the fd-tracker's
4197 * creation) is done after the daemonization to allow us to not
4198 * deal with liburcu's fork() management as the call RCU needs to
4199 * be restored.
4200 */
4201 rcu_register_thread();
4202
4203 the_fd_tracker = fd_tracker_create(lttng_opt_fd_pool_size);
4204 if (!the_fd_tracker) {
4205 retval = -1;
4206 goto exit_options;
4207 }
4208
4209 ret = track_stdio();
4210 if (ret) {
4211 retval = -1;
4212 goto exit_tracker;
4213 }
4214
4215 /* Initialize thread health monitoring */
4216 health_relayd = health_app_create(NR_HEALTH_RELAYD_TYPES);
4217 if (!health_relayd) {
4218 PERROR("health_app_create error");
4219 retval = -1;
4220 goto exit_health_app_create;
4221 }
4222
4223 /* Create thread quit pipe */
4224 if (init_thread_quit_pipe()) {
4225 retval = -1;
4226 goto exit_init_data;
4227 }
4228
4229 /* Setup the thread apps communication pipe. */
4230 if (create_relay_conn_pipe()) {
4231 retval = -1;
4232 goto exit_init_data;
4233 }
4234
4235 /* Init relay command queue. */
4236 cds_wfcq_init(&relay_conn_queue.head, &relay_conn_queue.tail);
4237
4238 /* Initialize communication library */
4239 lttcomm_init();
4240 lttcomm_inet_init();
4241
4242 /* tables of sessions indexed by session ID */
4243 sessions_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
4244 if (!sessions_ht) {
4245 retval = -1;
4246 goto exit_init_data;
4247 }
4248
4249 /* tables of streams indexed by stream ID */
4250 relay_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
4251 if (!relay_streams_ht) {
4252 retval = -1;
4253 goto exit_init_data;
4254 }
4255
4256 /* tables of streams indexed by stream ID */
4257 viewer_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
4258 if (!viewer_streams_ht) {
4259 retval = -1;
4260 goto exit_init_data;
4261 }
4262
4263 ret = init_health_quit_pipe();
4264 if (ret) {
4265 retval = -1;
4266 goto exit_health_quit_pipe;
4267 }
4268
4269 /* Create thread to manage the client socket */
4270 ret = pthread_create(&health_thread, default_pthread_attr(),
4271 thread_manage_health, (void *) NULL);
4272 if (ret) {
4273 errno = ret;
4274 PERROR("pthread_create health");
4275 retval = -1;
4276 goto exit_health_thread;
4277 }
4278
4279 /* Setup the dispatcher thread */
4280 ret = pthread_create(&dispatcher_thread, default_pthread_attr(),
4281 relay_thread_dispatcher, (void *) NULL);
4282 if (ret) {
4283 errno = ret;
4284 PERROR("pthread_create dispatcher");
4285 retval = -1;
4286 goto exit_dispatcher_thread;
4287 }
4288
4289 /* Setup the worker thread */
4290 ret = pthread_create(&worker_thread, default_pthread_attr(),
4291 relay_thread_worker, NULL);
4292 if (ret) {
4293 errno = ret;
4294 PERROR("pthread_create worker");
4295 retval = -1;
4296 goto exit_worker_thread;
4297 }
4298
4299 /* Setup the listener thread */
4300 ret = pthread_create(&listener_thread, default_pthread_attr(),
4301 relay_thread_listener, (void *) NULL);
4302 if (ret) {
4303 errno = ret;
4304 PERROR("pthread_create listener");
4305 retval = -1;
4306 goto exit_listener_thread;
4307 }
4308
4309 ret = relayd_live_create(live_uri);
4310 if (ret) {
4311 ERR("Starting live viewer threads");
4312 retval = -1;
4313 goto exit_live;
4314 }
4315
4316 /*
4317 * This is where we start awaiting program completion (e.g. through
4318 * signal that asks threads to teardown).
4319 */
4320
4321 ret = relayd_live_join();
4322 if (ret) {
4323 retval = -1;
4324 }
4325 exit_live:
4326
4327 ret = pthread_join(listener_thread, &status);
4328 if (ret) {
4329 errno = ret;
4330 PERROR("pthread_join listener_thread");
4331 retval = -1;
4332 }
4333
4334 exit_listener_thread:
4335 ret = pthread_join(worker_thread, &status);
4336 if (ret) {
4337 errno = ret;
4338 PERROR("pthread_join worker_thread");
4339 retval = -1;
4340 }
4341
4342 exit_worker_thread:
4343 ret = pthread_join(dispatcher_thread, &status);
4344 if (ret) {
4345 errno = ret;
4346 PERROR("pthread_join dispatcher_thread");
4347 retval = -1;
4348 }
4349 exit_dispatcher_thread:
4350
4351 ret = pthread_join(health_thread, &status);
4352 if (ret) {
4353 errno = ret;
4354 PERROR("pthread_join health_thread");
4355 retval = -1;
4356 }
4357 exit_health_thread:
4358
4359 (void) fd_tracker_util_pipe_close(the_fd_tracker, health_quit_pipe);
4360 exit_health_quit_pipe:
4361
4362 exit_init_data:
4363 health_app_destroy(health_relayd);
4364 exit_health_app_create:
4365
4366 /*
4367 * Wait for all pending call_rcu work to complete before tearing
4368 * down data structures. call_rcu worker may be trying to
4369 * perform lookups in those structures.
4370 */
4371 rcu_barrier();
4372 relayd_cleanup();
4373
4374 /* Ensure all prior call_rcu are done. */
4375 rcu_barrier();
4376 exit_tracker:
4377 untrack_stdio();
4378 /*
4379 * fd_tracker_destroy() will log the contents of the fd-tracker
4380 * if a leak is detected.
4381 */
4382 fd_tracker_destroy(the_fd_tracker);
4383 rcu_unregister_thread();
4384 exit_options:
4385 if (!retval) {
4386 exit(EXIT_SUCCESS);
4387 } else {
4388 exit(EXIT_FAILURE);
4389 }
4390 }
This page took 0.113617 seconds and 4 git commands to generate.