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