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