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