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