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