Don't allow slashes and dots in overriden trace chunk names
[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 <inttypes.h>
38 #include <urcu/futex.h>
39 #include <urcu/uatomic.h>
40 #include <unistd.h>
41 #include <fcntl.h>
42
43 #include <lttng/lttng.h>
44 #include <common/common.h>
45 #include <common/compat/poll.h>
46 #include <common/compat/socket.h>
47 #include <common/compat/endian.h>
48 #include <common/compat/getenv.h>
49 #include <common/defaults.h>
50 #include <common/daemonize.h>
51 #include <common/futex.h>
52 #include <common/sessiond-comm/sessiond-comm.h>
53 #include <common/sessiond-comm/inet.h>
54 #include <common/sessiond-comm/relayd.h>
55 #include <common/uri.h>
56 #include <common/utils.h>
57 #include <common/align.h>
58 #include <common/config/session-config.h>
59 #include <common/dynamic-buffer.h>
60 #include <common/buffer-view.h>
61 #include <urcu/rculist.h>
62
63 #include "cmd.h"
64 #include "ctf-trace.h"
65 #include "index.h"
66 #include "utils.h"
67 #include "lttng-relayd.h"
68 #include "live.h"
69 #include "health-relayd.h"
70 #include "testpoint.h"
71 #include "viewer-stream.h"
72 #include "session.h"
73 #include "stream.h"
74 #include "connection.h"
75 #include "tracefile-array.h"
76 #include "tcp_keep_alive.h"
77 #include "sessiond-trace-chunks.h"
78
79 static const char *help_msg =
80 #ifdef LTTNG_EMBED_HELP
81 #include <lttng-relayd.8.h>
82 #else
83 NULL
84 #endif
85 ;
86
87 enum relay_connection_status {
88 RELAY_CONNECTION_STATUS_OK,
89 /* An error occurred while processing an event on the connection. */
90 RELAY_CONNECTION_STATUS_ERROR,
91 /* Connection closed/shutdown cleanly. */
92 RELAY_CONNECTION_STATUS_CLOSED,
93 };
94
95 /* command line options */
96 char *opt_output_path;
97 static int opt_daemon, opt_background;
98
99 /*
100 * We need to wait for listener and live listener threads, as well as
101 * health check thread, before being ready to signal readiness.
102 */
103 #define NR_LTTNG_RELAY_READY 3
104 static int lttng_relay_ready = NR_LTTNG_RELAY_READY;
105
106 /* Size of receive buffer. */
107 #define RECV_DATA_BUFFER_SIZE 65536
108 #define FILE_COPY_BUFFER_SIZE 65536
109
110 static int recv_child_signal; /* Set to 1 when a SIGUSR1 signal is received. */
111 static pid_t child_ppid; /* Internal parent PID use with daemonize. */
112
113 static struct lttng_uri *control_uri;
114 static struct lttng_uri *data_uri;
115 static struct lttng_uri *live_uri;
116
117 const char *progname;
118
119 const char *tracing_group_name = DEFAULT_TRACING_GROUP;
120 static int tracing_group_name_override;
121
122 const char * const config_section_name = "relayd";
123
124 /*
125 * Quit pipe for all threads. This permits a single cancellation point
126 * for all threads when receiving an event on the pipe.
127 */
128 int thread_quit_pipe[2] = { -1, -1 };
129
130 /*
131 * This pipe is used to inform the worker thread that a command is queued and
132 * ready to be processed.
133 */
134 static int relay_conn_pipe[2] = { -1, -1 };
135
136 /* Shared between threads */
137 static int dispatch_thread_exit;
138
139 static pthread_t listener_thread;
140 static pthread_t dispatcher_thread;
141 static pthread_t worker_thread;
142 static pthread_t health_thread;
143
144 /*
145 * last_relay_stream_id_lock protects last_relay_stream_id increment
146 * atomicity on 32-bit architectures.
147 */
148 static pthread_mutex_t last_relay_stream_id_lock = PTHREAD_MUTEX_INITIALIZER;
149 static uint64_t last_relay_stream_id;
150
151 /*
152 * Relay command queue.
153 *
154 * The relay_thread_listener and relay_thread_dispatcher communicate with this
155 * queue.
156 */
157 static struct relay_conn_queue relay_conn_queue;
158
159 /* Global relay stream hash table. */
160 struct lttng_ht *relay_streams_ht;
161
162 /* Global relay viewer stream hash table. */
163 struct lttng_ht *viewer_streams_ht;
164
165 /* Global relay sessions hash table. */
166 struct lttng_ht *sessions_ht;
167
168 /* Relayd health monitoring */
169 struct health_app *health_relayd;
170
171 struct sessiond_trace_chunk_registry *sessiond_trace_chunk_registry;
172
173 static struct option long_options[] = {
174 { "control-port", 1, 0, 'C', },
175 { "data-port", 1, 0, 'D', },
176 { "live-port", 1, 0, 'L', },
177 { "daemonize", 0, 0, 'd', },
178 { "background", 0, 0, 'b', },
179 { "group", 1, 0, 'g', },
180 { "help", 0, 0, 'h', },
181 { "output", 1, 0, 'o', },
182 { "verbose", 0, 0, 'v', },
183 { "config", 1, 0, 'f' },
184 { "version", 0, 0, 'V' },
185 { NULL, 0, 0, 0, },
186 };
187
188 static const char *config_ignore_options[] = { "help", "config", "version" };
189
190 /*
191 * Take an option from the getopt output and set it in the right variable to be
192 * used later.
193 *
194 * Return 0 on success else a negative value.
195 */
196 static int set_option(int opt, const char *arg, const char *optname)
197 {
198 int ret;
199
200 switch (opt) {
201 case 0:
202 fprintf(stderr, "option %s", optname);
203 if (arg) {
204 fprintf(stderr, " with arg %s\n", arg);
205 }
206 break;
207 case 'C':
208 if (lttng_is_setuid_setgid()) {
209 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
210 "-C, --control-port");
211 } else {
212 ret = uri_parse(arg, &control_uri);
213 if (ret < 0) {
214 ERR("Invalid control URI specified");
215 goto end;
216 }
217 if (control_uri->port == 0) {
218 control_uri->port = DEFAULT_NETWORK_CONTROL_PORT;
219 }
220 }
221 break;
222 case 'D':
223 if (lttng_is_setuid_setgid()) {
224 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
225 "-D, -data-port");
226 } else {
227 ret = uri_parse(arg, &data_uri);
228 if (ret < 0) {
229 ERR("Invalid data URI specified");
230 goto end;
231 }
232 if (data_uri->port == 0) {
233 data_uri->port = DEFAULT_NETWORK_DATA_PORT;
234 }
235 }
236 break;
237 case 'L':
238 if (lttng_is_setuid_setgid()) {
239 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
240 "-L, -live-port");
241 } else {
242 ret = uri_parse(arg, &live_uri);
243 if (ret < 0) {
244 ERR("Invalid live URI specified");
245 goto end;
246 }
247 if (live_uri->port == 0) {
248 live_uri->port = DEFAULT_NETWORK_VIEWER_PORT;
249 }
250 }
251 break;
252 case 'd':
253 opt_daemon = 1;
254 break;
255 case 'b':
256 opt_background = 1;
257 break;
258 case 'g':
259 if (lttng_is_setuid_setgid()) {
260 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
261 "-g, --group");
262 } else {
263 tracing_group_name = strdup(arg);
264 if (tracing_group_name == NULL) {
265 ret = -errno;
266 PERROR("strdup");
267 goto end;
268 }
269 tracing_group_name_override = 1;
270 }
271 break;
272 case 'h':
273 ret = utils_show_help(8, "lttng-relayd", help_msg);
274 if (ret) {
275 ERR("Cannot show --help for `lttng-relayd`");
276 perror("exec");
277 }
278 exit(EXIT_FAILURE);
279 case 'V':
280 fprintf(stdout, "%s\n", VERSION);
281 exit(EXIT_SUCCESS);
282 case 'o':
283 if (lttng_is_setuid_setgid()) {
284 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
285 "-o, --output");
286 } else {
287 ret = asprintf(&opt_output_path, "%s", arg);
288 if (ret < 0) {
289 ret = -errno;
290 PERROR("asprintf opt_output_path");
291 goto end;
292 }
293 }
294 break;
295 case 'v':
296 /* Verbose level can increase using multiple -v */
297 if (arg) {
298 lttng_opt_verbose = config_parse_value(arg);
299 } else {
300 /* Only 3 level of verbosity (-vvv). */
301 if (lttng_opt_verbose < 3) {
302 lttng_opt_verbose += 1;
303 }
304 }
305 break;
306 default:
307 /* Unknown option or other error.
308 * Error is printed by getopt, just return */
309 ret = -1;
310 goto end;
311 }
312
313 /* All good. */
314 ret = 0;
315
316 end:
317 return ret;
318 }
319
320 /*
321 * config_entry_handler_cb used to handle options read from a config file.
322 * See config_entry_handler_cb comment in common/config/session-config.h for the
323 * return value conventions.
324 */
325 static int config_entry_handler(const struct config_entry *entry, void *unused)
326 {
327 int ret = 0, i;
328
329 if (!entry || !entry->name || !entry->value) {
330 ret = -EINVAL;
331 goto end;
332 }
333
334 /* Check if the option is to be ignored */
335 for (i = 0; i < sizeof(config_ignore_options) / sizeof(char *); i++) {
336 if (!strcmp(entry->name, config_ignore_options[i])) {
337 goto end;
338 }
339 }
340
341 for (i = 0; i < (sizeof(long_options) / sizeof(struct option)) - 1; i++) {
342 /* Ignore if entry name is not fully matched. */
343 if (strcmp(entry->name, long_options[i].name)) {
344 continue;
345 }
346
347 /*
348 * If the option takes no argument on the command line,
349 * we have to check if the value is "true". We support
350 * non-zero numeric values, true, on and yes.
351 */
352 if (!long_options[i].has_arg) {
353 ret = config_parse_value(entry->value);
354 if (ret <= 0) {
355 if (ret) {
356 WARN("Invalid configuration value \"%s\" for option %s",
357 entry->value, entry->name);
358 }
359 /* False, skip boolean config option. */
360 goto end;
361 }
362 }
363
364 ret = set_option(long_options[i].val, entry->value, entry->name);
365 goto end;
366 }
367
368 WARN("Unrecognized option \"%s\" in daemon configuration file.",
369 entry->name);
370
371 end:
372 return ret;
373 }
374
375 static int set_options(int argc, char **argv)
376 {
377 int c, ret = 0, option_index = 0, retval = 0;
378 int orig_optopt = optopt, orig_optind = optind;
379 char *default_address, *optstring;
380 const char *config_path = NULL;
381
382 optstring = utils_generate_optstring(long_options,
383 sizeof(long_options) / sizeof(struct option));
384 if (!optstring) {
385 retval = -ENOMEM;
386 goto exit;
387 }
388
389 /* Check for the --config option */
390
391 while ((c = getopt_long(argc, argv, optstring, long_options,
392 &option_index)) != -1) {
393 if (c == '?') {
394 retval = -EINVAL;
395 goto exit;
396 } else if (c != 'f') {
397 continue;
398 }
399
400 if (lttng_is_setuid_setgid()) {
401 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
402 "-f, --config");
403 } else {
404 config_path = utils_expand_path(optarg);
405 if (!config_path) {
406 ERR("Failed to resolve path: %s", optarg);
407 }
408 }
409 }
410
411 ret = config_get_section_entries(config_path, config_section_name,
412 config_entry_handler, NULL);
413 if (ret) {
414 if (ret > 0) {
415 ERR("Invalid configuration option at line %i", ret);
416 }
417 retval = -1;
418 goto exit;
419 }
420
421 /* Reset getopt's global state */
422 optopt = orig_optopt;
423 optind = orig_optind;
424 while (1) {
425 c = getopt_long(argc, argv, optstring, long_options, &option_index);
426 if (c == -1) {
427 break;
428 }
429
430 ret = set_option(c, optarg, long_options[option_index].name);
431 if (ret < 0) {
432 retval = -1;
433 goto exit;
434 }
435 }
436
437 /* assign default values */
438 if (control_uri == NULL) {
439 ret = asprintf(&default_address,
440 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS ":%d",
441 DEFAULT_NETWORK_CONTROL_PORT);
442 if (ret < 0) {
443 PERROR("asprintf default data address");
444 retval = -1;
445 goto exit;
446 }
447
448 ret = uri_parse(default_address, &control_uri);
449 free(default_address);
450 if (ret < 0) {
451 ERR("Invalid control URI specified");
452 retval = -1;
453 goto exit;
454 }
455 }
456 if (data_uri == NULL) {
457 ret = asprintf(&default_address,
458 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS ":%d",
459 DEFAULT_NETWORK_DATA_PORT);
460 if (ret < 0) {
461 PERROR("asprintf default data address");
462 retval = -1;
463 goto exit;
464 }
465
466 ret = uri_parse(default_address, &data_uri);
467 free(default_address);
468 if (ret < 0) {
469 ERR("Invalid data URI specified");
470 retval = -1;
471 goto exit;
472 }
473 }
474 if (live_uri == NULL) {
475 ret = asprintf(&default_address,
476 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS ":%d",
477 DEFAULT_NETWORK_VIEWER_PORT);
478 if (ret < 0) {
479 PERROR("asprintf default viewer control address");
480 retval = -1;
481 goto exit;
482 }
483
484 ret = uri_parse(default_address, &live_uri);
485 free(default_address);
486 if (ret < 0) {
487 ERR("Invalid viewer control URI specified");
488 retval = -1;
489 goto exit;
490 }
491 }
492
493 exit:
494 free(optstring);
495 return retval;
496 }
497
498 static void print_global_objects(void)
499 {
500 rcu_register_thread();
501
502 print_viewer_streams();
503 print_relay_streams();
504 print_sessions();
505
506 rcu_unregister_thread();
507 }
508
509 /*
510 * Cleanup the daemon
511 */
512 static void relayd_cleanup(void)
513 {
514 print_global_objects();
515
516 DBG("Cleaning up");
517
518 if (viewer_streams_ht)
519 lttng_ht_destroy(viewer_streams_ht);
520 if (relay_streams_ht)
521 lttng_ht_destroy(relay_streams_ht);
522 if (sessions_ht)
523 lttng_ht_destroy(sessions_ht);
524
525 /* free the dynamically allocated opt_output_path */
526 free(opt_output_path);
527
528 /* Close thread quit pipes */
529 utils_close_pipe(thread_quit_pipe);
530
531 uri_free(control_uri);
532 uri_free(data_uri);
533 /* Live URI is freed in the live thread. */
534
535 if (tracing_group_name_override) {
536 free((void *) tracing_group_name);
537 }
538 }
539
540 /*
541 * Write to writable pipe used to notify a thread.
542 */
543 static int notify_thread_pipe(int wpipe)
544 {
545 ssize_t ret;
546
547 ret = lttng_write(wpipe, "!", 1);
548 if (ret < 1) {
549 PERROR("write poll pipe");
550 goto end;
551 }
552 ret = 0;
553 end:
554 return ret;
555 }
556
557 static int notify_health_quit_pipe(int *pipe)
558 {
559 ssize_t ret;
560
561 ret = lttng_write(pipe[1], "4", 1);
562 if (ret < 1) {
563 PERROR("write relay health quit");
564 goto end;
565 }
566 ret = 0;
567 end:
568 return ret;
569 }
570
571 /*
572 * Stop all relayd and relayd-live threads.
573 */
574 int lttng_relay_stop_threads(void)
575 {
576 int retval = 0;
577
578 /* Stopping all threads */
579 DBG("Terminating all threads");
580 if (notify_thread_pipe(thread_quit_pipe[1])) {
581 ERR("write error on thread quit pipe");
582 retval = -1;
583 }
584
585 if (notify_health_quit_pipe(health_quit_pipe)) {
586 ERR("write error on health quit pipe");
587 }
588
589 /* Dispatch thread */
590 CMM_STORE_SHARED(dispatch_thread_exit, 1);
591 futex_nto1_wake(&relay_conn_queue.futex);
592
593 if (relayd_live_stop()) {
594 ERR("Error stopping live threads");
595 retval = -1;
596 }
597 return retval;
598 }
599
600 /*
601 * Signal handler for the daemon
602 *
603 * Simply stop all worker threads, leaving main() return gracefully after
604 * joining all threads and calling cleanup().
605 */
606 static void sighandler(int sig)
607 {
608 switch (sig) {
609 case SIGINT:
610 DBG("SIGINT caught");
611 if (lttng_relay_stop_threads()) {
612 ERR("Error stopping threads");
613 }
614 break;
615 case SIGTERM:
616 DBG("SIGTERM caught");
617 if (lttng_relay_stop_threads()) {
618 ERR("Error stopping threads");
619 }
620 break;
621 case SIGUSR1:
622 CMM_STORE_SHARED(recv_child_signal, 1);
623 break;
624 default:
625 break;
626 }
627 }
628
629 /*
630 * Setup signal handler for :
631 * SIGINT, SIGTERM, SIGPIPE
632 */
633 static int set_signal_handler(void)
634 {
635 int ret = 0;
636 struct sigaction sa;
637 sigset_t sigset;
638
639 if ((ret = sigemptyset(&sigset)) < 0) {
640 PERROR("sigemptyset");
641 return ret;
642 }
643
644 sa.sa_mask = sigset;
645 sa.sa_flags = 0;
646
647 sa.sa_handler = sighandler;
648 if ((ret = sigaction(SIGTERM, &sa, NULL)) < 0) {
649 PERROR("sigaction");
650 return ret;
651 }
652
653 if ((ret = sigaction(SIGINT, &sa, NULL)) < 0) {
654 PERROR("sigaction");
655 return ret;
656 }
657
658 if ((ret = sigaction(SIGUSR1, &sa, NULL)) < 0) {
659 PERROR("sigaction");
660 return ret;
661 }
662
663 sa.sa_handler = SIG_IGN;
664 if ((ret = sigaction(SIGPIPE, &sa, NULL)) < 0) {
665 PERROR("sigaction");
666 return ret;
667 }
668
669 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
670
671 return ret;
672 }
673
674 void lttng_relay_notify_ready(void)
675 {
676 /* Notify the parent of the fork() process that we are ready. */
677 if (opt_daemon || opt_background) {
678 if (uatomic_sub_return(&lttng_relay_ready, 1) == 0) {
679 kill(child_ppid, SIGUSR1);
680 }
681 }
682 }
683
684 /*
685 * Init thread quit pipe.
686 *
687 * Return -1 on error or 0 if all pipes are created.
688 */
689 static int init_thread_quit_pipe(void)
690 {
691 int ret;
692
693 ret = utils_create_pipe_cloexec(thread_quit_pipe);
694
695 return ret;
696 }
697
698 /*
699 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
700 */
701 static int create_thread_poll_set(struct lttng_poll_event *events, int size)
702 {
703 int ret;
704
705 if (events == NULL || size == 0) {
706 ret = -1;
707 goto error;
708 }
709
710 ret = lttng_poll_create(events, size, LTTNG_CLOEXEC);
711 if (ret < 0) {
712 goto error;
713 }
714
715 /* Add quit pipe */
716 ret = lttng_poll_add(events, thread_quit_pipe[0], LPOLLIN | LPOLLERR);
717 if (ret < 0) {
718 goto error;
719 }
720
721 return 0;
722
723 error:
724 return ret;
725 }
726
727 /*
728 * Check if the thread quit pipe was triggered.
729 *
730 * Return 1 if it was triggered else 0;
731 */
732 static int check_thread_quit_pipe(int fd, uint32_t events)
733 {
734 if (fd == thread_quit_pipe[0] && (events & LPOLLIN)) {
735 return 1;
736 }
737
738 return 0;
739 }
740
741 /*
742 * Create and init socket from uri.
743 */
744 static struct lttcomm_sock *relay_socket_create(struct lttng_uri *uri)
745 {
746 int ret;
747 struct lttcomm_sock *sock = NULL;
748
749 sock = lttcomm_alloc_sock_from_uri(uri);
750 if (sock == NULL) {
751 ERR("Allocating socket");
752 goto error;
753 }
754
755 ret = lttcomm_create_sock(sock);
756 if (ret < 0) {
757 goto error;
758 }
759 DBG("Listening on sock %d", sock->fd);
760
761 ret = sock->ops->bind(sock);
762 if (ret < 0) {
763 PERROR("Failed to bind socket");
764 goto error;
765 }
766
767 ret = sock->ops->listen(sock, -1);
768 if (ret < 0) {
769 goto error;
770
771 }
772
773 return sock;
774
775 error:
776 if (sock) {
777 lttcomm_destroy_sock(sock);
778 }
779 return NULL;
780 }
781
782 /*
783 * This thread manages the listening for new connections on the network
784 */
785 static void *relay_thread_listener(void *data)
786 {
787 int i, ret, pollfd, err = -1;
788 uint32_t revents, nb_fd;
789 struct lttng_poll_event events;
790 struct lttcomm_sock *control_sock, *data_sock;
791
792 DBG("[thread] Relay listener started");
793
794 health_register(health_relayd, HEALTH_RELAYD_TYPE_LISTENER);
795
796 health_code_update();
797
798 control_sock = relay_socket_create(control_uri);
799 if (!control_sock) {
800 goto error_sock_control;
801 }
802
803 data_sock = relay_socket_create(data_uri);
804 if (!data_sock) {
805 goto error_sock_relay;
806 }
807
808 /*
809 * Pass 3 as size here for the thread quit pipe, control and
810 * data socket.
811 */
812 ret = create_thread_poll_set(&events, 3);
813 if (ret < 0) {
814 goto error_create_poll;
815 }
816
817 /* Add the control socket */
818 ret = lttng_poll_add(&events, control_sock->fd, LPOLLIN | LPOLLRDHUP);
819 if (ret < 0) {
820 goto error_poll_add;
821 }
822
823 /* Add the data socket */
824 ret = lttng_poll_add(&events, data_sock->fd, LPOLLIN | LPOLLRDHUP);
825 if (ret < 0) {
826 goto error_poll_add;
827 }
828
829 lttng_relay_notify_ready();
830
831 if (testpoint(relayd_thread_listener)) {
832 goto error_testpoint;
833 }
834
835 while (1) {
836 health_code_update();
837
838 DBG("Listener accepting connections");
839
840 restart:
841 health_poll_entry();
842 ret = lttng_poll_wait(&events, -1);
843 health_poll_exit();
844 if (ret < 0) {
845 /*
846 * Restart interrupted system call.
847 */
848 if (errno == EINTR) {
849 goto restart;
850 }
851 goto error;
852 }
853
854 nb_fd = ret;
855
856 DBG("Relay new connection received");
857 for (i = 0; i < nb_fd; i++) {
858 health_code_update();
859
860 /* Fetch once the poll data */
861 revents = LTTNG_POLL_GETEV(&events, i);
862 pollfd = LTTNG_POLL_GETFD(&events, i);
863
864 /* Thread quit pipe has been closed. Killing thread. */
865 ret = check_thread_quit_pipe(pollfd, revents);
866 if (ret) {
867 err = 0;
868 goto exit;
869 }
870
871 if (revents & LPOLLIN) {
872 /*
873 * A new connection is requested, therefore a
874 * sessiond/consumerd connection is allocated in
875 * this thread, enqueued to a global queue and
876 * dequeued (and freed) in the worker thread.
877 */
878 int val = 1;
879 struct relay_connection *new_conn;
880 struct lttcomm_sock *newsock;
881 enum connection_type type;
882
883 if (pollfd == data_sock->fd) {
884 type = RELAY_DATA;
885 newsock = data_sock->ops->accept(data_sock);
886 DBG("Relay data connection accepted, socket %d",
887 newsock->fd);
888 } else {
889 assert(pollfd == control_sock->fd);
890 type = RELAY_CONTROL;
891 newsock = control_sock->ops->accept(control_sock);
892 DBG("Relay control connection accepted, socket %d",
893 newsock->fd);
894 }
895 if (!newsock) {
896 PERROR("accepting sock");
897 goto error;
898 }
899
900 ret = setsockopt(newsock->fd, SOL_SOCKET, SO_REUSEADDR, &val,
901 sizeof(val));
902 if (ret < 0) {
903 PERROR("setsockopt inet");
904 lttcomm_destroy_sock(newsock);
905 goto error;
906 }
907
908 ret = socket_apply_keep_alive_config(newsock->fd);
909 if (ret < 0) {
910 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
911 newsock->fd);
912 lttcomm_destroy_sock(newsock);
913 goto error;
914 }
915
916 new_conn = connection_create(newsock, type);
917 if (!new_conn) {
918 lttcomm_destroy_sock(newsock);
919 goto error;
920 }
921
922 /* Enqueue request for the dispatcher thread. */
923 cds_wfcq_enqueue(&relay_conn_queue.head, &relay_conn_queue.tail,
924 &new_conn->qnode);
925
926 /*
927 * Wake the dispatch queue futex.
928 * Implicit memory barrier with the
929 * exchange in cds_wfcq_enqueue.
930 */
931 futex_nto1_wake(&relay_conn_queue.futex);
932 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
933 ERR("socket poll error");
934 goto error;
935 } else {
936 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
937 goto error;
938 }
939 }
940 }
941
942 exit:
943 error:
944 error_poll_add:
945 error_testpoint:
946 lttng_poll_clean(&events);
947 error_create_poll:
948 if (data_sock->fd >= 0) {
949 ret = data_sock->ops->close(data_sock);
950 if (ret) {
951 PERROR("close");
952 }
953 }
954 lttcomm_destroy_sock(data_sock);
955 error_sock_relay:
956 if (control_sock->fd >= 0) {
957 ret = control_sock->ops->close(control_sock);
958 if (ret) {
959 PERROR("close");
960 }
961 }
962 lttcomm_destroy_sock(control_sock);
963 error_sock_control:
964 if (err) {
965 health_error();
966 ERR("Health error occurred in %s", __func__);
967 }
968 health_unregister(health_relayd);
969 DBG("Relay listener thread cleanup complete");
970 lttng_relay_stop_threads();
971 return NULL;
972 }
973
974 /*
975 * This thread manages the dispatching of the requests to worker threads
976 */
977 static void *relay_thread_dispatcher(void *data)
978 {
979 int err = -1;
980 ssize_t ret;
981 struct cds_wfcq_node *node;
982 struct relay_connection *new_conn = NULL;
983
984 DBG("[thread] Relay dispatcher started");
985
986 health_register(health_relayd, HEALTH_RELAYD_TYPE_DISPATCHER);
987
988 if (testpoint(relayd_thread_dispatcher)) {
989 goto error_testpoint;
990 }
991
992 health_code_update();
993
994 for (;;) {
995 health_code_update();
996
997 /* Atomically prepare the queue futex */
998 futex_nto1_prepare(&relay_conn_queue.futex);
999
1000 if (CMM_LOAD_SHARED(dispatch_thread_exit)) {
1001 break;
1002 }
1003
1004 do {
1005 health_code_update();
1006
1007 /* Dequeue commands */
1008 node = cds_wfcq_dequeue_blocking(&relay_conn_queue.head,
1009 &relay_conn_queue.tail);
1010 if (node == NULL) {
1011 DBG("Woken up but nothing in the relay command queue");
1012 /* Continue thread execution */
1013 break;
1014 }
1015 new_conn = caa_container_of(node, struct relay_connection, qnode);
1016
1017 DBG("Dispatching request waiting on sock %d", new_conn->sock->fd);
1018
1019 /*
1020 * Inform worker thread of the new request. This
1021 * call is blocking so we can be assured that
1022 * the data will be read at some point in time
1023 * or wait to the end of the world :)
1024 */
1025 ret = lttng_write(relay_conn_pipe[1], &new_conn, sizeof(new_conn));
1026 if (ret < 0) {
1027 PERROR("write connection pipe");
1028 connection_put(new_conn);
1029 goto error;
1030 }
1031 } while (node != NULL);
1032
1033 /* Futex wait on queue. Blocking call on futex() */
1034 health_poll_entry();
1035 futex_nto1_wait(&relay_conn_queue.futex);
1036 health_poll_exit();
1037 }
1038
1039 /* Normal exit, no error */
1040 err = 0;
1041
1042 error:
1043 error_testpoint:
1044 if (err) {
1045 health_error();
1046 ERR("Health error occurred in %s", __func__);
1047 }
1048 health_unregister(health_relayd);
1049 DBG("Dispatch thread dying");
1050 lttng_relay_stop_threads();
1051 return NULL;
1052 }
1053
1054 /*
1055 * Set index data from the control port to a given index object.
1056 */
1057 static int set_index_control_data(struct relay_index *index,
1058 struct lttcomm_relayd_index *data,
1059 struct relay_connection *conn)
1060 {
1061 struct ctf_packet_index index_data;
1062
1063 /*
1064 * The index on disk is encoded in big endian.
1065 */
1066 index_data.packet_size = htobe64(data->packet_size);
1067 index_data.content_size = htobe64(data->content_size);
1068 index_data.timestamp_begin = htobe64(data->timestamp_begin);
1069 index_data.timestamp_end = htobe64(data->timestamp_end);
1070 index_data.events_discarded = htobe64(data->events_discarded);
1071 index_data.stream_id = htobe64(data->stream_id);
1072
1073 if (conn->minor >= 8) {
1074 index->index_data.stream_instance_id = htobe64(data->stream_instance_id);
1075 index->index_data.packet_seq_num = htobe64(data->packet_seq_num);
1076 }
1077
1078 return relay_index_set_data(index, &index_data);
1079 }
1080
1081 static bool session_streams_have_index(const struct relay_session *session)
1082 {
1083 return session->minor >= 4 && !session->snapshot;
1084 }
1085
1086 /*
1087 * Handle the RELAYD_CREATE_SESSION command.
1088 *
1089 * On success, send back the session id or else return a negative value.
1090 */
1091 static int relay_create_session(const struct lttcomm_relayd_hdr *recv_hdr,
1092 struct relay_connection *conn,
1093 const struct lttng_buffer_view *payload)
1094 {
1095 int ret = 0;
1096 ssize_t send_ret;
1097 struct relay_session *session = NULL;
1098 struct lttcomm_relayd_status_session reply = {};
1099 char session_name[LTTNG_NAME_MAX] = {};
1100 char hostname[LTTNG_HOST_NAME_MAX] = {};
1101 uint32_t live_timer = 0;
1102 bool snapshot = false;
1103 /* Left nil for peers < 2.11. */
1104 lttng_uuid sessiond_uuid = {};
1105 LTTNG_OPTIONAL(uint64_t) id_sessiond = {};
1106 LTTNG_OPTIONAL(uint64_t) current_chunk_id = {};
1107
1108 if (conn->minor < 4) {
1109 /* From 2.1 to 2.3 */
1110 ret = 0;
1111 } else if (conn->minor >= 4 && conn->minor < 11) {
1112 /* From 2.4 to 2.10 */
1113 ret = cmd_create_session_2_4(payload, session_name,
1114 hostname, &live_timer, &snapshot);
1115 } else {
1116 bool has_current_chunk;
1117
1118 /* From 2.11 to ... */
1119 ret = cmd_create_session_2_11(payload, session_name,
1120 hostname, &live_timer, &snapshot,
1121 &id_sessiond.value, sessiond_uuid,
1122 &has_current_chunk,
1123 &current_chunk_id.value);
1124 if (lttng_uuid_is_nil(sessiond_uuid)) {
1125 /* The nil UUID is reserved for pre-2.11 clients. */
1126 ERR("Illegal nil UUID announced by peer in create session command");
1127 ret = -1;
1128 goto send_reply;
1129 }
1130 id_sessiond.is_set = true;
1131 current_chunk_id.is_set = has_current_chunk;
1132 }
1133
1134 if (ret < 0) {
1135 goto send_reply;
1136 }
1137
1138 session = session_create(session_name, hostname, live_timer,
1139 snapshot, sessiond_uuid,
1140 id_sessiond.is_set ? &id_sessiond.value : NULL,
1141 current_chunk_id.is_set ? &current_chunk_id.value : NULL,
1142 conn->major, conn->minor);
1143 if (!session) {
1144 ret = -1;
1145 goto send_reply;
1146 }
1147 assert(!conn->session);
1148 conn->session = session;
1149 DBG("Created session %" PRIu64, session->id);
1150
1151 reply.session_id = htobe64(session->id);
1152
1153 send_reply:
1154 if (ret < 0) {
1155 reply.ret_code = htobe32(LTTNG_ERR_FATAL);
1156 } else {
1157 reply.ret_code = htobe32(LTTNG_OK);
1158 }
1159
1160 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1161 if (send_ret < (ssize_t) sizeof(reply)) {
1162 ERR("Failed to send \"create session\" command reply (ret = %zd)",
1163 send_ret);
1164 ret = -1;
1165 }
1166 if (ret < 0 && session) {
1167 session_put(session);
1168 }
1169 return ret;
1170 }
1171
1172 /*
1173 * When we have received all the streams and the metadata for a channel,
1174 * we make them visible to the viewer threads.
1175 */
1176 static void publish_connection_local_streams(struct relay_connection *conn)
1177 {
1178 struct relay_stream *stream;
1179 struct relay_session *session = conn->session;
1180
1181 /*
1182 * We publish all streams belonging to a session atomically wrt
1183 * session lock.
1184 */
1185 pthread_mutex_lock(&session->lock);
1186 rcu_read_lock();
1187 cds_list_for_each_entry_rcu(stream, &session->recv_list,
1188 recv_node) {
1189 stream_publish(stream);
1190 }
1191 rcu_read_unlock();
1192
1193 /*
1194 * Inform the viewer that there are new streams in the session.
1195 */
1196 if (session->viewer_attached) {
1197 uatomic_set(&session->new_streams, 1);
1198 }
1199 pthread_mutex_unlock(&session->lock);
1200 }
1201
1202 /*
1203 * relay_add_stream: allocate a new stream for a session
1204 */
1205 static int relay_add_stream(const struct lttcomm_relayd_hdr *recv_hdr,
1206 struct relay_connection *conn,
1207 const struct lttng_buffer_view *payload)
1208 {
1209 int ret;
1210 ssize_t send_ret;
1211 struct relay_session *session = conn->session;
1212 struct relay_stream *stream = NULL;
1213 struct lttcomm_relayd_status_stream reply;
1214 struct ctf_trace *trace = NULL;
1215 uint64_t stream_handle = -1ULL;
1216 char *path_name = NULL, *channel_name = NULL;
1217 uint64_t tracefile_size = 0, tracefile_count = 0;
1218 struct relay_stream_chunk_id stream_chunk_id = { 0 };
1219
1220 if (!session || !conn->version_check_done) {
1221 ERR("Trying to add a stream before version check");
1222 ret = -1;
1223 goto end_no_session;
1224 }
1225
1226 if (session->minor == 1) {
1227 /* For 2.1 */
1228 ret = cmd_recv_stream_2_1(payload, &path_name,
1229 &channel_name);
1230 } else if (session->minor > 1 && session->minor < 11) {
1231 /* From 2.2 to 2.10 */
1232 ret = cmd_recv_stream_2_2(payload, &path_name,
1233 &channel_name, &tracefile_size, &tracefile_count);
1234 } else {
1235 /* From 2.11 to ... */
1236 ret = cmd_recv_stream_2_11(payload, &path_name,
1237 &channel_name, &tracefile_size, &tracefile_count,
1238 &stream_chunk_id.value);
1239 stream_chunk_id.is_set = true;
1240 }
1241
1242 if (ret < 0) {
1243 goto send_reply;
1244 }
1245
1246 trace = ctf_trace_get_by_path_or_create(session, path_name);
1247 if (!trace) {
1248 goto send_reply;
1249 }
1250 /* This stream here has one reference on the trace. */
1251
1252 pthread_mutex_lock(&last_relay_stream_id_lock);
1253 stream_handle = ++last_relay_stream_id;
1254 pthread_mutex_unlock(&last_relay_stream_id_lock);
1255
1256 /* We pass ownership of path_name and channel_name. */
1257 stream = stream_create(trace, stream_handle, path_name,
1258 channel_name, tracefile_size, tracefile_count,
1259 &stream_chunk_id);
1260 path_name = NULL;
1261 channel_name = NULL;
1262
1263 /*
1264 * Streams are the owners of their trace. Reference to trace is
1265 * kept within stream_create().
1266 */
1267 ctf_trace_put(trace);
1268
1269 send_reply:
1270 memset(&reply, 0, sizeof(reply));
1271 reply.handle = htobe64(stream_handle);
1272 if (!stream) {
1273 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1274 } else {
1275 reply.ret_code = htobe32(LTTNG_OK);
1276 }
1277
1278 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1279 sizeof(struct lttcomm_relayd_status_stream), 0);
1280 if (send_ret < (ssize_t) sizeof(reply)) {
1281 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1282 send_ret);
1283 ret = -1;
1284 }
1285
1286 end_no_session:
1287 free(path_name);
1288 free(channel_name);
1289 return ret;
1290 }
1291
1292 /*
1293 * relay_close_stream: close a specific stream
1294 */
1295 static int relay_close_stream(const struct lttcomm_relayd_hdr *recv_hdr,
1296 struct relay_connection *conn,
1297 const struct lttng_buffer_view *payload)
1298 {
1299 int ret;
1300 ssize_t send_ret;
1301 struct relay_session *session = conn->session;
1302 struct lttcomm_relayd_close_stream stream_info;
1303 struct lttcomm_relayd_generic_reply reply;
1304 struct relay_stream *stream;
1305
1306 DBG("Close stream received");
1307
1308 if (!session || !conn->version_check_done) {
1309 ERR("Trying to close a stream before version check");
1310 ret = -1;
1311 goto end_no_session;
1312 }
1313
1314 if (payload->size < sizeof(stream_info)) {
1315 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1316 sizeof(stream_info), payload->size);
1317 ret = -1;
1318 goto end_no_session;
1319 }
1320 memcpy(&stream_info, payload->data, sizeof(stream_info));
1321 stream_info.stream_id = be64toh(stream_info.stream_id);
1322 stream_info.last_net_seq_num = be64toh(stream_info.last_net_seq_num);
1323
1324 stream = stream_get_by_id(stream_info.stream_id);
1325 if (!stream) {
1326 ret = -1;
1327 goto end;
1328 }
1329
1330 /*
1331 * Set last_net_seq_num before the close flag. Required by data
1332 * pending check.
1333 */
1334 pthread_mutex_lock(&stream->lock);
1335 stream->last_net_seq_num = stream_info.last_net_seq_num;
1336 pthread_mutex_unlock(&stream->lock);
1337
1338 /*
1339 * This is one of the conditions which may trigger a stream close
1340 * with the others being:
1341 * 1) A close command is received for a stream
1342 * 2) The control connection owning the stream is closed
1343 * 3) We have received all of the stream's data _after_ a close
1344 * request.
1345 */
1346 try_stream_close(stream);
1347 if (stream->is_metadata) {
1348 struct relay_viewer_stream *vstream;
1349
1350 vstream = viewer_stream_get_by_id(stream->stream_handle);
1351 if (vstream) {
1352 if (vstream->metadata_sent == stream->metadata_received) {
1353 /*
1354 * Since all the metadata has been sent to the
1355 * viewer and that we have a request to close
1356 * its stream, we can safely teardown the
1357 * corresponding metadata viewer stream.
1358 */
1359 viewer_stream_put(vstream);
1360 }
1361 /* Put local reference. */
1362 viewer_stream_put(vstream);
1363 }
1364 }
1365 stream_put(stream);
1366 ret = 0;
1367
1368 end:
1369 memset(&reply, 0, sizeof(reply));
1370 if (ret < 0) {
1371 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1372 } else {
1373 reply.ret_code = htobe32(LTTNG_OK);
1374 }
1375 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1376 sizeof(struct lttcomm_relayd_generic_reply), 0);
1377 if (send_ret < (ssize_t) sizeof(reply)) {
1378 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1379 send_ret);
1380 ret = -1;
1381 }
1382
1383 end_no_session:
1384 return ret;
1385 }
1386
1387 /*
1388 * relay_reset_metadata: reset a metadata stream
1389 */
1390 static
1391 int relay_reset_metadata(const struct lttcomm_relayd_hdr *recv_hdr,
1392 struct relay_connection *conn,
1393 const struct lttng_buffer_view *payload)
1394 {
1395 int ret;
1396 ssize_t send_ret;
1397 struct relay_session *session = conn->session;
1398 struct lttcomm_relayd_reset_metadata stream_info;
1399 struct lttcomm_relayd_generic_reply reply;
1400 struct relay_stream *stream;
1401
1402 DBG("Reset metadata received");
1403
1404 if (!session || !conn->version_check_done) {
1405 ERR("Trying to reset a metadata stream before version check");
1406 ret = -1;
1407 goto end_no_session;
1408 }
1409
1410 if (payload->size < sizeof(stream_info)) {
1411 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1412 sizeof(stream_info), payload->size);
1413 ret = -1;
1414 goto end_no_session;
1415 }
1416 memcpy(&stream_info, payload->data, sizeof(stream_info));
1417 stream_info.stream_id = be64toh(stream_info.stream_id);
1418 stream_info.version = be64toh(stream_info.version);
1419
1420 DBG("Update metadata to version %" PRIu64, stream_info.version);
1421
1422 /* Unsupported for live sessions for now. */
1423 if (session->live_timer != 0) {
1424 ret = -1;
1425 goto end;
1426 }
1427
1428 stream = stream_get_by_id(stream_info.stream_id);
1429 if (!stream) {
1430 ret = -1;
1431 goto end;
1432 }
1433 pthread_mutex_lock(&stream->lock);
1434 if (!stream->is_metadata) {
1435 ret = -1;
1436 goto end_unlock;
1437 }
1438
1439 ret = utils_rotate_stream_file(stream->path_name, stream->channel_name,
1440 0, 0, -1, -1, stream->stream_fd->fd, NULL,
1441 &stream->stream_fd->fd);
1442 if (ret < 0) {
1443 ERR("Failed to rotate metadata file %s of channel %s",
1444 stream->path_name, stream->channel_name);
1445 goto end_unlock;
1446 }
1447
1448 end_unlock:
1449 pthread_mutex_unlock(&stream->lock);
1450 stream_put(stream);
1451
1452 end:
1453 memset(&reply, 0, sizeof(reply));
1454 if (ret < 0) {
1455 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1456 } else {
1457 reply.ret_code = htobe32(LTTNG_OK);
1458 }
1459 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1460 sizeof(struct lttcomm_relayd_generic_reply), 0);
1461 if (send_ret < (ssize_t) sizeof(reply)) {
1462 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1463 send_ret);
1464 ret = -1;
1465 }
1466
1467 end_no_session:
1468 return ret;
1469 }
1470
1471 /*
1472 * relay_unknown_command: send -1 if received unknown command
1473 */
1474 static void relay_unknown_command(struct relay_connection *conn)
1475 {
1476 struct lttcomm_relayd_generic_reply reply;
1477 ssize_t send_ret;
1478
1479 memset(&reply, 0, sizeof(reply));
1480 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1481 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1482 if (send_ret < sizeof(reply)) {
1483 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret);
1484 }
1485 }
1486
1487 /*
1488 * relay_start: send an acknowledgment to the client to tell if we are
1489 * ready to receive data. We are ready if a session is established.
1490 */
1491 static int relay_start(const struct lttcomm_relayd_hdr *recv_hdr,
1492 struct relay_connection *conn,
1493 const struct lttng_buffer_view *payload)
1494 {
1495 int ret = 0;
1496 ssize_t send_ret;
1497 struct lttcomm_relayd_generic_reply reply;
1498 struct relay_session *session = conn->session;
1499
1500 if (!session) {
1501 DBG("Trying to start the streaming without a session established");
1502 ret = htobe32(LTTNG_ERR_UNK);
1503 }
1504
1505 memset(&reply, 0, sizeof(reply));
1506 reply.ret_code = htobe32(LTTNG_OK);
1507 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1508 sizeof(reply), 0);
1509 if (send_ret < (ssize_t) sizeof(reply)) {
1510 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1511 send_ret);
1512 ret = -1;
1513 }
1514
1515 return ret;
1516 }
1517
1518 /*
1519 * Append padding to the file pointed by the file descriptor fd.
1520 */
1521 static int write_padding_to_file(int fd, uint32_t size)
1522 {
1523 ssize_t ret = 0;
1524 char *zeros;
1525
1526 if (size == 0) {
1527 goto end;
1528 }
1529
1530 zeros = zmalloc(size);
1531 if (zeros == NULL) {
1532 PERROR("zmalloc zeros for padding");
1533 ret = -1;
1534 goto end;
1535 }
1536
1537 ret = lttng_write(fd, zeros, size);
1538 if (ret < size) {
1539 PERROR("write padding to file");
1540 }
1541
1542 free(zeros);
1543
1544 end:
1545 return ret;
1546 }
1547
1548 /*
1549 * Close the current index file if it is open, and create a new one.
1550 *
1551 * Return 0 on success, -1 on error.
1552 */
1553 static
1554 int create_rotate_index_file(struct relay_stream *stream,
1555 const char *stream_path)
1556 {
1557 int ret;
1558 uint32_t major, minor;
1559
1560 /* Put ref on previous index_file. */
1561 if (stream->index_file) {
1562 lttng_index_file_put(stream->index_file);
1563 stream->index_file = NULL;
1564 }
1565 major = stream->trace->session->major;
1566 minor = stream->trace->session->minor;
1567 stream->index_file = lttng_index_file_create(stream_path,
1568 stream->channel_name,
1569 -1, -1, stream->tracefile_size,
1570 tracefile_array_get_file_index_head(stream->tfa),
1571 lttng_to_index_major(major, minor),
1572 lttng_to_index_minor(major, minor));
1573 if (!stream->index_file) {
1574 ret = -1;
1575 goto end;
1576 }
1577
1578 ret = 0;
1579
1580 end:
1581 return ret;
1582 }
1583
1584 static
1585 int do_rotate_stream_data(struct relay_stream *stream)
1586 {
1587 int ret;
1588
1589 DBG("Rotating stream %" PRIu64 " data file",
1590 stream->stream_handle);
1591 /* Perform the stream rotation. */
1592 ret = utils_rotate_stream_file(stream->path_name,
1593 stream->channel_name, stream->tracefile_size,
1594 stream->tracefile_count, -1,
1595 -1, stream->stream_fd->fd,
1596 NULL, &stream->stream_fd->fd);
1597 if (ret < 0) {
1598 ERR("Rotating stream output file");
1599 goto end;
1600 }
1601 stream->tracefile_size_current = 0;
1602 stream->pos_after_last_complete_data_index = 0;
1603 stream->data_rotated = true;
1604
1605 if (stream->data_rotated && stream->index_rotated) {
1606 /* Rotation completed; reset its state. */
1607 DBG("Rotation completed for stream %" PRIu64,
1608 stream->stream_handle);
1609 stream->rotate_at_seq_num = -1ULL;
1610 stream->data_rotated = false;
1611 stream->index_rotated = false;
1612 }
1613 end:
1614 return ret;
1615 }
1616
1617 /*
1618 * If too much data has been written in a tracefile before we received the
1619 * rotation command, we have to move the excess data to the new tracefile and
1620 * perform the rotation. This can happen because the control and data
1621 * connections are separate, the indexes as well as the commands arrive from
1622 * the control connection and we have no control over the order so we could be
1623 * in a situation where too much data has been received on the data connection
1624 * before the rotation command on the control connection arrives.
1625 */
1626 static
1627 int rotate_truncate_stream(struct relay_stream *stream)
1628 {
1629 int ret, new_fd;
1630 off_t lseek_ret;
1631 uint64_t diff, pos = 0;
1632 char buf[FILE_COPY_BUFFER_SIZE];
1633
1634 assert(!stream->is_metadata);
1635
1636 assert(stream->tracefile_size_current >
1637 stream->pos_after_last_complete_data_index);
1638 diff = stream->tracefile_size_current -
1639 stream->pos_after_last_complete_data_index;
1640
1641 /* Create the new tracefile. */
1642 new_fd = utils_create_stream_file(stream->path_name,
1643 stream->channel_name,
1644 stream->tracefile_size, stream->tracefile_count,
1645 /* uid */ -1, /* gid */ -1, /* suffix */ NULL);
1646 if (new_fd < 0) {
1647 ERR("Failed to create new stream file at path %s for channel %s",
1648 stream->path_name, stream->channel_name);
1649 ret = -1;
1650 goto end;
1651 }
1652
1653 /*
1654 * Rewind the current tracefile to the position at which the rotation
1655 * should have occurred.
1656 */
1657 lseek_ret = lseek(stream->stream_fd->fd,
1658 stream->pos_after_last_complete_data_index, SEEK_SET);
1659 if (lseek_ret < 0) {
1660 PERROR("seek truncate stream");
1661 ret = -1;
1662 goto end;
1663 }
1664
1665 /* Move data from the old file to the new file. */
1666 while (pos < diff) {
1667 uint64_t count, bytes_left;
1668 ssize_t io_ret;
1669
1670 bytes_left = diff - pos;
1671 count = bytes_left > sizeof(buf) ? sizeof(buf) : bytes_left;
1672 assert(count <= SIZE_MAX);
1673
1674 io_ret = lttng_read(stream->stream_fd->fd, buf, count);
1675 if (io_ret < (ssize_t) count) {
1676 char error_string[256];
1677
1678 snprintf(error_string, sizeof(error_string),
1679 "Failed to read %" PRIu64 " bytes from fd %i in rotate_truncate_stream(), returned %zi",
1680 count, stream->stream_fd->fd, io_ret);
1681 if (io_ret == -1) {
1682 PERROR("%s", error_string);
1683 } else {
1684 ERR("%s", error_string);
1685 }
1686 ret = -1;
1687 goto end;
1688 }
1689
1690 io_ret = lttng_write(new_fd, buf, count);
1691 if (io_ret < (ssize_t) count) {
1692 char error_string[256];
1693
1694 snprintf(error_string, sizeof(error_string),
1695 "Failed to write %" PRIu64 " bytes from fd %i in rotate_truncate_stream(), returned %zi",
1696 count, new_fd, io_ret);
1697 if (io_ret == -1) {
1698 PERROR("%s", error_string);
1699 } else {
1700 ERR("%s", error_string);
1701 }
1702 ret = -1;
1703 goto end;
1704 }
1705
1706 pos += count;
1707 }
1708
1709 /* Truncate the file to get rid of the excess data. */
1710 ret = ftruncate(stream->stream_fd->fd,
1711 stream->pos_after_last_complete_data_index);
1712 if (ret) {
1713 PERROR("ftruncate");
1714 goto end;
1715 }
1716
1717 ret = close(stream->stream_fd->fd);
1718 if (ret < 0) {
1719 PERROR("Closing tracefile");
1720 goto end;
1721 }
1722
1723 /*
1724 * Update the offset and FD of all the eventual indexes created by the
1725 * data connection before the rotation command arrived.
1726 */
1727 ret = relay_index_switch_all_files(stream);
1728 if (ret < 0) {
1729 ERR("Failed to rotate index file");
1730 goto end;
1731 }
1732
1733 stream->stream_fd->fd = new_fd;
1734 stream->tracefile_size_current = diff;
1735 stream->pos_after_last_complete_data_index = 0;
1736 stream->rotate_at_seq_num = -1ULL;
1737
1738 ret = 0;
1739
1740 end:
1741 return ret;
1742 }
1743
1744 /*
1745 * Check if a stream's index file should be rotated (for session rotation).
1746 * Must be called with the stream lock held.
1747 *
1748 * Return 0 on success, a negative value on error.
1749 */
1750 static
1751 int try_rotate_stream_index(struct relay_stream *stream)
1752 {
1753 int ret = 0;
1754
1755 if (stream->rotate_at_seq_num == -1ULL) {
1756 /* No rotation expected. */
1757 goto end;
1758 }
1759
1760 if (stream->index_rotated) {
1761 /* Rotation of the index has already occurred. */
1762 goto end;
1763 }
1764
1765 if (stream->prev_index_seq == -1ULL ||
1766 stream->prev_index_seq < stream->rotate_at_seq_num) {
1767 DBG("Stream %" PRIu64 " index not yet ready for rotation (rotate_at_seq_num = %" PRIu64 ", prev_index_seq = %" PRIu64 ")",
1768 stream->stream_handle,
1769 stream->rotate_at_seq_num,
1770 stream->prev_index_seq);
1771 goto end;
1772 } else if (stream->prev_index_seq != stream->rotate_at_seq_num) {
1773 /*
1774 * Unexpected, protocol error/bug.
1775 * It could mean that we received a rotation position
1776 * that is in the past.
1777 */
1778 ERR("Stream %" PRIu64 " index is in an inconsistent state (rotate_at_seq_num = %" PRIu64 ", prev_data_seq = %" PRIu64 ", prev_index_seq = %" PRIu64 ")",
1779 stream->stream_handle,
1780 stream->rotate_at_seq_num,
1781 stream->prev_data_seq,
1782 stream->prev_index_seq);
1783 ret = -1;
1784 goto end;
1785 } else {
1786 DBG("Rotating stream %" PRIu64 " index file",
1787 stream->stream_handle);
1788 ret = create_rotate_index_file(stream, stream->path_name);
1789 stream->index_rotated = true;
1790
1791 if (stream->data_rotated && stream->index_rotated) {
1792 /* Rotation completed; reset its state. */
1793 DBG("Rotation completed for stream %" PRIu64,
1794 stream->stream_handle);
1795 stream->rotate_at_seq_num = -1ULL;
1796 stream->data_rotated = false;
1797 stream->index_rotated = false;
1798 }
1799 }
1800
1801 end:
1802 return ret;
1803 }
1804
1805 /*
1806 * Check if a stream's data file (as opposed to index) should be rotated
1807 * (for session rotation).
1808 * Must be called with the stream lock held.
1809 *
1810 * Return 0 on success, a negative value on error.
1811 */
1812 static
1813 int try_rotate_stream_data(struct relay_stream *stream)
1814 {
1815 int ret = 0;
1816
1817 if (stream->rotate_at_seq_num == -1ULL) {
1818 /* No rotation expected. */
1819 goto end;
1820 }
1821
1822 if (stream->data_rotated) {
1823 /* Rotation of the data file has already occurred. */
1824 goto end;
1825 }
1826
1827 if (stream->prev_data_seq == -1ULL ||
1828 stream->prev_data_seq < stream->rotate_at_seq_num) {
1829 DBG("Stream %" PRIu64 " not yet ready for rotation (rotate_at_seq_num = %" PRIu64 ", prev_data_seq = %" PRIu64 ")",
1830 stream->stream_handle,
1831 stream->rotate_at_seq_num,
1832 stream->prev_data_seq);
1833 goto end;
1834 } else if (stream->prev_data_seq > stream->rotate_at_seq_num) {
1835 /*
1836 * prev_data_seq is checked here since indexes and rotation
1837 * commands are serialized with respect to each other.
1838 */
1839 DBG("Rotation after too much data has been written in tracefile "
1840 "for stream %" PRIu64 ", need to truncate before "
1841 "rotating", stream->stream_handle);
1842 ret = rotate_truncate_stream(stream);
1843 if (ret) {
1844 ERR("Failed to truncate stream");
1845 goto end;
1846 }
1847 } else if (stream->prev_data_seq != stream->rotate_at_seq_num) {
1848 /*
1849 * Unexpected, protocol error/bug.
1850 * It could mean that we received a rotation position
1851 * that is in the past.
1852 */
1853 ERR("Stream %" PRIu64 " data is in an inconsistent state (rotate_at_seq_num = %" PRIu64 ", prev_data_seq = %" PRIu64 ")",
1854 stream->stream_handle,
1855 stream->rotate_at_seq_num,
1856 stream->prev_data_seq);
1857 ret = -1;
1858 goto end;
1859 } else {
1860 ret = do_rotate_stream_data(stream);
1861 }
1862
1863 end:
1864 return ret;
1865 }
1866
1867 /*
1868 * relay_recv_metadata: receive the metadata for the session.
1869 */
1870 static int relay_recv_metadata(const struct lttcomm_relayd_hdr *recv_hdr,
1871 struct relay_connection *conn,
1872 const struct lttng_buffer_view *payload)
1873 {
1874 int ret = 0;
1875 ssize_t size_ret;
1876 struct relay_session *session = conn->session;
1877 struct lttcomm_relayd_metadata_payload metadata_payload_header;
1878 struct relay_stream *metadata_stream;
1879 uint64_t metadata_payload_size;
1880
1881 if (!session) {
1882 ERR("Metadata sent before version check");
1883 ret = -1;
1884 goto end;
1885 }
1886
1887 if (recv_hdr->data_size < sizeof(struct lttcomm_relayd_metadata_payload)) {
1888 ERR("Incorrect data size");
1889 ret = -1;
1890 goto end;
1891 }
1892 metadata_payload_size = recv_hdr->data_size -
1893 sizeof(struct lttcomm_relayd_metadata_payload);
1894
1895 memcpy(&metadata_payload_header, payload->data,
1896 sizeof(metadata_payload_header));
1897 metadata_payload_header.stream_id = be64toh(
1898 metadata_payload_header.stream_id);
1899 metadata_payload_header.padding_size = be32toh(
1900 metadata_payload_header.padding_size);
1901
1902 metadata_stream = stream_get_by_id(metadata_payload_header.stream_id);
1903 if (!metadata_stream) {
1904 ret = -1;
1905 goto end;
1906 }
1907
1908 pthread_mutex_lock(&metadata_stream->lock);
1909
1910 size_ret = lttng_write(metadata_stream->stream_fd->fd,
1911 payload->data + sizeof(metadata_payload_header),
1912 metadata_payload_size);
1913 if (size_ret < metadata_payload_size) {
1914 ERR("Relay error writing metadata on file");
1915 ret = -1;
1916 goto end_put;
1917 }
1918
1919 size_ret = write_padding_to_file(metadata_stream->stream_fd->fd,
1920 metadata_payload_header.padding_size);
1921 if (size_ret < (int64_t) metadata_payload_header.padding_size) {
1922 ret = -1;
1923 goto end_put;
1924 }
1925
1926 metadata_stream->metadata_received +=
1927 metadata_payload_size + metadata_payload_header.padding_size;
1928 DBG2("Relay metadata written. Updated metadata_received %" PRIu64,
1929 metadata_stream->metadata_received);
1930
1931 ret = try_rotate_stream_data(metadata_stream);
1932 if (ret < 0) {
1933 goto end_put;
1934 }
1935
1936 end_put:
1937 pthread_mutex_unlock(&metadata_stream->lock);
1938 stream_put(metadata_stream);
1939 end:
1940 return ret;
1941 }
1942
1943 /*
1944 * relay_send_version: send relayd version number
1945 */
1946 static int relay_send_version(const struct lttcomm_relayd_hdr *recv_hdr,
1947 struct relay_connection *conn,
1948 const struct lttng_buffer_view *payload)
1949 {
1950 int ret;
1951 ssize_t send_ret;
1952 struct lttcomm_relayd_version reply, msg;
1953 bool compatible = true;
1954
1955 conn->version_check_done = true;
1956
1957 /* Get version from the other side. */
1958 if (payload->size < sizeof(msg)) {
1959 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1960 sizeof(msg), payload->size);
1961 ret = -1;
1962 goto end;
1963 }
1964
1965 memcpy(&msg, payload->data, sizeof(msg));
1966 msg.major = be32toh(msg.major);
1967 msg.minor = be32toh(msg.minor);
1968
1969 memset(&reply, 0, sizeof(reply));
1970 reply.major = RELAYD_VERSION_COMM_MAJOR;
1971 reply.minor = RELAYD_VERSION_COMM_MINOR;
1972
1973 /* Major versions must be the same */
1974 if (reply.major != msg.major) {
1975 DBG("Incompatible major versions (%u vs %u), deleting session",
1976 reply.major, msg.major);
1977 compatible = false;
1978 }
1979
1980 conn->major = reply.major;
1981 /* We adapt to the lowest compatible version */
1982 if (reply.minor <= msg.minor) {
1983 conn->minor = reply.minor;
1984 } else {
1985 conn->minor = msg.minor;
1986 }
1987
1988 reply.major = htobe32(reply.major);
1989 reply.minor = htobe32(reply.minor);
1990 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1991 sizeof(reply), 0);
1992 if (send_ret < (ssize_t) sizeof(reply)) {
1993 ERR("Failed to send \"send version\" command reply (ret = %zd)",
1994 send_ret);
1995 ret = -1;
1996 goto end;
1997 } else {
1998 ret = 0;
1999 }
2000
2001 if (!compatible) {
2002 ret = -1;
2003 goto end;
2004 }
2005
2006 DBG("Version check done using protocol %u.%u", conn->major,
2007 conn->minor);
2008
2009 end:
2010 return ret;
2011 }
2012
2013 /*
2014 * Check for data pending for a given stream id from the session daemon.
2015 */
2016 static int relay_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
2017 struct relay_connection *conn,
2018 const struct lttng_buffer_view *payload)
2019 {
2020 struct relay_session *session = conn->session;
2021 struct lttcomm_relayd_data_pending msg;
2022 struct lttcomm_relayd_generic_reply reply;
2023 struct relay_stream *stream;
2024 ssize_t send_ret;
2025 int ret;
2026 uint64_t stream_seq;
2027
2028 DBG("Data pending command received");
2029
2030 if (!session || !conn->version_check_done) {
2031 ERR("Trying to check for data before version check");
2032 ret = -1;
2033 goto end_no_session;
2034 }
2035
2036 if (payload->size < sizeof(msg)) {
2037 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
2038 sizeof(msg), payload->size);
2039 ret = -1;
2040 goto end_no_session;
2041 }
2042 memcpy(&msg, payload->data, sizeof(msg));
2043 msg.stream_id = be64toh(msg.stream_id);
2044 msg.last_net_seq_num = be64toh(msg.last_net_seq_num);
2045
2046 stream = stream_get_by_id(msg.stream_id);
2047 if (stream == NULL) {
2048 ret = -1;
2049 goto end;
2050 }
2051
2052 pthread_mutex_lock(&stream->lock);
2053
2054 if (session_streams_have_index(session)) {
2055 /*
2056 * Ensure that both the index and stream data have been
2057 * flushed up to the requested point.
2058 */
2059 stream_seq = min(stream->prev_data_seq, stream->prev_index_seq);
2060 } else {
2061 stream_seq = stream->prev_data_seq;
2062 }
2063 DBG("Data pending for stream id %" PRIu64 ": prev_data_seq %" PRIu64
2064 ", prev_index_seq %" PRIu64
2065 ", and last_seq %" PRIu64, msg.stream_id,
2066 stream->prev_data_seq, stream->prev_index_seq,
2067 msg.last_net_seq_num);
2068
2069 /* Avoid wrapping issue */
2070 if (((int64_t) (stream_seq - msg.last_net_seq_num)) >= 0) {
2071 /* Data has in fact been written and is NOT pending */
2072 ret = 0;
2073 } else {
2074 /* Data still being streamed thus pending */
2075 ret = 1;
2076 }
2077
2078 stream->data_pending_check_done = true;
2079 pthread_mutex_unlock(&stream->lock);
2080
2081 stream_put(stream);
2082 end:
2083
2084 memset(&reply, 0, sizeof(reply));
2085 reply.ret_code = htobe32(ret);
2086 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2087 if (send_ret < (ssize_t) sizeof(reply)) {
2088 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
2089 send_ret);
2090 ret = -1;
2091 }
2092
2093 end_no_session:
2094 return ret;
2095 }
2096
2097 /*
2098 * Wait for the control socket to reach a quiescent state.
2099 *
2100 * Note that for now, when receiving this command from the session
2101 * daemon, this means that every subsequent commands or data received on
2102 * the control socket has been handled. So, this is why we simply return
2103 * OK here.
2104 */
2105 static int relay_quiescent_control(const struct lttcomm_relayd_hdr *recv_hdr,
2106 struct relay_connection *conn,
2107 const struct lttng_buffer_view *payload)
2108 {
2109 int ret;
2110 ssize_t send_ret;
2111 struct relay_stream *stream;
2112 struct lttcomm_relayd_quiescent_control msg;
2113 struct lttcomm_relayd_generic_reply reply;
2114
2115 DBG("Checking quiescent state on control socket");
2116
2117 if (!conn->session || !conn->version_check_done) {
2118 ERR("Trying to check for data before version check");
2119 ret = -1;
2120 goto end_no_session;
2121 }
2122
2123 if (payload->size < sizeof(msg)) {
2124 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2125 sizeof(msg), payload->size);
2126 ret = -1;
2127 goto end_no_session;
2128 }
2129 memcpy(&msg, payload->data, sizeof(msg));
2130 msg.stream_id = be64toh(msg.stream_id);
2131
2132 stream = stream_get_by_id(msg.stream_id);
2133 if (!stream) {
2134 goto reply;
2135 }
2136 pthread_mutex_lock(&stream->lock);
2137 stream->data_pending_check_done = true;
2138 pthread_mutex_unlock(&stream->lock);
2139
2140 DBG("Relay quiescent control pending flag set to %" PRIu64, msg.stream_id);
2141 stream_put(stream);
2142 reply:
2143 memset(&reply, 0, sizeof(reply));
2144 reply.ret_code = htobe32(LTTNG_OK);
2145 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2146 if (send_ret < (ssize_t) sizeof(reply)) {
2147 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
2148 send_ret);
2149 ret = -1;
2150 } else {
2151 ret = 0;
2152 }
2153
2154 end_no_session:
2155 return ret;
2156 }
2157
2158 /*
2159 * Initialize a data pending command. This means that a consumer is about
2160 * to ask for data pending for each stream it holds. Simply iterate over
2161 * all streams of a session and set the data_pending_check_done flag.
2162 *
2163 * This command returns to the client a LTTNG_OK code.
2164 */
2165 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
2166 struct relay_connection *conn,
2167 const struct lttng_buffer_view *payload)
2168 {
2169 int ret;
2170 ssize_t send_ret;
2171 struct lttng_ht_iter iter;
2172 struct lttcomm_relayd_begin_data_pending msg;
2173 struct lttcomm_relayd_generic_reply reply;
2174 struct relay_stream *stream;
2175
2176 assert(recv_hdr);
2177 assert(conn);
2178
2179 DBG("Init streams for data pending");
2180
2181 if (!conn->session || !conn->version_check_done) {
2182 ERR("Trying to check for data before version check");
2183 ret = -1;
2184 goto end_no_session;
2185 }
2186
2187 if (payload->size < sizeof(msg)) {
2188 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2189 sizeof(msg), payload->size);
2190 ret = -1;
2191 goto end_no_session;
2192 }
2193 memcpy(&msg, payload->data, sizeof(msg));
2194 msg.session_id = be64toh(msg.session_id);
2195
2196 /*
2197 * Iterate over all streams to set the begin data pending flag.
2198 * For now, the streams are indexed by stream handle so we have
2199 * to iterate over all streams to find the one associated with
2200 * the right session_id.
2201 */
2202 rcu_read_lock();
2203 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2204 node.node) {
2205 if (!stream_get(stream)) {
2206 continue;
2207 }
2208 if (stream->trace->session->id == msg.session_id) {
2209 pthread_mutex_lock(&stream->lock);
2210 stream->data_pending_check_done = false;
2211 pthread_mutex_unlock(&stream->lock);
2212 DBG("Set begin data pending flag to stream %" PRIu64,
2213 stream->stream_handle);
2214 }
2215 stream_put(stream);
2216 }
2217 rcu_read_unlock();
2218
2219 memset(&reply, 0, sizeof(reply));
2220 /* All good, send back reply. */
2221 reply.ret_code = htobe32(LTTNG_OK);
2222
2223 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2224 if (send_ret < (ssize_t) sizeof(reply)) {
2225 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2226 send_ret);
2227 ret = -1;
2228 } else {
2229 ret = 0;
2230 }
2231
2232 end_no_session:
2233 return ret;
2234 }
2235
2236 /*
2237 * End data pending command. This will check, for a given session id, if
2238 * each stream associated with it has its data_pending_check_done flag
2239 * set. If not, this means that the client lost track of the stream but
2240 * the data is still being streamed on our side. In this case, we inform
2241 * the client that data is in flight.
2242 *
2243 * Return to the client if there is data in flight or not with a ret_code.
2244 */
2245 static int relay_end_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
2246 struct relay_connection *conn,
2247 const struct lttng_buffer_view *payload)
2248 {
2249 int ret;
2250 ssize_t send_ret;
2251 struct lttng_ht_iter iter;
2252 struct lttcomm_relayd_end_data_pending msg;
2253 struct lttcomm_relayd_generic_reply reply;
2254 struct relay_stream *stream;
2255 uint32_t is_data_inflight = 0;
2256
2257 DBG("End data pending command");
2258
2259 if (!conn->session || !conn->version_check_done) {
2260 ERR("Trying to check for data before version check");
2261 ret = -1;
2262 goto end_no_session;
2263 }
2264
2265 if (payload->size < sizeof(msg)) {
2266 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2267 sizeof(msg), payload->size);
2268 ret = -1;
2269 goto end_no_session;
2270 }
2271 memcpy(&msg, payload->data, sizeof(msg));
2272 msg.session_id = be64toh(msg.session_id);
2273
2274 /*
2275 * Iterate over all streams to see if the begin data pending
2276 * flag is set.
2277 */
2278 rcu_read_lock();
2279 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2280 node.node) {
2281 if (!stream_get(stream)) {
2282 continue;
2283 }
2284 if (stream->trace->session->id != msg.session_id) {
2285 stream_put(stream);
2286 continue;
2287 }
2288 pthread_mutex_lock(&stream->lock);
2289 if (!stream->data_pending_check_done) {
2290 uint64_t stream_seq;
2291
2292 if (session_streams_have_index(conn->session)) {
2293 /*
2294 * Ensure that both the index and stream data have been
2295 * flushed up to the requested point.
2296 */
2297 stream_seq = min(stream->prev_data_seq, stream->prev_index_seq);
2298 } else {
2299 stream_seq = stream->prev_data_seq;
2300 }
2301 if (!stream->closed || !(((int64_t) (stream_seq - stream->last_net_seq_num)) >= 0)) {
2302 is_data_inflight = 1;
2303 DBG("Data is still in flight for stream %" PRIu64,
2304 stream->stream_handle);
2305 pthread_mutex_unlock(&stream->lock);
2306 stream_put(stream);
2307 break;
2308 }
2309 }
2310 pthread_mutex_unlock(&stream->lock);
2311 stream_put(stream);
2312 }
2313 rcu_read_unlock();
2314
2315 memset(&reply, 0, sizeof(reply));
2316 /* All good, send back reply. */
2317 reply.ret_code = htobe32(is_data_inflight);
2318
2319 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2320 if (send_ret < (ssize_t) sizeof(reply)) {
2321 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2322 send_ret);
2323 ret = -1;
2324 } else {
2325 ret = 0;
2326 }
2327
2328 end_no_session:
2329 return ret;
2330 }
2331
2332 /*
2333 * Receive an index for a specific stream.
2334 *
2335 * Return 0 on success else a negative value.
2336 */
2337 static int relay_recv_index(const struct lttcomm_relayd_hdr *recv_hdr,
2338 struct relay_connection *conn,
2339 const struct lttng_buffer_view *payload)
2340 {
2341 int ret;
2342 ssize_t send_ret;
2343 struct relay_session *session = conn->session;
2344 struct lttcomm_relayd_index index_info;
2345 struct relay_index *index;
2346 struct lttcomm_relayd_generic_reply reply;
2347 struct relay_stream *stream;
2348 size_t msg_len;
2349
2350 assert(conn);
2351
2352 DBG("Relay receiving index");
2353
2354 if (!session || !conn->version_check_done) {
2355 ERR("Trying to close a stream before version check");
2356 ret = -1;
2357 goto end_no_session;
2358 }
2359
2360 msg_len = lttcomm_relayd_index_len(
2361 lttng_to_index_major(conn->major, conn->minor),
2362 lttng_to_index_minor(conn->major, conn->minor));
2363 if (payload->size < msg_len) {
2364 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2365 msg_len, payload->size);
2366 ret = -1;
2367 goto end_no_session;
2368 }
2369 memcpy(&index_info, payload->data, msg_len);
2370 index_info.relay_stream_id = be64toh(index_info.relay_stream_id);
2371 index_info.net_seq_num = be64toh(index_info.net_seq_num);
2372 index_info.packet_size = be64toh(index_info.packet_size);
2373 index_info.content_size = be64toh(index_info.content_size);
2374 index_info.timestamp_begin = be64toh(index_info.timestamp_begin);
2375 index_info.timestamp_end = be64toh(index_info.timestamp_end);
2376 index_info.events_discarded = be64toh(index_info.events_discarded);
2377 index_info.stream_id = be64toh(index_info.stream_id);
2378
2379 if (conn->minor >= 8) {
2380 index_info.stream_instance_id =
2381 be64toh(index_info.stream_instance_id);
2382 index_info.packet_seq_num = be64toh(index_info.packet_seq_num);
2383 }
2384
2385 stream = stream_get_by_id(index_info.relay_stream_id);
2386 if (!stream) {
2387 ERR("stream_get_by_id not found");
2388 ret = -1;
2389 goto end;
2390 }
2391 pthread_mutex_lock(&stream->lock);
2392
2393 /* Live beacon handling */
2394 if (index_info.packet_size == 0) {
2395 DBG("Received live beacon for stream %" PRIu64,
2396 stream->stream_handle);
2397
2398 /*
2399 * Only flag a stream inactive when it has already
2400 * received data and no indexes are in flight.
2401 */
2402 if (stream->index_received_seqcount > 0
2403 && stream->indexes_in_flight == 0) {
2404 stream->beacon_ts_end = index_info.timestamp_end;
2405 }
2406 ret = 0;
2407 goto end_stream_put;
2408 } else {
2409 stream->beacon_ts_end = -1ULL;
2410 }
2411
2412 if (stream->ctf_stream_id == -1ULL) {
2413 stream->ctf_stream_id = index_info.stream_id;
2414 }
2415 index = relay_index_get_by_id_or_create(stream, index_info.net_seq_num);
2416 if (!index) {
2417 ret = -1;
2418 ERR("relay_index_get_by_id_or_create index NULL");
2419 goto end_stream_put;
2420 }
2421 if (set_index_control_data(index, &index_info, conn)) {
2422 ERR("set_index_control_data error");
2423 relay_index_put(index);
2424 ret = -1;
2425 goto end_stream_put;
2426 }
2427 ret = relay_index_try_flush(index);
2428 if (ret == 0) {
2429 tracefile_array_commit_seq(stream->tfa);
2430 stream->index_received_seqcount++;
2431 stream->pos_after_last_complete_data_index += index->total_size;
2432 stream->prev_index_seq = index_info.net_seq_num;
2433
2434 ret = try_rotate_stream_index(stream);
2435 if (ret < 0) {
2436 goto end_stream_put;
2437 }
2438 } else if (ret > 0) {
2439 /* no flush. */
2440 ret = 0;
2441 } else {
2442 /*
2443 * ret < 0
2444 *
2445 * relay_index_try_flush is responsible for the self-reference
2446 * put of the index object on error.
2447 */
2448 ERR("relay_index_try_flush error %d", ret);
2449 ret = -1;
2450 }
2451
2452 end_stream_put:
2453 pthread_mutex_unlock(&stream->lock);
2454 stream_put(stream);
2455
2456 end:
2457
2458 memset(&reply, 0, sizeof(reply));
2459 if (ret < 0) {
2460 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2461 } else {
2462 reply.ret_code = htobe32(LTTNG_OK);
2463 }
2464 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2465 if (send_ret < (ssize_t) sizeof(reply)) {
2466 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret);
2467 ret = -1;
2468 }
2469
2470 end_no_session:
2471 return ret;
2472 }
2473
2474 /*
2475 * Receive the streams_sent message.
2476 *
2477 * Return 0 on success else a negative value.
2478 */
2479 static int relay_streams_sent(const struct lttcomm_relayd_hdr *recv_hdr,
2480 struct relay_connection *conn,
2481 const struct lttng_buffer_view *payload)
2482 {
2483 int ret;
2484 ssize_t send_ret;
2485 struct lttcomm_relayd_generic_reply reply;
2486
2487 assert(conn);
2488
2489 DBG("Relay receiving streams_sent");
2490
2491 if (!conn->session || !conn->version_check_done) {
2492 ERR("Trying to close a stream before version check");
2493 ret = -1;
2494 goto end_no_session;
2495 }
2496
2497 /*
2498 * Publish every pending stream in the connection recv list which are
2499 * now ready to be used by the viewer.
2500 */
2501 publish_connection_local_streams(conn);
2502
2503 memset(&reply, 0, sizeof(reply));
2504 reply.ret_code = htobe32(LTTNG_OK);
2505 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2506 if (send_ret < (ssize_t) sizeof(reply)) {
2507 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2508 send_ret);
2509 ret = -1;
2510 } else {
2511 /* Success. */
2512 ret = 0;
2513 }
2514
2515 end_no_session:
2516 return ret;
2517 }
2518
2519 /*
2520 * relay_rotate_session_stream: rotate a stream to a new tracefile for the session
2521 * rotation feature (not the tracefile rotation feature).
2522 */
2523 static int relay_rotate_session_stream(const struct lttcomm_relayd_hdr *recv_hdr,
2524 struct relay_connection *conn,
2525 const struct lttng_buffer_view *payload)
2526 {
2527 int ret;
2528 ssize_t send_ret;
2529 struct relay_session *session = conn->session;
2530 struct lttcomm_relayd_rotate_stream stream_info;
2531 struct lttcomm_relayd_generic_reply reply;
2532 struct relay_stream *stream;
2533 size_t header_len;
2534 size_t path_len;
2535 struct lttng_buffer_view new_path_view;
2536
2537 DBG("Rotate stream received");
2538
2539 if (!session || !conn->version_check_done) {
2540 ERR("Trying to rotate a stream before version check");
2541 ret = -1;
2542 goto end_no_reply;
2543 }
2544
2545 if (session->major == 2 && session->minor < 11) {
2546 ERR("Unsupported feature before 2.11");
2547 ret = -1;
2548 goto end_no_reply;
2549 }
2550
2551 header_len = sizeof(struct lttcomm_relayd_rotate_stream);
2552
2553 if (payload->size < header_len) {
2554 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2555 header_len, payload->size);
2556 ret = -1;
2557 goto end_no_reply;
2558 }
2559
2560 memcpy(&stream_info, payload->data, header_len);
2561
2562 /* Convert to host */
2563 stream_info.pathname_length = be32toh(stream_info.pathname_length);
2564 stream_info.stream_id = be64toh(stream_info.stream_id);
2565 stream_info.new_chunk_id = be64toh(stream_info.new_chunk_id);
2566 stream_info.rotate_at_seq_num = be64toh(stream_info.rotate_at_seq_num);
2567
2568 path_len = stream_info.pathname_length;
2569 if (payload->size < header_len + path_len) {
2570 ERR("Unexpected payload size in \"relay_rotate_session_stream\" including path: expected >= %zu bytes, got %zu bytes",
2571 header_len + path_len, payload->size);
2572 ret = -1;
2573 goto end_no_reply;
2574 }
2575
2576 /* Ensure it fits in local filename length. */
2577 if (path_len >= LTTNG_PATH_MAX) {
2578 ret = -ENAMETOOLONG;
2579 ERR("Length of relay_rotate_session_stream command's path name (%zu bytes) exceeds the maximal allowed length of %i bytes",
2580 path_len, LTTNG_PATH_MAX);
2581 goto end;
2582 }
2583
2584 new_path_view = lttng_buffer_view_from_view(payload, header_len,
2585 stream_info.pathname_length);
2586
2587 stream = stream_get_by_id(stream_info.stream_id);
2588 if (!stream) {
2589 ret = -1;
2590 goto end;
2591 }
2592
2593 pthread_mutex_lock(&stream->lock);
2594
2595 /*
2596 * Update the trace path (just the folder, the stream name does not
2597 * change).
2598 */
2599 free(stream->prev_path_name);
2600 stream->prev_path_name = stream->path_name;
2601 stream->path_name = create_output_path(new_path_view.data);
2602 if (!stream->path_name) {
2603 ERR("Failed to create a new output path");
2604 ret = -1;
2605 goto end_stream_unlock;
2606 }
2607 ret = utils_mkdir_recursive(stream->path_name, S_IRWXU | S_IRWXG,
2608 -1, -1);
2609 if (ret < 0) {
2610 ERR("relay creating output directory");
2611 ret = -1;
2612 goto end_stream_unlock;
2613 }
2614
2615 assert(stream->current_chunk_id.is_set);
2616 stream->current_chunk_id.value = stream_info.new_chunk_id;
2617
2618 if (stream->is_metadata) {
2619 /*
2620 * Metadata streams have no index; consider its rotation
2621 * complete.
2622 */
2623 stream->index_rotated = true;
2624 /*
2625 * The metadata stream is sent only over the control connection
2626 * so we know we have all the data to perform the stream
2627 * rotation.
2628 */
2629 ret = do_rotate_stream_data(stream);
2630 } else {
2631 stream->rotate_at_seq_num = stream_info.rotate_at_seq_num;
2632 ret = try_rotate_stream_data(stream);
2633 if (ret < 0) {
2634 goto end_stream_unlock;
2635 }
2636
2637 ret = try_rotate_stream_index(stream);
2638 if (ret < 0) {
2639 goto end_stream_unlock;
2640 }
2641 }
2642
2643 end_stream_unlock:
2644 pthread_mutex_unlock(&stream->lock);
2645 stream_put(stream);
2646 end:
2647 memset(&reply, 0, sizeof(reply));
2648 if (ret < 0) {
2649 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2650 } else {
2651 reply.ret_code = htobe32(LTTNG_OK);
2652 }
2653 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
2654 sizeof(struct lttcomm_relayd_generic_reply), 0);
2655 if (send_ret < (ssize_t) sizeof(reply)) {
2656 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2657 send_ret);
2658 ret = -1;
2659 }
2660
2661 end_no_reply:
2662 return ret;
2663 }
2664
2665 #define DBG_CMD(cmd_name, conn) \
2666 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
2667
2668 static int relay_process_control_command(struct relay_connection *conn,
2669 const struct lttcomm_relayd_hdr *header,
2670 const struct lttng_buffer_view *payload)
2671 {
2672 int ret = 0;
2673
2674 switch (header->cmd) {
2675 case RELAYD_CREATE_SESSION:
2676 DBG_CMD("RELAYD_CREATE_SESSION", conn);
2677 ret = relay_create_session(header, conn, payload);
2678 break;
2679 case RELAYD_ADD_STREAM:
2680 DBG_CMD("RELAYD_ADD_STREAM", conn);
2681 ret = relay_add_stream(header, conn, payload);
2682 break;
2683 case RELAYD_START_DATA:
2684 DBG_CMD("RELAYD_START_DATA", conn);
2685 ret = relay_start(header, conn, payload);
2686 break;
2687 case RELAYD_SEND_METADATA:
2688 DBG_CMD("RELAYD_SEND_METADATA", conn);
2689 ret = relay_recv_metadata(header, conn, payload);
2690 break;
2691 case RELAYD_VERSION:
2692 DBG_CMD("RELAYD_VERSION", conn);
2693 ret = relay_send_version(header, conn, payload);
2694 break;
2695 case RELAYD_CLOSE_STREAM:
2696 DBG_CMD("RELAYD_CLOSE_STREAM", conn);
2697 ret = relay_close_stream(header, conn, payload);
2698 break;
2699 case RELAYD_DATA_PENDING:
2700 DBG_CMD("RELAYD_DATA_PENDING", conn);
2701 ret = relay_data_pending(header, conn, payload);
2702 break;
2703 case RELAYD_QUIESCENT_CONTROL:
2704 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn);
2705 ret = relay_quiescent_control(header, conn, payload);
2706 break;
2707 case RELAYD_BEGIN_DATA_PENDING:
2708 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn);
2709 ret = relay_begin_data_pending(header, conn, payload);
2710 break;
2711 case RELAYD_END_DATA_PENDING:
2712 DBG_CMD("RELAYD_END_DATA_PENDING", conn);
2713 ret = relay_end_data_pending(header, conn, payload);
2714 break;
2715 case RELAYD_SEND_INDEX:
2716 DBG_CMD("RELAYD_SEND_INDEX", conn);
2717 ret = relay_recv_index(header, conn, payload);
2718 break;
2719 case RELAYD_STREAMS_SENT:
2720 DBG_CMD("RELAYD_STREAMS_SENT", conn);
2721 ret = relay_streams_sent(header, conn, payload);
2722 break;
2723 case RELAYD_RESET_METADATA:
2724 DBG_CMD("RELAYD_RESET_METADATA", conn);
2725 ret = relay_reset_metadata(header, conn, payload);
2726 break;
2727 case RELAYD_ROTATE_STREAM:
2728 DBG_CMD("RELAYD_ROTATE_STREAM", conn);
2729 ret = relay_rotate_session_stream(header, conn, payload);
2730 break;
2731 case RELAYD_UPDATE_SYNC_INFO:
2732 default:
2733 ERR("Received unknown command (%u)", header->cmd);
2734 relay_unknown_command(conn);
2735 ret = -1;
2736 goto end;
2737 }
2738
2739 end:
2740 return ret;
2741 }
2742
2743 static enum relay_connection_status relay_process_control_receive_payload(
2744 struct relay_connection *conn)
2745 {
2746 int ret = 0;
2747 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
2748 struct lttng_dynamic_buffer *reception_buffer =
2749 &conn->protocol.ctrl.reception_buffer;
2750 struct ctrl_connection_state_receive_payload *state =
2751 &conn->protocol.ctrl.state.receive_payload;
2752 struct lttng_buffer_view payload_view;
2753
2754 if (state->left_to_receive == 0) {
2755 /* Short-circuit for payload-less commands. */
2756 goto reception_complete;
2757 }
2758
2759 ret = conn->sock->ops->recvmsg(conn->sock,
2760 reception_buffer->data + state->received,
2761 state->left_to_receive, MSG_DONTWAIT);
2762 if (ret < 0) {
2763 if (errno != EAGAIN && errno != EWOULDBLOCK) {
2764 PERROR("Unable to receive command payload on sock %d",
2765 conn->sock->fd);
2766 status = RELAY_CONNECTION_STATUS_ERROR;
2767 }
2768 goto end;
2769 } else if (ret == 0) {
2770 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
2771 status = RELAY_CONNECTION_STATUS_CLOSED;
2772 goto end;
2773 }
2774
2775 assert(ret > 0);
2776 assert(ret <= state->left_to_receive);
2777
2778 state->left_to_receive -= ret;
2779 state->received += ret;
2780
2781 if (state->left_to_receive > 0) {
2782 /*
2783 * Can't transition to the protocol's next state, wait to
2784 * receive the rest of the header.
2785 */
2786 DBG3("Partial reception of control connection protocol payload (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
2787 state->received, state->left_to_receive,
2788 conn->sock->fd);
2789 goto end;
2790 }
2791
2792 reception_complete:
2793 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64 " bytes",
2794 conn->sock->fd, state->received);
2795 /*
2796 * The payload required to process the command has been received.
2797 * A view to the reception buffer is forwarded to the various
2798 * commands and the state of the control is reset on success.
2799 *
2800 * Commands are responsible for sending their reply to the peer.
2801 */
2802 payload_view = lttng_buffer_view_from_dynamic_buffer(reception_buffer,
2803 0, -1);
2804 ret = relay_process_control_command(conn,
2805 &state->header, &payload_view);
2806 if (ret < 0) {
2807 status = RELAY_CONNECTION_STATUS_ERROR;
2808 goto end;
2809 }
2810
2811 ret = connection_reset_protocol_state(conn);
2812 if (ret) {
2813 status = RELAY_CONNECTION_STATUS_ERROR;
2814 }
2815 end:
2816 return status;
2817 }
2818
2819 static enum relay_connection_status relay_process_control_receive_header(
2820 struct relay_connection *conn)
2821 {
2822 int ret = 0;
2823 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
2824 struct lttcomm_relayd_hdr header;
2825 struct lttng_dynamic_buffer *reception_buffer =
2826 &conn->protocol.ctrl.reception_buffer;
2827 struct ctrl_connection_state_receive_header *state =
2828 &conn->protocol.ctrl.state.receive_header;
2829
2830 assert(state->left_to_receive != 0);
2831
2832 ret = conn->sock->ops->recvmsg(conn->sock,
2833 reception_buffer->data + state->received,
2834 state->left_to_receive, MSG_DONTWAIT);
2835 if (ret < 0) {
2836 if (errno != EAGAIN && errno != EWOULDBLOCK) {
2837 PERROR("Unable to receive control command header on sock %d",
2838 conn->sock->fd);
2839 status = RELAY_CONNECTION_STATUS_ERROR;
2840 }
2841 goto end;
2842 } else if (ret == 0) {
2843 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
2844 status = RELAY_CONNECTION_STATUS_CLOSED;
2845 goto end;
2846 }
2847
2848 assert(ret > 0);
2849 assert(ret <= state->left_to_receive);
2850
2851 state->left_to_receive -= ret;
2852 state->received += ret;
2853
2854 if (state->left_to_receive > 0) {
2855 /*
2856 * Can't transition to the protocol's next state, wait to
2857 * receive the rest of the header.
2858 */
2859 DBG3("Partial reception of control connection protocol header (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
2860 state->received, state->left_to_receive,
2861 conn->sock->fd);
2862 goto end;
2863 }
2864
2865 /* Transition to next state: receiving the command's payload. */
2866 conn->protocol.ctrl.state_id =
2867 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD;
2868 memcpy(&header, reception_buffer->data, sizeof(header));
2869 header.circuit_id = be64toh(header.circuit_id);
2870 header.data_size = be64toh(header.data_size);
2871 header.cmd = be32toh(header.cmd);
2872 header.cmd_version = be32toh(header.cmd_version);
2873 memcpy(&conn->protocol.ctrl.state.receive_payload.header,
2874 &header, sizeof(header));
2875
2876 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32 ", cmd_version = %" PRIu32 ", payload size = %" PRIu64 " bytes",
2877 conn->sock->fd, header.cmd, header.cmd_version,
2878 header.data_size);
2879
2880 if (header.data_size > DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE) {
2881 ERR("Command header indicates a payload (%" PRIu64 " bytes) that exceeds the maximal payload size allowed on a control connection.",
2882 header.data_size);
2883 status = RELAY_CONNECTION_STATUS_ERROR;
2884 goto end;
2885 }
2886
2887 conn->protocol.ctrl.state.receive_payload.left_to_receive =
2888 header.data_size;
2889 conn->protocol.ctrl.state.receive_payload.received = 0;
2890 ret = lttng_dynamic_buffer_set_size(reception_buffer,
2891 header.data_size);
2892 if (ret) {
2893 status = RELAY_CONNECTION_STATUS_ERROR;
2894 goto end;
2895 }
2896
2897 if (header.data_size == 0) {
2898 /*
2899 * Manually invoke the next state as the poll loop
2900 * will not wake-up to allow us to proceed further.
2901 */
2902 status = relay_process_control_receive_payload(conn);
2903 }
2904 end:
2905 return status;
2906 }
2907
2908 /*
2909 * Process the commands received on the control socket
2910 */
2911 static enum relay_connection_status relay_process_control(
2912 struct relay_connection *conn)
2913 {
2914 enum relay_connection_status status;
2915
2916 switch (conn->protocol.ctrl.state_id) {
2917 case CTRL_CONNECTION_STATE_RECEIVE_HEADER:
2918 status = relay_process_control_receive_header(conn);
2919 break;
2920 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD:
2921 status = relay_process_control_receive_payload(conn);
2922 break;
2923 default:
2924 ERR("Unknown control connection protocol state encountered.");
2925 abort();
2926 }
2927
2928 return status;
2929 }
2930
2931 /*
2932 * Handle index for a data stream.
2933 *
2934 * Called with the stream lock held.
2935 *
2936 * Return 0 on success else a negative value.
2937 */
2938 static int handle_index_data(struct relay_stream *stream, uint64_t net_seq_num,
2939 bool rotate_index, bool *flushed, uint64_t total_size)
2940 {
2941 int ret = 0;
2942 uint64_t data_offset;
2943 struct relay_index *index;
2944
2945 /* Get data offset because we are about to update the index. */
2946 data_offset = htobe64(stream->tracefile_size_current);
2947
2948 DBG("handle_index_data: stream %" PRIu64 " net_seq_num %" PRIu64 " data offset %" PRIu64,
2949 stream->stream_handle, net_seq_num, stream->tracefile_size_current);
2950
2951 /*
2952 * Lookup for an existing index for that stream id/sequence
2953 * number. If it exists, the control thread has already received the
2954 * data for it, thus we need to write it to disk.
2955 */
2956 index = relay_index_get_by_id_or_create(stream, net_seq_num);
2957 if (!index) {
2958 ret = -1;
2959 goto end;
2960 }
2961
2962 if (rotate_index || !stream->index_file) {
2963 const char *stream_path;
2964
2965 /*
2966 * The data connection creates the stream's first index file.
2967 *
2968 * This can happen _after_ a ROTATE_STREAM command. In
2969 * other words, the data of the first packet of this stream
2970 * can be received after a ROTATE_STREAM command.
2971 *
2972 * The ROTATE_STREAM command changes the stream's path_name
2973 * to point to the "next" chunk. If a rotation is pending for
2974 * this stream, as indicated by "rotate_at_seq_num != -1ULL",
2975 * it means that we are still receiving data that belongs in the
2976 * stream's former path.
2977 *
2978 * In this very specific case, we must ensure that the index
2979 * file is created in the streams's former path,
2980 * "prev_path_name".
2981 *
2982 * All other rotations beyond the first one are not affected
2983 * by this problem since the actual rotation operation creates
2984 * the new chunk's index file.
2985 */
2986 stream_path = stream->rotate_at_seq_num == -1ULL ?
2987 stream->path_name:
2988 stream->prev_path_name;
2989
2990 ret = create_rotate_index_file(stream, stream_path);
2991 if (ret < 0) {
2992 ERR("Failed to rotate index");
2993 /* Put self-ref for this index due to error. */
2994 relay_index_put(index);
2995 index = NULL;
2996 goto end;
2997 }
2998 }
2999
3000 if (relay_index_set_file(index, stream->index_file, data_offset)) {
3001 ret = -1;
3002 /* Put self-ref for this index due to error. */
3003 relay_index_put(index);
3004 index = NULL;
3005 goto end;
3006 }
3007
3008 ret = relay_index_try_flush(index);
3009 if (ret == 0) {
3010 tracefile_array_commit_seq(stream->tfa);
3011 stream->index_received_seqcount++;
3012 *flushed = true;
3013 } else if (ret > 0) {
3014 index->total_size = total_size;
3015 /* No flush. */
3016 ret = 0;
3017 } else {
3018 /*
3019 * ret < 0
3020 *
3021 * relay_index_try_flush is responsible for the self-reference
3022 * put of the index object on error.
3023 */
3024 ERR("relay_index_try_flush error %d", ret);
3025 ret = -1;
3026 }
3027 end:
3028 return ret;
3029 }
3030
3031 static enum relay_connection_status relay_process_data_receive_header(
3032 struct relay_connection *conn)
3033 {
3034 int ret;
3035 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
3036 struct data_connection_state_receive_header *state =
3037 &conn->protocol.data.state.receive_header;
3038 struct lttcomm_relayd_data_hdr header;
3039 struct relay_stream *stream;
3040
3041 assert(state->left_to_receive != 0);
3042
3043 ret = conn->sock->ops->recvmsg(conn->sock,
3044 state->header_reception_buffer + state->received,
3045 state->left_to_receive, MSG_DONTWAIT);
3046 if (ret < 0) {
3047 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3048 PERROR("Unable to receive data header on sock %d", conn->sock->fd);
3049 status = RELAY_CONNECTION_STATUS_ERROR;
3050 }
3051 goto end;
3052 } else if (ret == 0) {
3053 /* Orderly shutdown. Not necessary to print an error. */
3054 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
3055 status = RELAY_CONNECTION_STATUS_CLOSED;
3056 goto end;
3057 }
3058
3059 assert(ret > 0);
3060 assert(ret <= state->left_to_receive);
3061
3062 state->left_to_receive -= ret;
3063 state->received += ret;
3064
3065 if (state->left_to_receive > 0) {
3066 /*
3067 * Can't transition to the protocol's next state, wait to
3068 * receive the rest of the header.
3069 */
3070 DBG3("Partial reception of data connection header (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
3071 state->received, state->left_to_receive,
3072 conn->sock->fd);
3073 goto end;
3074 }
3075
3076 /* Transition to next state: receiving the payload. */
3077 conn->protocol.data.state_id = DATA_CONNECTION_STATE_RECEIVE_PAYLOAD;
3078
3079 memcpy(&header, state->header_reception_buffer, sizeof(header));
3080 header.circuit_id = be64toh(header.circuit_id);
3081 header.stream_id = be64toh(header.stream_id);
3082 header.data_size = be32toh(header.data_size);
3083 header.net_seq_num = be64toh(header.net_seq_num);
3084 header.padding_size = be32toh(header.padding_size);
3085 memcpy(&conn->protocol.data.state.receive_payload.header, &header, sizeof(header));
3086
3087 conn->protocol.data.state.receive_payload.left_to_receive =
3088 header.data_size;
3089 conn->protocol.data.state.receive_payload.received = 0;
3090 conn->protocol.data.state.receive_payload.rotate_index = false;
3091
3092 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64 ", stream_id = %" PRIu64 ", data_size = %" PRIu32 ", net_seq_num = %" PRIu64 ", padding_size = %" PRIu32,
3093 conn->sock->fd, header.circuit_id,
3094 header.stream_id, header.data_size,
3095 header.net_seq_num, header.padding_size);
3096
3097 stream = stream_get_by_id(header.stream_id);
3098 if (!stream) {
3099 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64,
3100 header.stream_id);
3101 /* Protocol error. */
3102 status = RELAY_CONNECTION_STATUS_ERROR;
3103 goto end;
3104 }
3105
3106 pthread_mutex_lock(&stream->lock);
3107
3108 /* Check if a rotation is needed. */
3109 if (stream->tracefile_size > 0 &&
3110 (stream->tracefile_size_current + header.data_size) >
3111 stream->tracefile_size) {
3112 uint64_t old_id, new_id;
3113
3114 old_id = tracefile_array_get_file_index_head(stream->tfa);
3115 tracefile_array_file_rotate(stream->tfa);
3116
3117 /* new_id is updated by utils_rotate_stream_file. */
3118 new_id = old_id;
3119
3120 ret = utils_rotate_stream_file(stream->path_name,
3121 stream->channel_name, stream->tracefile_size,
3122 stream->tracefile_count, -1,
3123 -1, stream->stream_fd->fd,
3124 &new_id, &stream->stream_fd->fd);
3125 if (ret < 0) {
3126 ERR("Failed to rotate stream output file");
3127 status = RELAY_CONNECTION_STATUS_ERROR;
3128 goto end_stream_unlock;
3129 }
3130
3131 /*
3132 * Reset current size because we just performed a stream
3133 * rotation.
3134 */
3135 stream->tracefile_size_current = 0;
3136 conn->protocol.data.state.receive_payload.rotate_index = true;
3137 }
3138
3139 end_stream_unlock:
3140 pthread_mutex_unlock(&stream->lock);
3141 stream_put(stream);
3142 end:
3143 return status;
3144 }
3145
3146 static enum relay_connection_status relay_process_data_receive_payload(
3147 struct relay_connection *conn)
3148 {
3149 int ret;
3150 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
3151 struct relay_stream *stream;
3152 struct data_connection_state_receive_payload *state =
3153 &conn->protocol.data.state.receive_payload;
3154 const size_t chunk_size = RECV_DATA_BUFFER_SIZE;
3155 char data_buffer[chunk_size];
3156 bool partial_recv = false;
3157 bool new_stream = false, close_requested = false, index_flushed = false;
3158 uint64_t left_to_receive = state->left_to_receive;
3159 struct relay_session *session;
3160
3161 DBG3("Receiving data for stream id %" PRIu64 " seqnum %" PRIu64 ", %" PRIu64" bytes received, %" PRIu64 " bytes left to receive",
3162 state->header.stream_id, state->header.net_seq_num,
3163 state->received, left_to_receive);
3164
3165 stream = stream_get_by_id(state->header.stream_id);
3166 if (!stream) {
3167 /* Protocol error. */
3168 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64,
3169 state->header.stream_id);
3170 status = RELAY_CONNECTION_STATUS_ERROR;
3171 goto end;
3172 }
3173
3174 pthread_mutex_lock(&stream->lock);
3175 session = stream->trace->session;
3176 if (!conn->session) {
3177 ret = connection_set_session(conn, session);
3178 if (ret) {
3179 status = RELAY_CONNECTION_STATUS_ERROR;
3180 goto end_stream_unlock;
3181 }
3182 }
3183
3184 /*
3185 * The size of the "chunk" received on any iteration is bounded by:
3186 * - the data left to receive,
3187 * - the data immediately available on the socket,
3188 * - the on-stack data buffer
3189 */
3190 while (left_to_receive > 0 && !partial_recv) {
3191 ssize_t write_ret;