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