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