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