Use dynamic payload for the add stream realyd command
[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
1202 if (!session || !conn->version_check_done) {
1203 ERR("Trying to add a stream before version check");
1204 ret = -1;
1205 goto end_no_session;
1206 }
1207
1208 if (session->minor == 1) {
1209 /* For 2.1 */
1210 ret = cmd_recv_stream_2_1(payload, &path_name,
1211 &channel_name);
1212 } else if (session->minor > 1 && session->minor < 11) {
1213 /* From 2.2 to 2.10 */
1214 ret = cmd_recv_stream_2_2(payload, &path_name,
1215 &channel_name, &tracefile_size, &tracefile_count);
1216 } else {
1217 /* From 2.11 to ... */
1218 ret = cmd_recv_stream_2_11(payload, &path_name,
1219 &channel_name, &tracefile_size, &tracefile_count);
1220 }
1221
1222 if (ret < 0) {
1223 goto send_reply;
1224 }
1225
1226 trace = ctf_trace_get_by_path_or_create(session, path_name);
1227 if (!trace) {
1228 goto send_reply;
1229 }
1230 /* This stream here has one reference on the trace. */
1231
1232 pthread_mutex_lock(&last_relay_stream_id_lock);
1233 stream_handle = ++last_relay_stream_id;
1234 pthread_mutex_unlock(&last_relay_stream_id_lock);
1235
1236 /* We pass ownership of path_name and channel_name. */
1237 stream = stream_create(trace, stream_handle, path_name,
1238 channel_name, tracefile_size, tracefile_count);
1239 path_name = NULL;
1240 channel_name = NULL;
1241
1242 /*
1243 * Streams are the owners of their trace. Reference to trace is
1244 * kept within stream_create().
1245 */
1246 ctf_trace_put(trace);
1247
1248 send_reply:
1249 memset(&reply, 0, sizeof(reply));
1250 reply.handle = htobe64(stream_handle);
1251 if (!stream) {
1252 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1253 } else {
1254 reply.ret_code = htobe32(LTTNG_OK);
1255 }
1256
1257 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1258 sizeof(struct lttcomm_relayd_status_stream), 0);
1259 if (send_ret < (ssize_t) sizeof(reply)) {
1260 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1261 send_ret);
1262 ret = -1;
1263 }
1264
1265 end_no_session:
1266 free(path_name);
1267 free(channel_name);
1268 return ret;
1269 }
1270
1271 /*
1272 * relay_close_stream: close a specific stream
1273 */
1274 static int relay_close_stream(const struct lttcomm_relayd_hdr *recv_hdr,
1275 struct relay_connection *conn,
1276 const struct lttng_buffer_view *payload)
1277 {
1278 int ret;
1279 ssize_t send_ret;
1280 struct relay_session *session = conn->session;
1281 struct lttcomm_relayd_close_stream stream_info;
1282 struct lttcomm_relayd_generic_reply reply;
1283 struct relay_stream *stream;
1284
1285 DBG("Close stream received");
1286
1287 if (!session || !conn->version_check_done) {
1288 ERR("Trying to close a stream before version check");
1289 ret = -1;
1290 goto end_no_session;
1291 }
1292
1293 if (payload->size < sizeof(stream_info)) {
1294 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1295 sizeof(stream_info), payload->size);
1296 ret = -1;
1297 goto end_no_session;
1298 }
1299 memcpy(&stream_info, payload->data, sizeof(stream_info));
1300 stream_info.stream_id = be64toh(stream_info.stream_id);
1301 stream_info.last_net_seq_num = be64toh(stream_info.last_net_seq_num);
1302
1303 stream = stream_get_by_id(stream_info.stream_id);
1304 if (!stream) {
1305 ret = -1;
1306 goto end;
1307 }
1308
1309 /*
1310 * Set last_net_seq_num before the close flag. Required by data
1311 * pending check.
1312 */
1313 pthread_mutex_lock(&stream->lock);
1314 stream->last_net_seq_num = stream_info.last_net_seq_num;
1315 pthread_mutex_unlock(&stream->lock);
1316
1317 /*
1318 * This is one of the conditions which may trigger a stream close
1319 * with the others being:
1320 * 1) A close command is received for a stream
1321 * 2) The control connection owning the stream is closed
1322 * 3) We have received all of the stream's data _after_ a close
1323 * request.
1324 */
1325 try_stream_close(stream);
1326 if (stream->is_metadata) {
1327 struct relay_viewer_stream *vstream;
1328
1329 vstream = viewer_stream_get_by_id(stream->stream_handle);
1330 if (vstream) {
1331 if (vstream->metadata_sent == stream->metadata_received) {
1332 /*
1333 * Since all the metadata has been sent to the
1334 * viewer and that we have a request to close
1335 * its stream, we can safely teardown the
1336 * corresponding metadata viewer stream.
1337 */
1338 viewer_stream_put(vstream);
1339 }
1340 /* Put local reference. */
1341 viewer_stream_put(vstream);
1342 }
1343 }
1344 stream_put(stream);
1345 ret = 0;
1346
1347 end:
1348 memset(&reply, 0, sizeof(reply));
1349 if (ret < 0) {
1350 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1351 } else {
1352 reply.ret_code = htobe32(LTTNG_OK);
1353 }
1354 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1355 sizeof(struct lttcomm_relayd_generic_reply), 0);
1356 if (send_ret < (ssize_t) sizeof(reply)) {
1357 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1358 send_ret);
1359 ret = -1;
1360 }
1361
1362 end_no_session:
1363 return ret;
1364 }
1365
1366 /*
1367 * relay_reset_metadata: reset a metadata stream
1368 */
1369 static
1370 int relay_reset_metadata(const struct lttcomm_relayd_hdr *recv_hdr,
1371 struct relay_connection *conn,
1372 const struct lttng_buffer_view *payload)
1373 {
1374 int ret;
1375 ssize_t send_ret;
1376 struct relay_session *session = conn->session;
1377 struct lttcomm_relayd_reset_metadata stream_info;
1378 struct lttcomm_relayd_generic_reply reply;
1379 struct relay_stream *stream;
1380
1381 DBG("Reset metadata received");
1382
1383 if (!session || !conn->version_check_done) {
1384 ERR("Trying to reset a metadata stream before version check");
1385 ret = -1;
1386 goto end_no_session;
1387 }
1388
1389 if (payload->size < sizeof(stream_info)) {
1390 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1391 sizeof(stream_info), payload->size);
1392 ret = -1;
1393 goto end_no_session;
1394 }
1395 memcpy(&stream_info, payload->data, sizeof(stream_info));
1396 stream_info.stream_id = be64toh(stream_info.stream_id);
1397 stream_info.version = be64toh(stream_info.version);
1398
1399 DBG("Update metadata to version %" PRIu64, stream_info.version);
1400
1401 /* Unsupported for live sessions for now. */
1402 if (session->live_timer != 0) {
1403 ret = -1;
1404 goto end;
1405 }
1406
1407 stream = stream_get_by_id(stream_info.stream_id);
1408 if (!stream) {
1409 ret = -1;
1410 goto end;
1411 }
1412 pthread_mutex_lock(&stream->lock);
1413 if (!stream->is_metadata) {
1414 ret = -1;
1415 goto end_unlock;
1416 }
1417
1418 ret = utils_rotate_stream_file(stream->path_name, stream->channel_name,
1419 0, 0, -1, -1, stream->stream_fd->fd, NULL,
1420 &stream->stream_fd->fd);
1421 if (ret < 0) {
1422 ERR("Failed to rotate metadata file %s of channel %s",
1423 stream->path_name, stream->channel_name);
1424 goto end_unlock;
1425 }
1426
1427 end_unlock:
1428 pthread_mutex_unlock(&stream->lock);
1429 stream_put(stream);
1430
1431 end:
1432 memset(&reply, 0, sizeof(reply));
1433 if (ret < 0) {
1434 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1435 } else {
1436 reply.ret_code = htobe32(LTTNG_OK);
1437 }
1438 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1439 sizeof(struct lttcomm_relayd_generic_reply), 0);
1440 if (send_ret < (ssize_t) sizeof(reply)) {
1441 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1442 send_ret);
1443 ret = -1;
1444 }
1445
1446 end_no_session:
1447 return ret;
1448 }
1449
1450 /*
1451 * relay_unknown_command: send -1 if received unknown command
1452 */
1453 static void relay_unknown_command(struct relay_connection *conn)
1454 {
1455 struct lttcomm_relayd_generic_reply reply;
1456 ssize_t send_ret;
1457
1458 memset(&reply, 0, sizeof(reply));
1459 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1460 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1461 if (send_ret < sizeof(reply)) {
1462 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret);
1463 }
1464 }
1465
1466 /*
1467 * relay_start: send an acknowledgment to the client to tell if we are
1468 * ready to receive data. We are ready if a session is established.
1469 */
1470 static int relay_start(const struct lttcomm_relayd_hdr *recv_hdr,
1471 struct relay_connection *conn,
1472 const struct lttng_buffer_view *payload)
1473 {
1474 int ret = 0;
1475 ssize_t send_ret;
1476 struct lttcomm_relayd_generic_reply reply;
1477 struct relay_session *session = conn->session;
1478
1479 if (!session) {
1480 DBG("Trying to start the streaming without a session established");
1481 ret = htobe32(LTTNG_ERR_UNK);
1482 }
1483
1484 memset(&reply, 0, sizeof(reply));
1485 reply.ret_code = htobe32(LTTNG_OK);
1486 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1487 sizeof(reply), 0);
1488 if (send_ret < (ssize_t) sizeof(reply)) {
1489 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1490 send_ret);
1491 ret = -1;
1492 }
1493
1494 return ret;
1495 }
1496
1497 /*
1498 * Append padding to the file pointed by the file descriptor fd.
1499 */
1500 static int write_padding_to_file(int fd, uint32_t size)
1501 {
1502 ssize_t ret = 0;
1503 char *zeros;
1504
1505 if (size == 0) {
1506 goto end;
1507 }
1508
1509 zeros = zmalloc(size);
1510 if (zeros == NULL) {
1511 PERROR("zmalloc zeros for padding");
1512 ret = -1;
1513 goto end;
1514 }
1515
1516 ret = lttng_write(fd, zeros, size);
1517 if (ret < size) {
1518 PERROR("write padding to file");
1519 }
1520
1521 free(zeros);
1522
1523 end:
1524 return ret;
1525 }
1526
1527 /*
1528 * Close the current index file if it is open, and create a new one.
1529 *
1530 * Return 0 on success, -1 on error.
1531 */
1532 static
1533 int create_rotate_index_file(struct relay_stream *stream)
1534 {
1535 int ret;
1536 uint32_t major, minor;
1537
1538 /* Put ref on previous index_file. */
1539 if (stream->index_file) {
1540 lttng_index_file_put(stream->index_file);
1541 stream->index_file = NULL;
1542 }
1543 major = stream->trace->session->major;
1544 minor = stream->trace->session->minor;
1545 stream->index_file = lttng_index_file_create(stream->path_name,
1546 stream->channel_name,
1547 -1, -1, stream->tracefile_size,
1548 tracefile_array_get_file_index_head(stream->tfa),
1549 lttng_to_index_major(major, minor),
1550 lttng_to_index_minor(major, minor));
1551 if (!stream->index_file) {
1552 ret = -1;
1553 goto end;
1554 }
1555
1556 ret = 0;
1557
1558 end:
1559 return ret;
1560 }
1561
1562 static
1563 int do_rotate_stream(struct relay_stream *stream)
1564 {
1565 int ret;
1566
1567 /* Perform the stream rotation. */
1568 ret = utils_rotate_stream_file(stream->path_name,
1569 stream->channel_name, stream->tracefile_size,
1570 stream->tracefile_count, -1,
1571 -1, stream->stream_fd->fd,
1572 NULL, &stream->stream_fd->fd);
1573 if (ret < 0) {
1574 ERR("Rotating stream output file");
1575 goto end;
1576 }
1577 stream->tracefile_size_current = 0;
1578
1579 /* Rotate also the index if the stream is not a metadata stream. */
1580 if (!stream->is_metadata) {
1581 ret = create_rotate_index_file(stream);
1582 if (ret < 0) {
1583 ERR("Failed to rotate index file");
1584 goto end;
1585 }
1586 }
1587
1588 stream->rotate_at_seq_num = -1ULL;
1589 stream->pos_after_last_complete_data_index = 0;
1590
1591 end:
1592 return ret;
1593 }
1594
1595 /*
1596 * If too much data has been written in a tracefile before we received the
1597 * rotation command, we have to move the excess data to the new tracefile and
1598 * perform the rotation. This can happen because the control and data
1599 * connections are separate, the indexes as well as the commands arrive from
1600 * the control connection and we have no control over the order so we could be
1601 * in a situation where too much data has been received on the data connection
1602 * before the rotation command on the control connection arrives. We don't need
1603 * to update the index because its order is guaranteed with the rotation
1604 * command message.
1605 */
1606 static
1607 int rotate_truncate_stream(struct relay_stream *stream)
1608 {
1609 int ret, new_fd;
1610 off_t lseek_ret;
1611 uint64_t diff, pos = 0;
1612 char buf[FILE_COPY_BUFFER_SIZE];
1613
1614 assert(!stream->is_metadata);
1615
1616 assert(stream->tracefile_size_current >
1617 stream->pos_after_last_complete_data_index);
1618 diff = stream->tracefile_size_current -
1619 stream->pos_after_last_complete_data_index;
1620
1621 /* Create the new tracefile. */
1622 new_fd = utils_create_stream_file(stream->path_name,
1623 stream->channel_name,
1624 stream->tracefile_size, stream->tracefile_count,
1625 /* uid */ -1, /* gid */ -1, /* suffix */ NULL);
1626 if (new_fd < 0) {
1627 ERR("Failed to create new stream file at path %s for channel %s",
1628 stream->path_name, stream->channel_name);
1629 ret = -1;
1630 goto end;
1631 }
1632
1633 /*
1634 * Rewind the current tracefile to the position at which the rotation
1635 * should have occured.
1636 */
1637 lseek_ret = lseek(stream->stream_fd->fd,
1638 stream->pos_after_last_complete_data_index, SEEK_SET);
1639 if (lseek_ret < 0) {
1640 PERROR("seek truncate stream");
1641 ret = -1;
1642 goto end;
1643 }
1644
1645 /* Move data from the old file to the new file. */
1646 while (pos < diff) {
1647 uint64_t count, bytes_left;
1648 ssize_t io_ret;
1649
1650 bytes_left = diff - pos;
1651 count = bytes_left > sizeof(buf) ? sizeof(buf) : bytes_left;
1652 assert(count <= SIZE_MAX);
1653
1654 io_ret = lttng_read(stream->stream_fd->fd, buf, count);
1655 if (io_ret < (ssize_t) count) {
1656 char error_string[256];
1657
1658 snprintf(error_string, sizeof(error_string),
1659 "Failed to read %" PRIu64 " bytes from fd %i in rotate_truncate_stream(), returned %zi",
1660 count, stream->stream_fd->fd, io_ret);
1661 if (io_ret == -1) {
1662 PERROR("%s", error_string);
1663 } else {
1664 ERR("%s", error_string);
1665 }
1666 ret = -1;
1667 goto end;
1668 }
1669
1670 io_ret = lttng_write(new_fd, buf, count);
1671 if (io_ret < (ssize_t) count) {
1672 char error_string[256];
1673
1674 snprintf(error_string, sizeof(error_string),
1675 "Failed to write %" PRIu64 " bytes from fd %i in rotate_truncate_stream(), returned %zi",
1676 count, new_fd, io_ret);
1677 if (io_ret == -1) {
1678 PERROR("%s", error_string);
1679 } else {
1680 ERR("%s", error_string);
1681 }
1682 ret = -1;
1683 goto end;
1684 }
1685
1686 pos += count;
1687 }
1688
1689 /* Truncate the file to get rid of the excess data. */
1690 ret = ftruncate(stream->stream_fd->fd,
1691 stream->pos_after_last_complete_data_index);
1692 if (ret) {
1693 PERROR("ftruncate");
1694 goto end;
1695 }
1696
1697 ret = close(stream->stream_fd->fd);
1698 if (ret < 0) {
1699 PERROR("Closing tracefile");
1700 goto end;
1701 }
1702
1703 ret = create_rotate_index_file(stream);
1704 if (ret < 0) {
1705 ERR("Rotate stream index file");
1706 goto end;
1707 }
1708
1709 /*
1710 * Update the offset and FD of all the eventual indexes created by the
1711 * data connection before the rotation command arrived.
1712 */
1713 ret = relay_index_switch_all_files(stream);
1714 if (ret < 0) {
1715 ERR("Failed to rotate index file");
1716 goto end;
1717 }
1718
1719 stream->stream_fd->fd = new_fd;
1720 stream->tracefile_size_current = diff;
1721 stream->pos_after_last_complete_data_index = 0;
1722 stream->rotate_at_seq_num = -1ULL;
1723
1724 ret = 0;
1725
1726 end:
1727 return ret;
1728 }
1729
1730 /*
1731 * Check if a stream should perform a rotation (for session rotation).
1732 * Must be called with the stream lock held.
1733 *
1734 * Return 0 on success, a negative value on error.
1735 */
1736 static
1737 int try_rotate_stream(struct relay_stream *stream)
1738 {
1739 int ret = 0;
1740
1741 /* No rotation expected. */
1742 if (stream->rotate_at_seq_num == -1ULL) {
1743 goto end;
1744 }
1745
1746 if (stream->prev_seq < stream->rotate_at_seq_num ||
1747 stream->prev_seq == -1ULL) {
1748 DBG("Stream %" PRIu64 " no yet ready for rotation",
1749 stream->stream_handle);
1750 goto end;
1751 } else if (stream->prev_seq > stream->rotate_at_seq_num) {
1752 DBG("Rotation after too much data has been written in tracefile "
1753 "for stream %" PRIu64 ", need to truncate before "
1754 "rotating", stream->stream_handle);
1755 ret = rotate_truncate_stream(stream);
1756 if (ret) {
1757 ERR("Failed to truncate stream");
1758 goto end;
1759 }
1760 } else {
1761 /* stream->prev_seq == stream->rotate_at_seq_num */
1762 DBG("Stream %" PRIu64 " ready for rotation",
1763 stream->stream_handle);
1764 ret = do_rotate_stream(stream);
1765 }
1766
1767 end:
1768 return ret;
1769 }
1770
1771 /*
1772 * relay_recv_metadata: receive the metadata for the session.
1773 */
1774 static int relay_recv_metadata(const struct lttcomm_relayd_hdr *recv_hdr,
1775 struct relay_connection *conn,
1776 const struct lttng_buffer_view *payload)
1777 {
1778 int ret = 0;
1779 ssize_t size_ret;
1780 struct relay_session *session = conn->session;
1781 struct lttcomm_relayd_metadata_payload metadata_payload_header;
1782 struct relay_stream *metadata_stream;
1783 uint64_t metadata_payload_size;
1784
1785 if (!session) {
1786 ERR("Metadata sent before version check");
1787 ret = -1;
1788 goto end;
1789 }
1790
1791 if (recv_hdr->data_size < sizeof(struct lttcomm_relayd_metadata_payload)) {
1792 ERR("Incorrect data size");
1793 ret = -1;
1794 goto end;
1795 }
1796 metadata_payload_size = recv_hdr->data_size -
1797 sizeof(struct lttcomm_relayd_metadata_payload);
1798
1799 memcpy(&metadata_payload_header, payload->data,
1800 sizeof(metadata_payload_header));
1801 metadata_payload_header.stream_id = be64toh(
1802 metadata_payload_header.stream_id);
1803 metadata_payload_header.padding_size = be32toh(
1804 metadata_payload_header.padding_size);
1805
1806 metadata_stream = stream_get_by_id(metadata_payload_header.stream_id);
1807 if (!metadata_stream) {
1808 ret = -1;
1809 goto end;
1810 }
1811
1812 pthread_mutex_lock(&metadata_stream->lock);
1813
1814 size_ret = lttng_write(metadata_stream->stream_fd->fd,
1815 payload->data + sizeof(metadata_payload_header),
1816 metadata_payload_size);
1817 if (size_ret < metadata_payload_size) {
1818 ERR("Relay error writing metadata on file");
1819 ret = -1;
1820 goto end_put;
1821 }
1822
1823 size_ret = write_padding_to_file(metadata_stream->stream_fd->fd,
1824 metadata_payload_header.padding_size);
1825 if (size_ret < (int64_t) metadata_payload_header.padding_size) {
1826 ret = -1;
1827 goto end_put;
1828 }
1829
1830 metadata_stream->metadata_received +=
1831 metadata_payload_size + metadata_payload_header.padding_size;
1832 DBG2("Relay metadata written. Updated metadata_received %" PRIu64,
1833 metadata_stream->metadata_received);
1834
1835 ret = try_rotate_stream(metadata_stream);
1836 if (ret < 0) {
1837 goto end_put;
1838 }
1839
1840 end_put:
1841 pthread_mutex_unlock(&metadata_stream->lock);
1842 stream_put(metadata_stream);
1843 end:
1844 return ret;
1845 }
1846
1847 /*
1848 * relay_send_version: send relayd version number
1849 */
1850 static int relay_send_version(const struct lttcomm_relayd_hdr *recv_hdr,
1851 struct relay_connection *conn,
1852 const struct lttng_buffer_view *payload)
1853 {
1854 int ret;
1855 ssize_t send_ret;
1856 struct lttcomm_relayd_version reply, msg;
1857 bool compatible = true;
1858
1859 conn->version_check_done = true;
1860
1861 /* Get version from the other side. */
1862 if (payload->size < sizeof(msg)) {
1863 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1864 sizeof(msg), payload->size);
1865 ret = -1;
1866 goto end;
1867 }
1868
1869 memcpy(&msg, payload->data, sizeof(msg));
1870 msg.major = be32toh(msg.major);
1871 msg.minor = be32toh(msg.minor);
1872
1873 memset(&reply, 0, sizeof(reply));
1874 reply.major = RELAYD_VERSION_COMM_MAJOR;
1875 reply.minor = RELAYD_VERSION_COMM_MINOR;
1876
1877 /* Major versions must be the same */
1878 if (reply.major != msg.major) {
1879 DBG("Incompatible major versions (%u vs %u), deleting session",
1880 reply.major, msg.major);
1881 compatible = false;
1882 }
1883
1884 conn->major = reply.major;
1885 /* We adapt to the lowest compatible version */
1886 if (reply.minor <= msg.minor) {
1887 conn->minor = reply.minor;
1888 } else {
1889 conn->minor = msg.minor;
1890 }
1891
1892 reply.major = htobe32(reply.major);
1893 reply.minor = htobe32(reply.minor);
1894 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1895 sizeof(reply), 0);
1896 if (send_ret < (ssize_t) sizeof(reply)) {
1897 ERR("Failed to send \"send version\" command reply (ret = %zd)",
1898 send_ret);
1899 ret = -1;
1900 goto end;
1901 } else {
1902 ret = 0;
1903 }
1904
1905 if (!compatible) {
1906 ret = -1;
1907 goto end;
1908 }
1909
1910 DBG("Version check done using protocol %u.%u", conn->major,
1911 conn->minor);
1912
1913 end:
1914 return ret;
1915 }
1916
1917 /*
1918 * Check for data pending for a given stream id from the session daemon.
1919 */
1920 static int relay_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
1921 struct relay_connection *conn,
1922 const struct lttng_buffer_view *payload)
1923 {
1924 struct relay_session *session = conn->session;
1925 struct lttcomm_relayd_data_pending msg;
1926 struct lttcomm_relayd_generic_reply reply;
1927 struct relay_stream *stream;
1928 ssize_t send_ret;
1929 int ret;
1930
1931 DBG("Data pending command received");
1932
1933 if (!session || !conn->version_check_done) {
1934 ERR("Trying to check for data before version check");
1935 ret = -1;
1936 goto end_no_session;
1937 }
1938
1939 if (payload->size < sizeof(msg)) {
1940 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
1941 sizeof(msg), payload->size);
1942 ret = -1;
1943 goto end_no_session;
1944 }
1945 memcpy(&msg, payload->data, sizeof(msg));
1946 msg.stream_id = be64toh(msg.stream_id);
1947 msg.last_net_seq_num = be64toh(msg.last_net_seq_num);
1948
1949 stream = stream_get_by_id(msg.stream_id);
1950 if (stream == NULL) {
1951 ret = -1;
1952 goto end;
1953 }
1954
1955 pthread_mutex_lock(&stream->lock);
1956
1957 DBG("Data pending for stream id %" PRIu64 " prev_seq %" PRIu64
1958 " and last_seq %" PRIu64, msg.stream_id,
1959 stream->prev_seq, msg.last_net_seq_num);
1960
1961 /* Avoid wrapping issue */
1962 if (((int64_t) (stream->prev_seq - msg.last_net_seq_num)) >= 0) {
1963 /* Data has in fact been written and is NOT pending */
1964 ret = 0;
1965 } else {
1966 /* Data still being streamed thus pending */
1967 ret = 1;
1968 }
1969
1970 stream->data_pending_check_done = true;
1971 pthread_mutex_unlock(&stream->lock);
1972
1973 stream_put(stream);
1974 end:
1975
1976 memset(&reply, 0, sizeof(reply));
1977 reply.ret_code = htobe32(ret);
1978 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1979 if (send_ret < (ssize_t) sizeof(reply)) {
1980 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
1981 send_ret);
1982 ret = -1;
1983 }
1984
1985 end_no_session:
1986 return ret;
1987 }
1988
1989 /*
1990 * Wait for the control socket to reach a quiescent state.
1991 *
1992 * Note that for now, when receiving this command from the session
1993 * daemon, this means that every subsequent commands or data received on
1994 * the control socket has been handled. So, this is why we simply return
1995 * OK here.
1996 */
1997 static int relay_quiescent_control(const struct lttcomm_relayd_hdr *recv_hdr,
1998 struct relay_connection *conn,
1999 const struct lttng_buffer_view *payload)
2000 {
2001 int ret;
2002 ssize_t send_ret;
2003 struct relay_stream *stream;
2004 struct lttcomm_relayd_quiescent_control msg;
2005 struct lttcomm_relayd_generic_reply reply;
2006
2007 DBG("Checking quiescent state on control socket");
2008
2009 if (!conn->session || !conn->version_check_done) {
2010 ERR("Trying to check for data before version check");
2011 ret = -1;
2012 goto end_no_session;
2013 }
2014
2015 if (payload->size < sizeof(msg)) {
2016 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2017 sizeof(msg), payload->size);
2018 ret = -1;
2019 goto end_no_session;
2020 }
2021 memcpy(&msg, payload->data, sizeof(msg));
2022 msg.stream_id = be64toh(msg.stream_id);
2023
2024 stream = stream_get_by_id(msg.stream_id);
2025 if (!stream) {
2026 goto reply;
2027 }
2028 pthread_mutex_lock(&stream->lock);
2029 stream->data_pending_check_done = true;
2030 pthread_mutex_unlock(&stream->lock);
2031
2032 DBG("Relay quiescent control pending flag set to %" PRIu64, msg.stream_id);
2033 stream_put(stream);
2034 reply:
2035 memset(&reply, 0, sizeof(reply));
2036 reply.ret_code = htobe32(LTTNG_OK);
2037 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2038 if (send_ret < (ssize_t) sizeof(reply)) {
2039 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
2040 send_ret);
2041 ret = -1;
2042 } else {
2043 ret = 0;
2044 }
2045
2046 end_no_session:
2047 return ret;
2048 }
2049
2050 /*
2051 * Initialize a data pending command. This means that a consumer is about
2052 * to ask for data pending for each stream it holds. Simply iterate over
2053 * all streams of a session and set the data_pending_check_done flag.
2054 *
2055 * This command returns to the client a LTTNG_OK code.
2056 */
2057 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
2058 struct relay_connection *conn,
2059 const struct lttng_buffer_view *payload)
2060 {
2061 int ret;
2062 ssize_t send_ret;
2063 struct lttng_ht_iter iter;
2064 struct lttcomm_relayd_begin_data_pending msg;
2065 struct lttcomm_relayd_generic_reply reply;
2066 struct relay_stream *stream;
2067
2068 assert(recv_hdr);
2069 assert(conn);
2070
2071 DBG("Init streams for data pending");
2072
2073 if (!conn->session || !conn->version_check_done) {
2074 ERR("Trying to check for data before version check");
2075 ret = -1;
2076 goto end_no_session;
2077 }
2078
2079 if (payload->size < sizeof(msg)) {
2080 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2081 sizeof(msg), payload->size);
2082 ret = -1;
2083 goto end_no_session;
2084 }
2085 memcpy(&msg, payload->data, sizeof(msg));
2086 msg.session_id = be64toh(msg.session_id);
2087
2088 /*
2089 * Iterate over all streams to set the begin data pending flag.
2090 * For now, the streams are indexed by stream handle so we have
2091 * to iterate over all streams to find the one associated with
2092 * the right session_id.
2093 */
2094 rcu_read_lock();
2095 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2096 node.node) {
2097 if (!stream_get(stream)) {
2098 continue;
2099 }
2100 if (stream->trace->session->id == msg.session_id) {
2101 pthread_mutex_lock(&stream->lock);
2102 stream->data_pending_check_done = false;
2103 pthread_mutex_unlock(&stream->lock);
2104 DBG("Set begin data pending flag to stream %" PRIu64,
2105 stream->stream_handle);
2106 }
2107 stream_put(stream);
2108 }
2109 rcu_read_unlock();
2110
2111 memset(&reply, 0, sizeof(reply));
2112 /* All good, send back reply. */
2113 reply.ret_code = htobe32(LTTNG_OK);
2114
2115 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2116 if (send_ret < (ssize_t) sizeof(reply)) {
2117 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2118 send_ret);
2119 ret = -1;
2120 } else {
2121 ret = 0;
2122 }
2123
2124 end_no_session:
2125 return ret;
2126 }
2127
2128 /*
2129 * End data pending command. This will check, for a given session id, if
2130 * each stream associated with it has its data_pending_check_done flag
2131 * set. If not, this means that the client lost track of the stream but
2132 * the data is still being streamed on our side. In this case, we inform
2133 * the client that data is in flight.
2134 *
2135 * Return to the client if there is data in flight or not with a ret_code.
2136 */
2137 static int relay_end_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
2138 struct relay_connection *conn,
2139 const struct lttng_buffer_view *payload)
2140 {
2141 int ret;
2142 ssize_t send_ret;
2143 struct lttng_ht_iter iter;
2144 struct lttcomm_relayd_end_data_pending msg;
2145 struct lttcomm_relayd_generic_reply reply;
2146 struct relay_stream *stream;
2147 uint32_t is_data_inflight = 0;
2148
2149 DBG("End data pending command");
2150
2151 if (!conn->session || !conn->version_check_done) {
2152 ERR("Trying to check for data before version check");
2153 ret = -1;
2154 goto end_no_session;
2155 }
2156
2157 if (payload->size < sizeof(msg)) {
2158 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2159 sizeof(msg), payload->size);
2160 ret = -1;
2161 goto end_no_session;
2162 }
2163 memcpy(&msg, payload->data, sizeof(msg));
2164 msg.session_id = be64toh(msg.session_id);
2165
2166 /*
2167 * Iterate over all streams to see if the begin data pending
2168 * flag is set.
2169 */
2170 rcu_read_lock();
2171 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2172 node.node) {
2173 if (!stream_get(stream)) {
2174 continue;
2175 }
2176 if (stream->trace->session->id != msg.session_id) {
2177 stream_put(stream);
2178 continue;
2179 }
2180 pthread_mutex_lock(&stream->lock);
2181 if (!stream->data_pending_check_done) {
2182 if (!stream->closed || !(((int64_t) (stream->prev_seq - stream->last_net_seq_num)) >= 0)) {
2183 is_data_inflight = 1;
2184 DBG("Data is still in flight for stream %" PRIu64,
2185 stream->stream_handle);
2186 pthread_mutex_unlock(&stream->lock);
2187 stream_put(stream);
2188 break;
2189 }
2190 }
2191 pthread_mutex_unlock(&stream->lock);
2192 stream_put(stream);
2193 }
2194 rcu_read_unlock();
2195
2196 memset(&reply, 0, sizeof(reply));
2197 /* All good, send back reply. */
2198 reply.ret_code = htobe32(is_data_inflight);
2199
2200 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2201 if (send_ret < (ssize_t) sizeof(reply)) {
2202 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2203 send_ret);
2204 ret = -1;
2205 } else {
2206 ret = 0;
2207 }
2208
2209 end_no_session:
2210 return ret;
2211 }
2212
2213 /*
2214 * Receive an index for a specific stream.
2215 *
2216 * Return 0 on success else a negative value.
2217 */
2218 static int relay_recv_index(const struct lttcomm_relayd_hdr *recv_hdr,
2219 struct relay_connection *conn,
2220 const struct lttng_buffer_view *payload)
2221 {
2222 int ret;
2223 ssize_t send_ret;
2224 struct relay_session *session = conn->session;
2225 struct lttcomm_relayd_index index_info;
2226 struct relay_index *index;
2227 struct lttcomm_relayd_generic_reply reply;
2228 struct relay_stream *stream;
2229 size_t msg_len;
2230
2231 assert(conn);
2232
2233 DBG("Relay receiving index");
2234
2235 if (!session || !conn->version_check_done) {
2236 ERR("Trying to close a stream before version check");
2237 ret = -1;
2238 goto end_no_session;
2239 }
2240
2241 msg_len = lttcomm_relayd_index_len(
2242 lttng_to_index_major(conn->major, conn->minor),
2243 lttng_to_index_minor(conn->major, conn->minor));
2244 if (payload->size < msg_len) {
2245 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2246 msg_len, payload->size);
2247 ret = -1;
2248 goto end_no_session;
2249 }
2250 memcpy(&index_info, payload->data, msg_len);
2251 index_info.relay_stream_id = be64toh(index_info.relay_stream_id);
2252 index_info.net_seq_num = be64toh(index_info.net_seq_num);
2253 index_info.packet_size = be64toh(index_info.packet_size);
2254 index_info.content_size = be64toh(index_info.content_size);
2255 index_info.timestamp_begin = be64toh(index_info.timestamp_begin);
2256 index_info.timestamp_end = be64toh(index_info.timestamp_end);
2257 index_info.events_discarded = be64toh(index_info.events_discarded);
2258 index_info.stream_id = be64toh(index_info.stream_id);
2259
2260 if (conn->minor >= 8) {
2261 index_info.stream_instance_id =
2262 be64toh(index_info.stream_instance_id);
2263 index_info.packet_seq_num = be64toh(index_info.packet_seq_num);
2264 }
2265
2266 stream = stream_get_by_id(index_info.relay_stream_id);
2267 if (!stream) {
2268 ERR("stream_get_by_id not found");
2269 ret = -1;
2270 goto end;
2271 }
2272 pthread_mutex_lock(&stream->lock);
2273
2274 /* Live beacon handling */
2275 if (index_info.packet_size == 0) {
2276 DBG("Received live beacon for stream %" PRIu64,
2277 stream->stream_handle);
2278
2279 /*
2280 * Only flag a stream inactive when it has already
2281 * received data and no indexes are in flight.
2282 */
2283 if (stream->index_received_seqcount > 0
2284 && stream->indexes_in_flight == 0) {
2285 stream->beacon_ts_end = index_info.timestamp_end;
2286 }
2287 ret = 0;
2288 goto end_stream_put;
2289 } else {
2290 stream->beacon_ts_end = -1ULL;
2291 }
2292
2293 if (stream->ctf_stream_id == -1ULL) {
2294 stream->ctf_stream_id = index_info.stream_id;
2295 }
2296 index = relay_index_get_by_id_or_create(stream, index_info.net_seq_num);
2297 if (!index) {
2298 ret = -1;
2299 ERR("relay_index_get_by_id_or_create index NULL");
2300 goto end_stream_put;
2301 }
2302 if (set_index_control_data(index, &index_info, conn)) {
2303 ERR("set_index_control_data error");
2304 relay_index_put(index);
2305 ret = -1;
2306 goto end_stream_put;
2307 }
2308 ret = relay_index_try_flush(index);
2309 if (ret == 0) {
2310 tracefile_array_commit_seq(stream->tfa);
2311 stream->index_received_seqcount++;
2312 stream->pos_after_last_complete_data_index += index->total_size;
2313 } else if (ret > 0) {
2314 /* no flush. */
2315 ret = 0;
2316 } else {
2317 ERR("relay_index_try_flush error %d", ret);
2318 relay_index_put(index);
2319 ret = -1;
2320 }
2321
2322 end_stream_put:
2323 pthread_mutex_unlock(&stream->lock);
2324 stream_put(stream);
2325
2326 end:
2327
2328 memset(&reply, 0, sizeof(reply));
2329 if (ret < 0) {
2330 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2331 } else {
2332 reply.ret_code = htobe32(LTTNG_OK);
2333 }
2334 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2335 if (send_ret < (ssize_t) sizeof(reply)) {
2336 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret);
2337 ret = -1;
2338 }
2339
2340 end_no_session:
2341 return ret;
2342 }
2343
2344 /*
2345 * Receive the streams_sent message.
2346 *
2347 * Return 0 on success else a negative value.
2348 */
2349 static int relay_streams_sent(const struct lttcomm_relayd_hdr *recv_hdr,
2350 struct relay_connection *conn,
2351 const struct lttng_buffer_view *payload)
2352 {
2353 int ret;
2354 ssize_t send_ret;
2355 struct lttcomm_relayd_generic_reply reply;
2356
2357 assert(conn);
2358
2359 DBG("Relay receiving streams_sent");
2360
2361 if (!conn->session || !conn->version_check_done) {
2362 ERR("Trying to close a stream before version check");
2363 ret = -1;
2364 goto end_no_session;
2365 }
2366
2367 /*
2368 * Publish every pending stream in the connection recv list which are
2369 * now ready to be used by the viewer.
2370 */
2371 publish_connection_local_streams(conn);
2372
2373 memset(&reply, 0, sizeof(reply));
2374 reply.ret_code = htobe32(LTTNG_OK);
2375 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2376 if (send_ret < (ssize_t) sizeof(reply)) {
2377 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2378 send_ret);
2379 ret = -1;
2380 } else {
2381 /* Success. */
2382 ret = 0;
2383 }
2384
2385 end_no_session:
2386 return ret;
2387 }
2388
2389 /*
2390 * relay_rotate_session_stream: rotate a stream to a new tracefile for the session
2391 * rotation feature (not the tracefile rotation feature).
2392 */
2393 static int relay_rotate_session_stream(const struct lttcomm_relayd_hdr *recv_hdr,
2394 struct relay_connection *conn,
2395 const struct lttng_buffer_view *payload)
2396 {
2397 int ret;
2398 ssize_t send_ret;
2399 struct relay_session *session = conn->session;
2400 struct lttcomm_relayd_rotate_stream stream_info;
2401 struct lttcomm_relayd_generic_reply reply;
2402 struct relay_stream *stream;
2403 size_t header_len;
2404 size_t path_len;
2405 struct lttng_buffer_view new_path_view;
2406
2407 DBG("Rotate stream received");
2408
2409 if (!session || !conn->version_check_done) {
2410 ERR("Trying to rotate a stream before version check");
2411 ret = -1;
2412 goto end_no_reply;
2413 }
2414
2415 if (session->major == 2 && session->minor < 11) {
2416 ERR("Unsupported feature before 2.11");
2417 ret = -1;
2418 goto end_no_reply;
2419 }
2420
2421 header_len = sizeof(struct lttcomm_relayd_rotate_stream);
2422
2423 if (payload->size < header_len) {
2424 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2425 header_len, payload->size);
2426 ret = -1;
2427 goto end_no_reply;
2428 }
2429
2430 memcpy(&stream_info, payload->data, header_len);
2431
2432 /* Convert to host */
2433 stream_info.pathname_length = be32toh(stream_info.pathname_length);
2434 stream_info.stream_id = be64toh(stream_info.stream_id);
2435 stream_info.new_chunk_id = be64toh(stream_info.new_chunk_id);
2436 stream_info.rotate_at_seq_num = be64toh(stream_info.rotate_at_seq_num);
2437
2438 path_len = stream_info.pathname_length;
2439 if (payload->size < header_len + path_len) {
2440 ERR("Unexpected payload size in \"relay_rotate_session_stream\" including path: expected >= %zu bytes, got %zu bytes",
2441 header_len + path_len, payload->size);
2442 ret = -1;
2443 goto end_no_reply;
2444 }
2445
2446 /* Ensure it fits in local filename length. */
2447 if (path_len >= LTTNG_PATH_MAX) {
2448 ret = -ENAMETOOLONG;
2449 ERR("Length of relay_rotate_session_stream command's path name (%zu bytes) exceeds the maximal allowed length of %i bytes",
2450 path_len, LTTNG_PATH_MAX);
2451 goto end;
2452 }
2453
2454 new_path_view = lttng_buffer_view_from_view(payload, header_len,
2455 stream_info.pathname_length);
2456
2457 stream = stream_get_by_id(stream_info.stream_id);
2458 if (!stream) {
2459 ret = -1;
2460 goto end;
2461 }
2462
2463 pthread_mutex_lock(&stream->lock);
2464
2465 /*
2466 * Update the trace path (just the folder, the stream name does not
2467 * change).
2468 */
2469 free(stream->path_name);
2470 stream->path_name = create_output_path(new_path_view.data);
2471 if (!stream->path_name) {
2472 ERR("Failed to create a new output path");
2473 ret = -1;
2474 goto end_stream_unlock;
2475 }
2476 ret = utils_mkdir_recursive(stream->path_name, S_IRWXU | S_IRWXG,
2477 -1, -1);
2478 if (ret < 0) {
2479 ERR("relay creating output directory");
2480 ret = -1;
2481 goto end_stream_unlock;
2482 }
2483
2484 stream->chunk_id = stream_info.new_chunk_id;
2485
2486 if (stream->is_metadata) {
2487 /*
2488 * The metadata stream is sent only over the control connection
2489 * so we know we have all the data to perform the stream
2490 * rotation.
2491 */
2492 ret = do_rotate_stream(stream);
2493 } else {
2494 stream->rotate_at_seq_num = stream_info.rotate_at_seq_num;
2495 ret = try_rotate_stream(stream);
2496 }
2497 if (ret < 0) {
2498 goto end_stream_unlock;
2499 }
2500
2501 end_stream_unlock:
2502 pthread_mutex_unlock(&stream->lock);
2503 stream_put(stream);
2504 end:
2505 memset(&reply, 0, sizeof(reply));
2506 if (ret < 0) {
2507 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2508 } else {
2509 reply.ret_code = htobe32(LTTNG_OK);
2510 }
2511 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
2512 sizeof(struct lttcomm_relayd_generic_reply), 0);
2513 if (send_ret < (ssize_t) sizeof(reply)) {
2514 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2515 send_ret);
2516 ret = -1;
2517 }
2518
2519 end_no_reply:
2520 return ret;
2521 }
2522
2523 /*
2524 * relay_mkdir: Create a folder on the disk.
2525 */
2526 static int relay_mkdir(const struct lttcomm_relayd_hdr *recv_hdr,
2527 struct relay_connection *conn,
2528 const struct lttng_buffer_view *payload)
2529 {
2530 int ret;
2531 struct relay_session *session = conn->session;
2532 struct lttcomm_relayd_mkdir path_info_header;
2533 struct lttcomm_relayd_generic_reply reply;
2534 char *path = NULL;
2535 size_t header_len;
2536 ssize_t send_ret;
2537 struct lttng_buffer_view path_view;
2538
2539 if (!session || !conn->version_check_done) {
2540 ERR("Trying to create a directory before version check");
2541 ret = -1;
2542 goto end_no_session;
2543 }
2544
2545 if (session->major == 2 && session->minor < 11) {
2546 /*
2547 * This client is not supposed to use this command since
2548 * it predates its introduction.
2549 */
2550 ERR("relay_mkdir command is unsupported before LTTng 2.11");
2551 ret = -1;
2552 goto end_no_session;
2553 }
2554
2555 header_len = sizeof(path_info_header);
2556 if (payload->size < header_len) {
2557 ERR("Unexpected payload size in \"relay_mkdir\": expected >= %zu bytes, got %zu bytes",
2558 header_len, payload->size);
2559 ret = -1;
2560 goto end_no_session;
2561 }
2562
2563 memcpy(&path_info_header, payload->data, header_len);
2564
2565 path_info_header.length = be32toh(path_info_header.length);
2566
2567 if (payload->size < header_len + path_info_header.length) {
2568 ERR("Unexpected payload size in \"relay_mkdir\" including path: expected >= %zu bytes, got %zu bytes",
2569 header_len + path_info_header.length, payload->size);
2570 ret = -1;
2571 goto end_no_session;
2572 }
2573
2574 /* Ensure that it fits in local path length. */
2575 if (path_info_header.length >= LTTNG_PATH_MAX) {
2576 ret = -ENAMETOOLONG;
2577 ERR("Path name argument of mkdir command (%" PRIu32 " bytes) exceeds the maximal length allowed (%d bytes)",
2578 path_info_header.length, LTTNG_PATH_MAX);
2579 goto end;
2580 }
2581
2582 path_view = lttng_buffer_view_from_view(payload, header_len,
2583 path_info_header.length);
2584
2585 path = create_output_path(path_view.data);
2586 if (!path) {
2587 ERR("Failed to create output path");
2588 ret = -1;
2589 goto end;
2590 }
2591
2592 ret = utils_mkdir_recursive(path, S_IRWXU | S_IRWXG, -1, -1);
2593 if (ret < 0) {
2594 ERR("relay creating output directory");
2595 goto end;
2596 }
2597
2598 ret = 0;
2599
2600 end:
2601 memset(&reply, 0, sizeof(reply));
2602 if (ret < 0) {
2603 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2604 } else {
2605 reply.ret_code = htobe32(LTTNG_OK);
2606 }
2607 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2608 if (send_ret < (ssize_t) sizeof(reply)) {
2609 ERR("Failed to send \"mkdir\" command reply (ret = %zd)", send_ret);
2610 ret = -1;
2611 }
2612
2613 end_no_session:
2614 free(path);
2615 return ret;
2616 }
2617
2618 static int validate_rotate_rename_path_length(const char *path_type,
2619 uint32_t path_length)
2620 {
2621 int ret = 0;
2622
2623 if (path_length > LTTNG_PATH_MAX) {
2624 ret = -ENAMETOOLONG;
2625 ERR("rotate rename \"%s\" path name length (%" PRIu32 " bytes) exceeds the allowed size of %i bytes",
2626 path_type, path_length, LTTNG_PATH_MAX);
2627 } else if (path_length == 0) {
2628 ret = -EINVAL;
2629 ERR("rotate rename \"%s\" path name has an illegal length of 0", path_type);
2630 }
2631 return ret;
2632 }
2633
2634 /*
2635 * relay_rotate_rename: rename the trace folder after a rotation is
2636 * completed. We are not closing any fd here, just moving the folder, so it
2637 * works even if data is still in-flight.
2638 */
2639 static int relay_rotate_rename(const struct lttcomm_relayd_hdr *recv_hdr,
2640 struct relay_connection *conn,
2641 const struct lttng_buffer_view *payload)
2642 {
2643 int ret;
2644 ssize_t send_ret;
2645 struct relay_session *session = conn->session;
2646 struct lttcomm_relayd_generic_reply reply;
2647 struct lttcomm_relayd_rotate_rename header;
2648 size_t header_len;
2649 size_t received_paths_size;
2650 char *complete_old_path = NULL, *complete_new_path = NULL;
2651 struct lttng_buffer_view old_path_view;
2652 struct lttng_buffer_view new_path_view;
2653
2654 if (!session || !conn->version_check_done) {
2655 ERR("Trying to rename a trace folder before version check");
2656 ret = -1;
2657 goto end_no_reply;
2658 }
2659
2660 if (session->major == 2 && session->minor < 11) {
2661 ERR("relay_rotate_rename command is unsupported before LTTng 2.11");
2662 ret = -1;
2663 goto end_no_reply;
2664 }
2665
2666 header_len = sizeof(header);
2667 if (payload->size < header_len) {
2668 ERR("Unexpected payload size in \"relay_rotate_rename\": expected >= %zu bytes, got %zu bytes",
2669 header_len, payload->size);
2670 ret = -1;
2671 goto end_no_reply;
2672 }
2673
2674 memcpy(&header, payload->data, header_len);
2675
2676 header.old_path_length = be32toh(header.old_path_length);
2677 header.new_path_length = be32toh(header.new_path_length);
2678 received_paths_size = header.old_path_length + header.new_path_length;
2679
2680 if (payload->size < header_len + received_paths_size) {
2681 ERR("Unexpected payload size in \"relay_rotate_rename\" including paths: expected >= %zu bytes, got %zu bytes",
2682 header_len, payload->size);
2683 ret = -1;
2684 goto end_no_reply;
2685 }
2686
2687 /* Ensure the paths don't exceed their allowed size. */
2688 ret = validate_rotate_rename_path_length("old", header.old_path_length);
2689 if (ret) {
2690 goto end;
2691 }
2692 ret = validate_rotate_rename_path_length("new", header.new_path_length);
2693 if (ret) {
2694 goto end;
2695 }
2696
2697 old_path_view = lttng_buffer_view_from_view(payload, header_len,
2698 header.old_path_length);
2699 new_path_view = lttng_buffer_view_from_view(payload,
2700 header_len + header.old_path_length,
2701 header.new_path_length);
2702
2703 /* Validate that both paths received are NULL terminated. */
2704 if (old_path_view.data[old_path_view.size - 1] != '\0') {
2705 ERR("relay_rotate_rename command's \"old\" path is invalid (not NULL terminated)");
2706 ret = -1;
2707 goto end;
2708 }
2709 if (new_path_view.data[new_path_view.size - 1] != '\0') {
2710 ERR("relay_rotate_rename command's \"new\" path is invalid (not NULL terminated)");
2711 ret = -1;
2712 goto end;
2713 }
2714
2715 complete_old_path = create_output_path(old_path_view.data);
2716 if (!complete_old_path) {
2717 ERR("Failed to build old output path in rotate_rename command");
2718 ret = -1;
2719 goto end;
2720 }
2721
2722 complete_new_path = create_output_path(new_path_view.data);
2723 if (!complete_new_path) {
2724 ERR("Failed to build new output path in rotate_rename command");
2725 ret = -1;
2726 goto end;
2727 }
2728
2729 ret = utils_mkdir_recursive(complete_new_path, S_IRWXU | S_IRWXG,
2730 -1, -1);
2731 if (ret < 0) {
2732 ERR("Failed to mkdir() rotate_rename's \"new\" output directory at \"%s\"",
2733 complete_new_path);
2734 goto end;
2735 }
2736
2737 /*
2738 * If a domain has not yet created its channel, the domain-specific
2739 * folder might not exist, but this is not an error.
2740 */
2741 ret = rename(complete_old_path, complete_new_path);
2742 if (ret < 0 && errno != ENOENT) {
2743 PERROR("Renaming chunk in rotate_rename command from \"%s\" to \"%s\"",
2744 complete_old_path, complete_new_path);
2745 goto end;
2746 }
2747 ret = 0;
2748
2749 end:
2750 memset(&reply, 0, sizeof(reply));
2751 if (ret < 0) {
2752 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2753 } else {
2754 reply.ret_code = htobe32(LTTNG_OK);
2755 }
2756 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
2757 sizeof(reply), 0);
2758 if (send_ret < sizeof(reply)) {
2759 ERR("Failed to send \"rotate rename\" command reply (ret = %zd)",
2760 send_ret);
2761 ret = -1;
2762 }
2763
2764 end_no_reply:
2765 free(complete_old_path);
2766 free(complete_new_path);
2767 return ret;
2768 }
2769
2770 /*
2771 * Check if all the streams in the session have completed the last rotation.
2772 * The chunk_id value is used to distinguish the cases where a stream was
2773 * closed on the consumerd before the rotation started but it still active on
2774 * the relayd, and the case where a stream appeared on the consumerd/relayd
2775 * after the last rotation started (in that case, it is already writing in the
2776 * new chunk folder).
2777 */
2778 static
2779 int relay_rotate_pending(const struct lttcomm_relayd_hdr *recv_hdr,
2780 struct relay_connection *conn,
2781 const struct lttng_buffer_view *payload)
2782 {
2783 struct relay_session *session = conn->session;
2784 struct lttcomm_relayd_rotate_pending msg;
2785 struct lttcomm_relayd_rotate_pending_reply reply;
2786 struct lttng_ht_iter iter;
2787 struct relay_stream *stream;
2788 int ret = 0;
2789 ssize_t send_ret;
2790 uint64_t chunk_id;
2791 bool rotate_pending = false;
2792
2793 DBG("Rotate pending command received");
2794
2795 if (!session || !conn->version_check_done) {
2796 ERR("Trying to check for data before version check");
2797 ret = -1;
2798 goto end_no_reply;
2799 }
2800
2801 if (session->major == 2 && session->minor < 11) {
2802 ERR("Unsupported feature before 2.11");
2803 ret = -1;
2804 goto end_no_reply;
2805 }
2806
2807 if (payload->size < sizeof(msg)) {
2808 ERR("Unexpected payload size in \"relay_rotate_pending\": expected >= %zu bytes, got %zu bytes",
2809 sizeof(msg), payload->size);
2810 ret = -1;
2811 goto end_no_reply;
2812 }
2813
2814 memcpy(&msg, payload->data, sizeof(msg));
2815
2816 chunk_id = be64toh(msg.chunk_id);
2817
2818 DBG("Evaluating rotate pending for chunk id %" PRIu64, chunk_id);
2819
2820 /*
2821 * Iterate over all the streams in the session and check if they are
2822 * still waiting for data to perform their rotation.
2823 */
2824 rcu_read_lock();
2825 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2826 node.node) {
2827 if (!stream_get(stream)) {
2828 continue;
2829 }
2830 if (stream->trace->session != session) {
2831 stream_put(stream);
2832 continue;
2833 }
2834 pthread_mutex_lock(&stream->lock);
2835 if (stream->rotate_at_seq_num != -1ULL) {
2836 /* We have not yet performed the rotation. */
2837 rotate_pending = true;
2838 DBG("Stream %" PRIu64 " is still rotating",
2839 stream->stream_handle);
2840 } else if (stream->chunk_id < chunk_id) {
2841 /*
2842 * Stream closed on the consumer but still active on the
2843 * relay.
2844 */
2845 rotate_pending = true;
2846 DBG("Stream %" PRIu64 " did not exist on the consumer "
2847 "when the last rotation started, but is"
2848 "still waiting for data before getting"
2849 "closed",
2850 stream->stream_handle);
2851 }
2852 pthread_mutex_unlock(&stream->lock);
2853 stream_put(stream);
2854 if (rotate_pending) {
2855 goto send_reply;
2856 }
2857 }
2858
2859 send_reply:
2860 rcu_read_unlock();
2861 memset(&reply, 0, sizeof(reply));
2862 reply.generic.ret_code = htobe32((uint32_t) LTTNG_OK);
2863 reply.is_pending = (uint8_t) !!rotate_pending;
2864 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
2865 sizeof(reply), 0);
2866 if (send_ret < (ssize_t) sizeof(reply)) {
2867 ERR("Failed to send \"rotate pending\" command reply (ret = %zd)",
2868 send_ret);
2869 ret = -1;
2870 }
2871
2872 end_no_reply:
2873 return ret;
2874 }
2875
2876 #define DBG_CMD(cmd_name, conn) \
2877 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
2878
2879 static int relay_process_control_command(struct relay_connection *conn,
2880 const struct lttcomm_relayd_hdr *header,
2881 const struct lttng_buffer_view *payload)
2882 {
2883 int ret = 0;
2884
2885 switch (header->cmd) {
2886 case RELAYD_CREATE_SESSION:
2887 DBG_CMD("RELAYD_CREATE_SESSION", conn);
2888 ret = relay_create_session(header, conn, payload);
2889 break;
2890 case RELAYD_ADD_STREAM:
2891 DBG_CMD("RELAYD_ADD_STREAM", conn);
2892 ret = relay_add_stream(header, conn, payload);
2893 break;
2894 case RELAYD_START_DATA:
2895 DBG_CMD("RELAYD_START_DATA", conn);
2896 ret = relay_start(header, conn, payload);
2897 break;
2898 case RELAYD_SEND_METADATA:
2899 DBG_CMD("RELAYD_SEND_METADATA", conn);
2900 ret = relay_recv_metadata(header, conn, payload);
2901 break;
2902 case RELAYD_VERSION:
2903 DBG_CMD("RELAYD_VERSION", conn);
2904 ret = relay_send_version(header, conn, payload);
2905 break;
2906 case RELAYD_CLOSE_STREAM:
2907 DBG_CMD("RELAYD_CLOSE_STREAM", conn);
2908 ret = relay_close_stream(header, conn, payload);
2909 break;
2910 case RELAYD_DATA_PENDING:
2911 DBG_CMD("RELAYD_DATA_PENDING", conn);
2912 ret = relay_data_pending(header, conn, payload);
2913 break;
2914 case RELAYD_QUIESCENT_CONTROL:
2915 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn);
2916 ret = relay_quiescent_control(header, conn, payload);
2917 break;
2918 case RELAYD_BEGIN_DATA_PENDING:
2919 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn);
2920 ret = relay_begin_data_pending(header, conn, payload);
2921 break;
2922 case RELAYD_END_DATA_PENDING:
2923 DBG_CMD("RELAYD_END_DATA_PENDING", conn);
2924 ret = relay_end_data_pending(header, conn, payload);
2925 break;
2926 case RELAYD_SEND_INDEX:
2927 DBG_CMD("RELAYD_SEND_INDEX", conn);
2928 ret = relay_recv_index(header, conn, payload);
2929 break;
2930 case RELAYD_STREAMS_SENT:
2931 DBG_CMD("RELAYD_STREAMS_SENT", conn);
2932 ret = relay_streams_sent(header, conn, payload);
2933 break;
2934 case RELAYD_RESET_METADATA:
2935 DBG_CMD("RELAYD_RESET_METADATA", conn);
2936 ret = relay_reset_metadata(header, conn, payload);
2937 break;
2938 case RELAYD_ROTATE_STREAM:
2939 DBG_CMD("RELAYD_ROTATE_STREAM", conn);
2940 ret = relay_rotate_session_stream(header, conn, payload);
2941 break;
2942 case RELAYD_ROTATE_RENAME:
2943 DBG_CMD("RELAYD_ROTATE_RENAME", conn);
2944 ret = relay_rotate_rename(header, conn, payload);
2945 break;
2946 case RELAYD_ROTATE_PENDING:
2947 DBG_CMD("RELAYD_ROTATE_PENDING", conn);
2948 ret = relay_rotate_pending(header, conn, payload);
2949 break;
2950 case RELAYD_MKDIR:
2951 DBG_CMD("RELAYD_MKDIR", conn);
2952 ret = relay_mkdir(header, conn, payload);
2953 break;
2954 case RELAYD_UPDATE_SYNC_INFO:
2955 default:
2956 ERR("Received unknown command (%u)", header->cmd);
2957 relay_unknown_command(conn);
2958 ret = -1;
2959 goto end;
2960 }
2961
2962 end:
2963 return ret;
2964 }
2965
2966 static enum relay_connection_status relay_process_control_receive_payload(
2967 struct relay_connection *conn)
2968 {
2969 int ret = 0;
2970 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
2971 struct lttng_dynamic_buffer *reception_buffer =
2972 &conn->protocol.ctrl.reception_buffer;
2973 struct ctrl_connection_state_receive_payload *state =
2974 &conn->protocol.ctrl.state.receive_payload;
2975 struct lttng_buffer_view payload_view;
2976
2977 if (state->left_to_receive == 0) {
2978 /* Short-circuit for payload-less commands. */
2979 goto reception_complete;
2980 }
2981
2982 ret = conn->sock->ops->recvmsg(conn->sock,
2983 reception_buffer->data + state->received,
2984 state->left_to_receive, MSG_DONTWAIT);
2985 if (ret < 0) {
2986 if (errno != EAGAIN && errno != EWOULDBLOCK) {
2987 PERROR("Unable to receive command payload on sock %d",
2988 conn->sock->fd);
2989 status = RELAY_CONNECTION_STATUS_ERROR;
2990 }
2991 goto end;
2992 } else if (ret == 0) {
2993 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
2994 status = RELAY_CONNECTION_STATUS_CLOSED;
2995 goto end;
2996 }
2997
2998 assert(ret > 0);
2999 assert(ret <= state->left_to_receive);
3000
3001 state->left_to_receive -= ret;
3002 state->received += ret;
3003
3004 if (state->left_to_receive > 0) {
3005 /*
3006 * Can't transition to the protocol's next state, wait to
3007 * receive the rest of the header.
3008 */
3009 DBG3("Partial reception of control connection protocol payload (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
3010 state->received, state->left_to_receive,
3011 conn->sock->fd);
3012 goto end;
3013 }
3014
3015 reception_complete:
3016 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64 " bytes",
3017 conn->sock->fd, state->received);
3018 /*
3019 * The payload required to process the command has been received.
3020 * A view to the reception buffer is forwarded to the various
3021 * commands and the state of the control is reset on success.
3022 *
3023 * Commands are responsible for sending their reply to the peer.
3024 */
3025 payload_view = lttng_buffer_view_from_dynamic_buffer(reception_buffer,
3026 0, -1);
3027 ret = relay_process_control_command(conn,
3028 &state->header, &payload_view);
3029 if (ret < 0) {
3030 status = RELAY_CONNECTION_STATUS_ERROR;
3031 goto end;
3032 }
3033
3034 ret = connection_reset_protocol_state(conn);
3035 if (ret) {
3036 status = RELAY_CONNECTION_STATUS_ERROR;
3037 }
3038 end:
3039 return status;
3040 }
3041
3042 static enum relay_connection_status relay_process_control_receive_header(
3043 struct relay_connection *conn)
3044 {
3045 int ret = 0;
3046 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
3047 struct lttcomm_relayd_hdr header;
3048 struct lttng_dynamic_buffer *reception_buffer =
3049 &conn->protocol.ctrl.reception_buffer;
3050 struct ctrl_connection_state_receive_header *state =
3051 &conn->protocol.ctrl.state.receive_header;
3052
3053 assert(state->left_to_receive != 0);
3054
3055 ret = conn->sock->ops->recvmsg(conn->sock,
3056 reception_buffer->data + state->received,
3057 state->left_to_receive, MSG_DONTWAIT);
3058 if (ret < 0) {
3059 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3060 PERROR("Unable to receive control command header on sock %d",
3061 conn->sock->fd);
3062 status = RELAY_CONNECTION_STATUS_ERROR;
3063 }
3064 goto end;
3065 } else if (ret == 0) {
3066 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
3067 status = RELAY_CONNECTION_STATUS_CLOSED;
3068 goto end;
3069 }
3070
3071 assert(ret > 0);
3072 assert(ret <= state->left_to_receive);
3073
3074 state->left_to_receive -= ret;
3075 state->received += ret;
3076
3077 if (state->left_to_receive > 0) {
3078 /*
3079 * Can't transition to the protocol's next state, wait to
3080 * receive the rest of the header.
3081 */
3082 DBG3("Partial reception of control connection protocol header (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
3083 state->received, state->left_to_receive,
3084 conn->sock->fd);
3085 goto end;
3086 }
3087
3088 /* Transition to next state: receiving the command's payload. */
3089 conn->protocol.ctrl.state_id =
3090 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD;
3091 memcpy(&header, reception_buffer->data, sizeof(header));
3092 header.circuit_id = be64toh(header.circuit_id);
3093 header.data_size = be64toh(header.data_size);
3094 header.cmd = be32toh(header.cmd);
3095 header.cmd_version = be32toh(header.cmd_version);
3096 memcpy(&conn->protocol.ctrl.state.receive_payload.header,
3097 &header, sizeof(header));
3098
3099 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32 ", cmd_version = %" PRIu32 ", payload size = %" PRIu64 " bytes",
3100 conn->sock->fd, header.cmd, header.cmd_version,
3101 header.data_size);
3102
3103 if (header.data_size > DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE) {
3104 ERR("Command header indicates a payload (%" PRIu64 " bytes) that exceeds the maximal payload size allowed on a control connection.",
3105 header.data_size);
3106 status = RELAY_CONNECTION_STATUS_ERROR;
3107 goto end;
3108 }
3109
3110 conn->protocol.ctrl.state.receive_payload.left_to_receive =
3111 header.data_size;
3112 conn->protocol.ctrl.state.receive_payload.received = 0;
3113 ret = lttng_dynamic_buffer_set_size(reception_buffer,
3114 header.data_size);
3115 if (ret) {
3116 status = RELAY_CONNECTION_STATUS_ERROR;
3117 goto end;
3118 }
3119
3120 if (header.data_size == 0) {
3121 /*
3122 * Manually invoke the next state as the poll loop
3123 * will not wake-up to allow us to proceed further.
3124 */
3125 status = relay_process_control_receive_payload(conn);
3126 }
3127 end:
3128 return status;
3129 }
3130
3131 /*
3132 * Process the commands received on the control socket
3133 */
3134 static enum relay_connection_status relay_process_control(
3135 struct relay_connection *conn)
3136 {
3137 enum relay_connection_status status;
3138
3139 switch (conn->protocol.ctrl.state_id) {
3140 case CTRL_CONNECTION_STATE_RECEIVE_HEADER:
3141 status = relay_process_control_receive_header(conn);
3142 break;
3143 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD:
3144 status = relay_process_control_receive_payload(conn);
3145 break;
3146 default:
3147 ERR("Unknown control connection protocol state encountered.");
3148 abort();
3149 }
3150
3151 return status;
3152 }
3153
3154 /*
3155 * Handle index for a data stream.
3156 *
3157 * Called with the stream lock held.
3158 *
3159 * Return 0 on success else a negative value.
3160 */
3161 static int handle_index_data(struct relay_stream *stream, uint64_t net_seq_num,
3162 bool rotate_index, bool *flushed, uint64_t total_size)
3163 {
3164 int ret = 0;
3165 uint64_t data_offset;
3166 struct relay_index *index;
3167
3168 /* Get data offset because we are about to update the index. */
3169 data_offset = htobe64(stream->tracefile_size_current);
3170
3171 DBG("handle_index_data: stream %" PRIu64 " net_seq_num %" PRIu64 " data offset %" PRIu64,
3172 stream->stream_handle, net_seq_num, stream->tracefile_size_current);
3173
3174 /*
3175 * Lookup for an existing index for that stream id/sequence
3176 * number. If it exists, the control thread has already received the
3177 * data for it, thus we need to write it to disk.
3178 */
3179 index = relay_index_get_by_id_or_create(stream, net_seq_num);
3180 if (!index) {
3181 ret = -1;
3182 goto end;
3183 }
3184
3185 if (rotate_index || !stream->index_file) {
3186 ret = create_rotate_index_file(stream);
3187 if (ret < 0) {
3188 ERR("Failed to rotate index");
3189 /* Put self-ref for this index due to error. */
3190 relay_index_put(index);
3191 index = NULL;
3192 goto end;
3193 }
3194 }
3195
3196 if (relay_index_set_file(index, stream->index_file, data_offset)) {
3197 ret = -1;
3198 /* Put self-ref for this index due to error. */
3199 relay_index_put(index);
3200 index = NULL;
3201 goto end;
3202 }
3203
3204 ret = relay_index_try_flush(index);
3205 if (ret == 0) {
3206 tracefile_array_commit_seq(stream->tfa);
3207 stream->index_received_seqcount++;
3208 *flushed = true;
3209 } else if (ret > 0) {
3210 index->total_size = total_size;
3211 /* No flush. */
3212 ret = 0;
3213 } else {
3214 /* Put self-ref for this index due to error. */
3215 relay_index_put(index);
3216 index = NULL;
3217 ret = -1;
3218 }
3219 end:
3220 return ret;
3221 }
3222
3223 static enum relay_connection_status relay_process_data_receive_header(
3224 struct relay_connection *conn)
3225 {
3226 int ret;
3227 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
3228 struct data_connection_state_receive_header *state =
3229 &conn->protocol.data.state.receive_header;
3230 struct lttcomm_relayd_data_hdr header;
3231 struct relay_stream *stream;
3232
3233 assert(state->left_to_receive != 0);
3234
3235 ret = conn->sock->ops->recvmsg(conn->sock,
3236 state->header_reception_buffer + state->received,
3237 state->left_to_receive, MSG_DONTWAIT);
3238 if (ret < 0) {
3239 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3240 PERROR("Unable to receive data header on sock %d", conn->sock->fd);
3241 status = RELAY_CONNECTION_STATUS_ERROR;
3242 }
3243 goto end;
3244 } else if (ret == 0) {
3245 /* Orderly shutdown. Not necessary to print an error. */
3246 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
3247 status = RELAY_CONNECTION_STATUS_CLOSED;
3248 goto end;
3249 }
3250
3251 assert(ret > 0);
3252 assert(ret <= state->left_to_receive);
3253
3254 state->left_to_receive -= ret;
3255 state->received += ret;
3256
3257 if (state->left_to_receive > 0) {
3258 /*
3259 * Can't transition to the protocol's next state, wait to
3260 * receive the rest of the header.
3261 */
3262 DBG3("Partial reception of data connection header (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
3263 state->received, state->left_to_receive,
3264 conn->sock->fd);
3265 goto end;
3266 }
3267
3268 /* Transition to next state: receiving the payload. */
3269 conn->protocol.data.state_id = DATA_CONNECTION_STATE_RECEIVE_PAYLOAD;
3270
3271 memcpy(&header, state->header_reception_buffer, sizeof(header));
3272 header.circuit_id = be64toh(header.circuit_id);
3273 header.stream_id = be64toh(header.stream_id);
3274 header.data_size = be32toh(header.data_size);
3275 header.net_seq_num = be64toh(header.net_seq_num);
3276 header.padding_size = be32toh(header.padding_size);
3277 memcpy(&conn->protocol.data.state.receive_payload.header, &header, sizeof(header));
3278
3279 conn->protocol.data.state.receive_payload.left_to_receive =
3280 header.data_size;
3281 conn->protocol.data.state.receive_payload.received = 0;
3282 conn->protocol.data.state.receive_payload.rotate_index = false;
3283
3284 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64 ", stream_id = %" PRIu64 ", data_size = %" PRIu32 ", net_seq_num = %" PRIu64 ", padding_size = %" PRIu32,
3285 conn->sock->fd, header.circuit_id,
3286 header.stream_id, header.data_size,
3287 header.net_seq_num, header.padding_size);
3288
3289 stream = stream_get_by_id(header.stream_id);
3290 if (!stream) {
3291 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64,
3292 header.stream_id);
3293 /* Protocol error. */
3294 status = RELAY_CONNECTION_STATUS_ERROR;
3295 goto end;
3296 }
3297
3298 pthread_mutex_lock(&stream->lock);
3299
3300 /* Check if a rotation is needed. */
3301 if (stream->tracefile_size > 0 &&
3302 (stream->tracefile_size_current + header.data_size) >
3303 stream->tracefile_size) {
3304 uint64_t old_id, new_id;
3305
3306 old_id = tracefile_array_get_file_index_head(stream->tfa);
3307 tracefile_array_file_rotate(stream->tfa);
3308
3309 /* new_id is updated by utils_rotate_stream_file. */
3310 new_id = old_id;
3311
3312 ret = utils_rotate_stream_file(stream->path_name,
3313 stream->channel_name, stream->tracefile_size,
3314 stream->tracefile_count, -1,
3315 -1, stream->stream_fd->fd,
3316 &new_id, &stream->stream_fd->fd);
3317 if (ret < 0) {
3318 ERR("Failed to rotate stream output file");
3319 status = RELAY_CONNECTION_STATUS_ERROR;
3320 goto end_stream_unlock;
3321 }
3322
3323 /*
3324 * Reset current size because we just performed a stream
3325 * rotation.
3326 */
3327 stream->tracefile_size_current = 0;
3328 conn->protocol.data.state.receive_payload.rotate_index = true;
3329 }
3330
3331 end_stream_unlock:
3332 pthread_mutex_unlock(&stream->lock);
3333 stream_put(stream);
3334 end:
3335 return status;
3336 }
3337
3338 static enum relay_connection_status relay_process_data_receive_payload(
3339 struct relay_connection *conn)
3340 {
3341 int ret;
3342 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
3343 struct relay_stream *stream;
3344 struct data_connection_state_receive_payload *state =
3345 &conn->protocol.data.state.receive_payload;
3346 const size_t chunk_size = RECV_DATA_BUFFER_SIZE;
3347 char data_buffer[chunk_size];
3348 bool partial_recv = false;
3349 bool new_stream = false, close_requested = false, index_flushed = false;
3350 uint64_t left_to_receive = state->left_to_receive;
3351 struct relay_session *session;
3352
3353 DBG3("Receiving data for stream id %" PRIu64 " seqnum %" PRIu64 ", %" PRIu64" bytes received, %" PRIu64 " bytes left to receive",
3354 state->header.stream_id, state->header.net_seq_num,
3355 state->received, left_to_receive);
3356
3357 stream = stream_get_by_id(state->header.stream_id);
3358 if (!stream) {
3359 /* Protocol error. */
3360 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64,
3361 state->header.stream_id);
3362 status = RELAY_CONNECTION_STATUS_ERROR;
3363 goto end;
3364 }
3365
3366 pthread_mutex_lock(&stream->lock);
3367 session = stream->trace->session;
3368 if (!conn->session) {
3369 ret = connection_set_session(conn, session);
3370 if (ret) {
3371 status = RELAY_CONNECTION_STATUS_ERROR;
3372 goto end_stream_unlock;
3373 }
3374 }
3375
3376 /*
3377 * The size of the "chunk" received on any iteration is bounded by:
3378 * - the data left to receive,
3379 * - the data immediately available on the socket,
3380 * - the on-stack data buffer
3381 */
3382 while (left_to_receive > 0 && !partial_recv) {
3383 ssize_t write_ret;
3384 size_t recv_size = min(left_to_receive, chunk_size);
3385
3386 ret = conn->sock->ops->recvmsg(conn->sock, data_buffer,
3387 recv_size, MSG_DONTWAIT);
3388 if (ret < 0) {
3389 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3390 PERROR("Socket %d error", conn->sock->fd);
3391 status = RELAY_CONNECTION_STATUS_ERROR;
3392 }
3393 goto end_stream_unlock;
3394 } else if (ret == 0) {
3395 /* No more data ready to be consumed on socket. */
3396 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64,
3397 state->header.stream_id);
3398 status = RELAY_CONNECTION_STATUS_CLOSED;
3399 break;
3400 } else if (ret < (int) recv_size) {
3401 /*
3402 * All the data available on the socket has been
3403 * consumed.
3404 */
3405 partial_recv = true;
3406 }
3407
3408 recv_size = ret;
3409
3410 /* Write data to stream output fd. */
3411 write_ret = lttng_write(stream->stream_fd->fd, data_buffer,
3412 recv_size);
3413 if (write_ret < (ssize_t) recv_size) {
3414 ERR("Relay error writing data to file");
3415 status = RELAY_CONNECTION_STATUS_ERROR;
3416 goto end_stream_unlock;
3417 }
3418
3419 left_to_receive -= recv_size;
3420 state->received += recv_size;
3421 state->left_to_receive = left_to_receive;
3422
3423 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64,
3424 write_ret, stream->stream_handle);
3425 }
3426
3427 if (state->left_to_receive > 0) {
3428 /*
3429 * Did not receive all the data expected, wait for more data to
3430 * become available on the socket.
3431 */
3432 DBG3("Partial receive on data connection of stream id %" PRIu64 ", %" PRIu64 " bytes received, %" PRIu64 " bytes left to receive",
3433 state->header.stream_id, state->received,
3434 state->left_to_receive);
3435 goto end_stream_unlock;
3436 }
3437
3438 ret = write_padding_to_file(stream->stream_fd->fd,
3439 state->header.padding_size);
3440 if ((int64_t) ret < (int64_t) state->header.padding_size) {
3441 ERR("write_padding_to_file: fail stream %" PRIu64 " net_seq_num %" PRIu64 " ret %d",
3442 stream->stream_handle,
3443 state->header.net_seq_num, ret);
3444 status = RELAY_CONNECTION_STATUS_ERROR;
3445 goto end_stream_unlock;
3446 }
3447
3448
3449 if (session->minor >= 4 && !session->snapshot) {
3450 ret = handle_index_data(stream, state->header.net_seq_num,
3451 state->rotate_index, &index_flushed, state->header.data_size + state->header.padding_size);
3452 if (ret < 0) {
3453 ERR("handle_index_data: fail stream %" PRIu64 " net_seq_num %" PRIu64 " ret %d",
3454 stream->stream_handle,
3455 state->header.net_seq_num, ret);
3456 status = RELAY_CONNECTION_STATUS_ERROR;
3457 goto end_stream_unlock;
3458 }
3459 }
3460
3461 stream->tracefile_size_current += state->header.data_size +
3462 state->header.padding_size;
3463
3464 if (stream->prev_seq == -1ULL) {
3465 new_stream = true;
3466 }
3467 if (index_flushed) {
3468 stream->pos_after_last_complete_data_index =
3469 stream->tracefile_size_current;
3470 }
3471
3472 stream->prev_seq = state->header.net_seq_num;
3473
3474 /*
3475 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3476 * contents of *state which are aliased (union) to the same location as
3477 * the new state. Don't use it beyond this point.
3478 */
3479 connection_reset_protocol_state(conn);
3480 state = NULL;
3481
3482 ret = try_rotate_stream(stream);
3483 if (ret < 0) {
3484 status = RELAY_CONNECTION_STATUS_ERROR;
3485 goto end_stream_unlock;
3486 }
3487
3488 end_stream_unlock:
3489 close_requested = stream->close_requested;
3490 pthread_mutex_unlock(&stream->lock);
3491 if (close_requested && left_to_receive == 0) {
3492 try_stream_close(stream);
3493 }
3494
3495 if (new_stream) {
3496 pthread_mutex_lock(&session->lock);
3497 uatomic_set(&session->new_streams, 1);
3498 pthread_mutex_unlock(&session->lock);
3499 }
3500
3501 stream_put(stream);
3502 end:
3503 return status;
3504 }
3505
3506 /*
3507 * relay_process_data: Process the data received on the data socket
3508 */
3509 static enum relay_connection_status relay_process_data(
3510 struct relay_connection *conn)
3511 {
3512 enum relay_connection_status status;
3513
3514 switch (conn->protocol.data.state_id) {
3515 case DATA_CONNECTION_STATE_RECEIVE_HEADER:
3516 status = relay_process_data_receive_header(conn);
3517 break;
3518 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD:
3519 status = relay_process_data_receive_payload(conn);
3520 break;
3521 default:
3522 ERR("Unexpected data connection communication state.");
3523 abort();
3524 }
3525
3526 return status;
3527 }
3528
3529 static void cleanup_connection_pollfd(struct lttng_poll_event *events, int pollfd)
3530 {
3531 int ret;
3532
3533 (void) lttng_poll_del(events, pollfd);
3534
3535 ret = close(pollfd);
3536 if (ret < 0) {
3537 ERR("Closing pollfd %d", pollfd);
3538 }
3539 }
3540
3541 static void relay_thread_close_connection(struct lttng_poll_event *events,
3542 int pollfd, struct relay_connection *conn)
3543 {
3544 const char *type_str;
3545
3546 switch (conn->type) {
3547 case RELAY_DATA:
3548 type_str = "Data";
3549 break;
3550 case RELAY_CONTROL:
3551 type_str = "Control";
3552 break;
3553 case RELAY_VIEWER_COMMAND:
3554 type_str = "Viewer Command";
3555 break;
3556 case RELAY_VIEWER_NOTIFICATION:
3557 type_str = "Viewer Notification";
3558 break;
3559 default:
3560 type_str = "Unknown";
3561 }
3562 cleanup_connection_pollfd(events, pollfd);
3563 connection_put(conn);
3564 DBG("%s connection closed with %d", type_str, pollfd);
3565 }
3566
3567 /*
3568 * This thread does the actual work
3569 */
3570 static void *relay_thread_worker(void *data)
3571 {
3572 int ret, err = -1, last_seen_data_fd = -1;
3573 uint32_t nb_fd;
3574 struct lttng_poll_event events;
3575 struct lttng_ht *relay_connections_ht;
3576 struct lttng_ht_iter iter;
3577 struct relay_connection *destroy_conn = NULL;
3578
3579 DBG("[thread] Relay worker started");
3580
3581 rcu_register_thread();
3582
3583 health_register(health_relayd, HEALTH_RELAYD_TYPE_WORKER);
3584
3585 if (testpoint(relayd_thread_worker)) {
3586 goto error_testpoint;
3587 }
3588
3589 health_code_update();
3590
3591 /* table of connections indexed on socket */
3592 relay_connections_ht = lttng_ht_new(0, LTTNG_HT_TYPE_ULONG);
3593 if (!relay_connections_ht) {
3594 goto relay_connections_ht_error;
3595 }
3596
3597 ret = create_thread_poll_set(&events, 2);
3598 if (ret < 0) {
3599 goto error_poll_create;
3600 }
3601
3602 ret = lttng_poll_add(&events, relay_conn_pipe[0], LPOLLIN | LPOLLRDHUP);
3603 if (ret < 0) {
3604 goto error;
3605 }
3606
3607 restart:
3608 while (1) {
3609 int idx = -1, i, seen_control = 0, last_notdel_data_fd = -1;
3610
3611 health_code_update();
3612
3613 /* Infinite blocking call, waiting for transmission */
3614 DBG3("Relayd worker thread polling...");
3615 health_poll_entry();
3616 ret = lttng_poll_wait(&events, -1);
3617 health_poll_exit();
3618 if (ret < 0) {
3619 /*
3620 * Restart interrupted system call.
3621 */
3622 if (errno == EINTR) {
3623 goto restart;
3624 }
3625 goto error;
3626 }
3627
3628 nb_fd = ret;
3629
3630 /*
3631 * Process control. The control connection is
3632 * prioritized so we don't starve it with high
3633 * throughput tracing data on the data connection.
3634 */
3635 for (i = 0; i < nb_fd; i++) {
3636 /* Fetch once the poll data */
3637 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
3638 int pollfd = LTTNG_POLL_GETFD(&events, i);
3639
3640 health_code_update();
3641
3642 if (!revents) {
3643 /*
3644 * No activity for this FD (poll
3645 * implementation).
3646 */
3647 continue;
3648 }
3649
3650 /* Thread quit pipe has been closed. Killing thread. */
3651 ret = check_thread_quit_pipe(pollfd, revents);
3652 if (ret) {
3653 err = 0;
3654 goto exit;
3655 }
3656
3657 /* Inspect the relay conn pipe for new connection */
3658 if (pollfd == relay_conn_pipe[0]) {
3659 if (revents & LPOLLIN) {
3660 struct relay_connection *conn;
3661
3662 ret = lttng_read(relay_conn_pipe[0], &conn, sizeof(conn));
3663 if (ret < 0) {
3664 goto error;
3665 }
3666 lttng_poll_add(&events, conn->sock->fd,
3667 LPOLLIN | LPOLLRDHUP);
3668 connection_ht_add(relay_connections_ht, conn);
3669 DBG("Connection socket %d added", conn->sock->fd);
3670 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
3671 ERR("Relay connection pipe error");
3672 goto error;
3673 } else {
3674 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
3675 goto error;
3676 }
3677 } else {
3678 struct relay_connection *ctrl_conn;
3679
3680 ctrl_conn = connection_get_by_sock(relay_connections_ht, pollfd);
3681 /* If not found, there is a synchronization issue. */
3682 assert(ctrl_conn);
3683
3684 if (ctrl_conn->type == RELAY_DATA) {
3685 if (revents & LPOLLIN) {
3686 /*
3687 * Flag the last seen data fd not deleted. It will be
3688 * used as the last seen fd if any fd gets deleted in
3689 * this first loop.
3690 */
3691 last_notdel_data_fd = pollfd;
3692 }
3693 goto put_ctrl_connection;
3694 }
3695 assert(ctrl_conn->type == RELAY_CONTROL);
3696
3697 if (revents & LPOLLIN) {
3698 enum relay_connection_status status;
3699
3700 status = relay_process_control(ctrl_conn);
3701 if (status != RELAY_CONNECTION_STATUS_OK) {
3702 /*
3703 * On socket error flag the session as aborted to force
3704 * the cleanup of its stream otherwise it can leak
3705 * during the lifetime of the relayd.
3706 *
3707 * This prevents situations in which streams can be
3708 * left opened because an index was received, the
3709 * control connection is closed, and the data
3710 * connection is closed (uncleanly) before the packet's
3711 * data provided.
3712 *
3713 * Since the control connection encountered an error,
3714 * it is okay to be conservative and close the
3715 * session right now as we can't rely on the protocol
3716 * being respected anymore.
3717 */
3718 if (status == RELAY_CONNECTION_STATUS_ERROR) {
3719 session_abort(ctrl_conn->session);
3720 }
3721
3722 /* Clear the connection on error or close. */
3723 relay_thread_close_connection(&events,
3724 pollfd,
3725 ctrl_conn);
3726 }
3727 seen_control = 1;
3728 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
3729 relay_thread_close_connection(&events,
3730 pollfd, ctrl_conn);
3731 if (last_seen_data_fd == pollfd) {
3732 last_seen_data_fd = last_notdel_data_fd;
3733 }
3734 } else {
3735 ERR("Unexpected poll events %u for control sock %d",
3736 revents, pollfd);
3737 connection_put(ctrl_conn);
3738 goto error;
3739 }
3740 put_ctrl_connection:
3741 connection_put(ctrl_conn);
3742 }
3743 }
3744
3745 /*
3746 * The last loop handled a control request, go back to poll to make
3747 * sure we prioritise the control socket.
3748 */
3749 if (seen_control) {
3750 continue;
3751 }
3752
3753 if (last_seen_data_fd >= 0) {
3754 for (i = 0; i < nb_fd; i++) {
3755 int pollfd = LTTNG_POLL_GETFD(&events, i);
3756
3757 health_code_update();
3758
3759 if (last_seen_data_fd == pollfd) {
3760 idx = i;
3761 break;
3762 }
3763 }
3764 }
3765
3766 /* Process data connection. */
3767 for (i = idx + 1; i < nb_fd; i++) {
3768 /* Fetch the poll data. */
3769 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
3770 int pollfd = LTTNG_POLL_GETFD(&events, i);
3771 struct relay_connection *data_conn;
3772
3773 health_code_update();
3774
3775 if (!revents) {
3776 /* No activity for this FD (poll implementation). */
3777 continue;
3778 }
3779
3780 /* Skip the command pipe. It's handled in the first loop. */
3781 if (pollfd == relay_conn_pipe[0]) {
3782 continue;
3783 }
3784
3785 data_conn = connection_get_by_sock(relay_connections_ht, pollfd);
3786 if (!data_conn) {
3787 /* Skip it. Might be removed before. */
3788 continue;
3789 }
3790 if (data_conn->type == RELAY_CONTROL) {
3791 goto put_data_connection;
3792 }
3793 assert(data_conn->type == RELAY_DATA);
3794
3795 if (revents & LPOLLIN) {
3796 enum relay_connection_status status;
3797
3798 status = relay_process_data(data_conn);
3799 /* Connection closed or error. */
3800 if (status != RELAY_CONNECTION_STATUS_OK) {
3801 /*
3802 * On socket error flag the session as aborted to force
3803 * the cleanup of its stream otherwise it can leak
3804 * during the lifetime of the relayd.
3805 *
3806 * This prevents situations in which streams can be
3807 * left opened because an index was received, the
3808 * control connection is closed, and the data
3809 * connection is closed (uncleanly) before the packet's
3810 * data provided.
3811 *
3812 * Since the data connection encountered an error,
3813 * it is okay to be conservative and close the
3814 * session right now as we can't rely on the protocol
3815 * being respected anymore.
3816 */
3817 if (status == RELAY_CONNECTION_STATUS_ERROR) {
3818 session_abort(data_conn->session);
3819 }
3820 relay_thread_close_connection(&events, pollfd,
3821 data_conn);
3822 /*
3823 * Every goto restart call sets the last seen fd where
3824 * here we don't really care since we gracefully
3825 * continue the loop after the connection is deleted.
3826 */
3827 } else {
3828 /* Keep last seen port. */
3829 last_seen_data_fd = pollfd;
3830 connection_put(data_conn);
3831 goto restart;
3832 }
3833 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
3834 relay_thread_close_connection(&events, pollfd,
3835 data_conn);
3836 } else {
3837 ERR("Unknown poll events %u for data sock %d",
3838 revents, pollfd);
3839 }
3840 put_data_connection:
3841 connection_put(data_conn);
3842 }
3843 last_seen_data_fd = -1;
3844 }
3845
3846 /* Normal exit, no error */
3847 ret = 0;
3848
3849 exit:
3850 error:
3851 /* Cleanup remaining connection object. */
3852 rcu_read_lock();
3853 cds_lfht_for_each_entry(relay_connections_ht->ht, &iter.iter,
3854 destroy_conn,
3855 sock_n.node) {
3856 health_code_update();
3857
3858 session_abort(destroy_conn->session);
3859
3860 /*
3861 * No need to grab another ref, because we own
3862 * destroy_conn.
3863 */
3864 relay_thread_close_connection(&events, destroy_conn->sock->fd,
3865 destroy_conn);
3866 }
3867 rcu_read_unlock();
3868
3869 lttng_poll_clean(&events);
3870 error_poll_create:
3871 lttng_ht_destroy(relay_connections_ht);
3872 relay_connections_ht_error:
3873 /* Close relay conn pipes */
3874 utils_close_pipe(relay_conn_pipe);
3875 if (err) {
3876 DBG("Thread exited with error");
3877 }
3878 DBG("Worker thread cleanup complete");
3879 error_testpoint:
3880 if (err) {
3881 health_error();
3882 ERR("Health error occurred in %s", __func__);
3883 }
3884 health_unregister(health_relayd);
3885 rcu_unregister_thread();
3886 lttng_relay_stop_threads();
3887 return NULL;
3888 }
3889
3890 /*
3891 * Create the relay command pipe to wake thread_manage_apps.
3892 * Closed in cleanup().
3893 */
3894 static int create_relay_conn_pipe(void)
3895 {
3896 int ret;
3897
3898 ret = utils_create_pipe_cloexec(relay_conn_pipe);
3899
3900 return ret;
3901 }
3902
3903 /*
3904 * main
3905 */
3906 int main(int argc, char **argv)
3907 {
3908 int ret = 0, retval = 0;
3909 void *status;
3910
3911 /* Parse arguments */
3912 progname = argv[0];
3913 if (set_options(argc, argv)) {
3914 retval = -1;
3915 goto exit_options;
3916 }
3917
3918 if (set_signal_handler()) {
3919 retval = -1;
3920 goto exit_options;
3921 }
3922
3923 /* Try to create directory if -o, --output is specified. */
3924 if (opt_output_path) {
3925 if (*opt_output_path != '/') {
3926 ERR("Please specify an absolute path for -o, --output PATH");
3927 retval = -1;
3928 goto exit_options;
3929 }
3930
3931 ret = utils_mkdir_recursive(opt_output_path, S_IRWXU | S_IRWXG,
3932 -1, -1);
3933 if (ret < 0) {
3934 ERR("Unable to create %s", opt_output_path);
3935 retval = -1;
3936 goto exit_options;
3937 }
3938 }
3939
3940 /* Daemonize */
3941 if (opt_daemon || opt_background) {
3942 int i;
3943
3944 ret = lttng_daemonize(&child_ppid, &recv_child_signal,
3945 !opt_background);
3946 if (ret < 0) {
3947 retval = -1;
3948 goto exit_options;
3949 }
3950
3951 /*
3952 * We are in the child. Make sure all other file
3953 * descriptors are closed, in case we are called with
3954 * more opened file descriptors than the standard ones.
3955 */
3956 for (i = 3; i < sysconf(_SC_OPEN_MAX); i++) {
3957 (void) close(i);
3958 }
3959 }
3960
3961 /* Initialize thread health monitoring */
3962 health_relayd = health_app_create(NR_HEALTH_RELAYD_TYPES);
3963 if (!health_relayd) {
3964 PERROR("health_app_create error");
3965 retval = -1;
3966 goto exit_health_app_create;
3967 }
3968
3969 /* Create thread quit pipe */
3970 if (init_thread_quit_pipe()) {
3971 retval = -1;
3972 goto exit_init_data;
3973 }
3974
3975 /* Setup the thread apps communication pipe. */
3976 if (create_relay_conn_pipe()) {
3977 retval = -1;
3978 goto exit_init_data;
3979 }
3980
3981 /* Init relay command queue. */
3982 cds_wfcq_init(&relay_conn_queue.head, &relay_conn_queue.tail);
3983
3984 /* Initialize communication library */
3985 lttcomm_init();
3986 lttcomm_inet_init();
3987
3988 /* tables of sessions indexed by session ID */
3989 sessions_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3990 if (!sessions_ht) {
3991 retval = -1;
3992 goto exit_init_data;
3993 }
3994
3995 /* tables of streams indexed by stream ID */
3996 relay_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3997 if (!relay_streams_ht) {
3998 retval = -1;
3999 goto exit_init_data;
4000 }
4001
4002 /* tables of streams indexed by stream ID */
4003 viewer_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
4004 if (!viewer_streams_ht) {
4005 retval = -1;
4006 goto exit_init_data;
4007 }
4008
4009 ret = utils_create_pipe(health_quit_pipe);
4010 if (ret) {
4011 retval = -1;
4012 goto exit_health_quit_pipe;
4013 }
4014
4015 /* Create thread to manage the client socket */
4016 ret = pthread_create(&health_thread, default_pthread_attr(),
4017 thread_manage_health, (void *) NULL);
4018 if (ret) {
4019 errno = ret;
4020 PERROR("pthread_create health");
4021 retval = -1;
4022 goto exit_health_thread;
4023 }
4024
4025 /* Setup the dispatcher thread */
4026 ret = pthread_create(&dispatcher_thread, default_pthread_attr(),
4027 relay_thread_dispatcher, (void *) NULL);
4028 if (ret) {
4029 errno = ret;
4030 PERROR("pthread_create dispatcher");
4031 retval = -1;
4032 goto exit_dispatcher_thread;
4033 }
4034
4035 /* Setup the worker thread */
4036 ret = pthread_create(&worker_thread, default_pthread_attr(),
4037 relay_thread_worker, NULL);
4038 if (ret) {
4039 errno = ret;
4040 PERROR("pthread_create worker");
4041 retval = -1;
4042 goto exit_worker_thread;
4043 }
4044
4045 /* Setup the listener thread */
4046 ret = pthread_create(&listener_thread, default_pthread_attr(),
4047 relay_thread_listener, (void *) NULL);
4048 if (ret) {
4049 errno = ret;
4050 PERROR("pthread_create listener");
4051 retval = -1;
4052 goto exit_listener_thread;
4053 }
4054
4055 ret = relayd_live_create(live_uri);
4056 if (ret) {
4057 ERR("Starting live viewer threads");
4058 retval = -1;
4059 goto exit_live;
4060 }
4061
4062 /*
4063 * This is where we start awaiting program completion (e.g. through
4064 * signal that asks threads to teardown).
4065 */
4066
4067 ret = relayd_live_join();
4068 if (ret) {
4069 retval = -1;
4070 }
4071 exit_live:
4072
4073 ret = pthread_join(listener_thread, &status);
4074 if (ret) {
4075 errno = ret;
4076 PERROR("pthread_join listener_thread");
4077 retval = -1;
4078 }
4079
4080 exit_listener_thread:
4081 ret = pthread_join(worker_thread, &status);
4082 if (ret) {
4083 errno = ret;
4084 PERROR("pthread_join worker_thread");
4085 retval = -1;
4086 }
4087
4088 exit_worker_thread:
4089 ret = pthread_join(dispatcher_thread, &status);
4090 if (ret) {
4091 errno = ret;
4092 PERROR("pthread_join dispatcher_thread");
4093 retval = -1;
4094 }
4095 exit_dispatcher_thread:
4096
4097 ret = pthread_join(health_thread, &status);
4098 if (ret) {
4099 errno = ret;
4100 PERROR("pthread_join health_thread");
4101 retval = -1;
4102 }
4103 exit_health_thread:
4104
4105 utils_close_pipe(health_quit_pipe);
4106 exit_health_quit_pipe:
4107
4108 exit_init_data:
4109 health_app_destroy(health_relayd);
4110 exit_health_app_create:
4111 exit_options:
4112 /*
4113 * Wait for all pending call_rcu work to complete before tearing
4114 * down data structures. call_rcu worker may be trying to
4115 * perform lookups in those structures.
4116 */
4117 rcu_barrier();
4118 relayd_cleanup();
4119
4120 /* Ensure all prior call_rcu are done. */
4121 rcu_barrier();
4122
4123 if (!retval) {
4124 exit(EXIT_SUCCESS);
4125 } else {
4126 exit(EXIT_FAILURE);
4127 }
4128 }
This page took 0.163177 seconds and 5 git commands to generate.