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