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