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