e3eb9d72ef9c59a68ddc561abe9a01bf41559d90
[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(relay_conn_pipe[1], &new_conn, sizeof(new_conn)); /* NOLINT
1325 sizeof
1326 used
1327 on a
1328 pointer.
1329 */
1330 if (ret < 0) {
1331 PERROR("write connection pipe");
1332 connection_put(new_conn);
1333 goto error;
1334 }
1335 } while (node != nullptr);
1336
1337 /* Futex wait on queue. Blocking call on futex() */
1338 health_poll_entry();
1339 futex_nto1_wait(&relay_conn_queue.futex);
1340 health_poll_exit();
1341 }
1342
1343 /* Normal exit, no error */
1344 err = 0;
1345
1346 error:
1347 error_testpoint:
1348 if (err) {
1349 health_error();
1350 ERR("Health error occurred in %s", __func__);
1351 }
1352 health_unregister(health_relayd);
1353 DBG("Dispatch thread dying");
1354 lttng_relay_stop_threads();
1355 return nullptr;
1356 }
1357
1358 static bool session_streams_have_index(const struct relay_session *session)
1359 {
1360 return session->minor >= 4 && !session->snapshot;
1361 }
1362
1363 /*
1364 * Handle the RELAYD_CREATE_SESSION command.
1365 *
1366 * On success, send back the session id or else return a negative value.
1367 */
1368 static int relay_create_session(const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
1369 struct relay_connection *conn,
1370 const struct lttng_buffer_view *payload)
1371 {
1372 int ret = 0;
1373 ssize_t send_ret;
1374 struct relay_session *session = nullptr;
1375 struct lttcomm_relayd_create_session_reply_2_11 reply = {};
1376 char session_name[LTTNG_NAME_MAX] = {};
1377 char hostname[LTTNG_HOST_NAME_MAX] = {};
1378 uint32_t live_timer = 0;
1379 bool snapshot = false;
1380 bool session_name_contains_creation_timestamp = false;
1381 /* Left nil for peers < 2.11. */
1382 char base_path[LTTNG_PATH_MAX] = {};
1383 lttng_uuid sessiond_uuid = {};
1384 LTTNG_OPTIONAL(uint64_t) id_sessiond = {};
1385 LTTNG_OPTIONAL(uint64_t) current_chunk_id = {};
1386 LTTNG_OPTIONAL(time_t) creation_time = {};
1387 struct lttng_dynamic_buffer reply_payload;
1388
1389 lttng_dynamic_buffer_init(&reply_payload);
1390
1391 if (conn->minor < 4) {
1392 /* From 2.1 to 2.3 */
1393 ret = 0;
1394 } else if (conn->minor >= 4 && conn->minor < 11) {
1395 /* From 2.4 to 2.10 */
1396 ret = cmd_create_session_2_4(
1397 payload, session_name, hostname, &live_timer, &snapshot);
1398 } else {
1399 bool has_current_chunk;
1400 uint64_t current_chunk_id_value;
1401 time_t creation_time_value;
1402 uint64_t id_sessiond_value;
1403
1404 /* From 2.11 to ... */
1405 ret = cmd_create_session_2_11(payload,
1406 session_name,
1407 hostname,
1408 base_path,
1409 &live_timer,
1410 &snapshot,
1411 &id_sessiond_value,
1412 sessiond_uuid,
1413 &has_current_chunk,
1414 &current_chunk_id_value,
1415 &creation_time_value,
1416 &session_name_contains_creation_timestamp);
1417 if (lttng_uuid_is_nil(sessiond_uuid)) {
1418 /* The nil UUID is reserved for pre-2.11 clients. */
1419 ERR("Illegal nil UUID announced by peer in create session command");
1420 ret = -1;
1421 goto send_reply;
1422 }
1423 LTTNG_OPTIONAL_SET(&id_sessiond, id_sessiond_value);
1424 LTTNG_OPTIONAL_SET(&creation_time, creation_time_value);
1425 if (has_current_chunk) {
1426 LTTNG_OPTIONAL_SET(&current_chunk_id, current_chunk_id_value);
1427 }
1428 }
1429
1430 if (ret < 0) {
1431 goto send_reply;
1432 }
1433
1434 session = session_create(session_name,
1435 hostname,
1436 base_path,
1437 live_timer,
1438 snapshot,
1439 sessiond_uuid,
1440 id_sessiond.is_set ? &id_sessiond.value : nullptr,
1441 current_chunk_id.is_set ? &current_chunk_id.value : nullptr,
1442 creation_time.is_set ? &creation_time.value : nullptr,
1443 conn->major,
1444 conn->minor,
1445 session_name_contains_creation_timestamp);
1446 if (!session) {
1447 ret = -1;
1448 goto send_reply;
1449 }
1450 LTTNG_ASSERT(!conn->session);
1451 conn->session = session;
1452 DBG("Created session %" PRIu64, session->id);
1453
1454 reply.generic.session_id = htobe64(session->id);
1455
1456 send_reply:
1457 if (ret < 0) {
1458 reply.generic.ret_code = htobe32(LTTNG_ERR_FATAL);
1459 } else {
1460 reply.generic.ret_code = htobe32(LTTNG_OK);
1461 }
1462
1463 if (conn->minor < 11) {
1464 /* From 2.1 to 2.10 */
1465 ret = lttng_dynamic_buffer_append(
1466 &reply_payload, &reply.generic, sizeof(reply.generic));
1467 if (ret) {
1468 ERR("Failed to append \"create session\" command reply header to payload buffer");
1469 ret = -1;
1470 goto end;
1471 }
1472 } else {
1473 const uint32_t output_path_length = session ? strlen(session->output_path) + 1 : 0;
1474
1475 reply.output_path_length = htobe32(output_path_length);
1476 ret = lttng_dynamic_buffer_append(&reply_payload, &reply, sizeof(reply));
1477 if (ret) {
1478 ERR("Failed to append \"create session\" command reply header to payload buffer");
1479 goto end;
1480 }
1481
1482 if (output_path_length) {
1483 ret = lttng_dynamic_buffer_append(
1484 &reply_payload, session->output_path, output_path_length);
1485 if (ret) {
1486 ERR("Failed to append \"create session\" command reply path to payload buffer");
1487 goto end;
1488 }
1489 }
1490 }
1491
1492 send_ret = conn->sock->ops->sendmsg(conn->sock, reply_payload.data, reply_payload.size, 0);
1493 if (send_ret < (ssize_t) reply_payload.size) {
1494 ERR("Failed to send \"create session\" command reply of %zu bytes (ret = %zd)",
1495 reply_payload.size,
1496 send_ret);
1497 ret = -1;
1498 }
1499 end:
1500 if (ret < 0 && session) {
1501 session_put(session);
1502 }
1503 lttng_dynamic_buffer_reset(&reply_payload);
1504 return ret;
1505 }
1506
1507 /*
1508 * When we have received all the streams and the metadata for a channel,
1509 * we make them visible to the viewer threads.
1510 */
1511 static void publish_connection_local_streams(struct relay_connection *conn)
1512 {
1513 struct relay_stream *stream;
1514 struct relay_session *session = conn->session;
1515
1516 /*
1517 * We publish all streams belonging to a session atomically wrt
1518 * session lock.
1519 */
1520 pthread_mutex_lock(&session->lock);
1521 lttng::urcu::read_lock_guard read_lock;
1522 cds_list_for_each_entry_rcu(stream, &session->recv_list, recv_node)
1523 {
1524 stream_publish(stream);
1525 }
1526
1527 /*
1528 * Inform the viewer that there are new streams in the session.
1529 */
1530 if (session->viewer_attached) {
1531 uatomic_set(&session->new_streams, 1);
1532 }
1533 pthread_mutex_unlock(&session->lock);
1534 }
1535
1536 static int conform_channel_path(char *channel_path)
1537 {
1538 int ret = 0;
1539
1540 if (strstr("../", channel_path)) {
1541 ERR("Refusing channel path as it walks up the path hierarchy: \"%s\"",
1542 channel_path);
1543 ret = -1;
1544 goto end;
1545 }
1546
1547 if (*channel_path == '/') {
1548 const size_t len = strlen(channel_path);
1549
1550 /*
1551 * Channel paths from peers prior to 2.11 are expressed as an
1552 * absolute path that is, in reality, relative to the relay
1553 * daemon's output directory. Remove the leading slash so it
1554 * is correctly interpreted as a relative path later on.
1555 *
1556 * len (and not len - 1) is used to copy the trailing NULL.
1557 */
1558 bcopy(channel_path + 1, channel_path, len);
1559 }
1560 end:
1561 return ret;
1562 }
1563
1564 /*
1565 * relay_add_stream: allocate a new stream for a session
1566 */
1567 static int relay_add_stream(const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
1568 struct relay_connection *conn,
1569 const struct lttng_buffer_view *payload)
1570 {
1571 int ret;
1572 ssize_t send_ret;
1573 struct relay_session *session = conn->session;
1574 struct relay_stream *stream = nullptr;
1575 struct lttcomm_relayd_status_stream reply;
1576 struct ctf_trace *trace = nullptr;
1577 uint64_t stream_handle = -1ULL;
1578 char *path_name = nullptr, *channel_name = nullptr;
1579 uint64_t tracefile_size = 0, tracefile_count = 0;
1580 LTTNG_OPTIONAL(uint64_t) stream_chunk_id = {};
1581
1582 if (!session || !conn->version_check_done) {
1583 ERR("Trying to add a stream before version check");
1584 ret = -1;
1585 goto end_no_session;
1586 }
1587
1588 if (session->minor == 1) {
1589 /* For 2.1 */
1590 ret = cmd_recv_stream_2_1(payload, &path_name, &channel_name);
1591 } else if (session->minor > 1 && session->minor < 11) {
1592 /* From 2.2 to 2.10 */
1593 ret = cmd_recv_stream_2_2(
1594 payload, &path_name, &channel_name, &tracefile_size, &tracefile_count);
1595 } else {
1596 /* From 2.11 to ... */
1597 ret = cmd_recv_stream_2_11(payload,
1598 &path_name,
1599 &channel_name,
1600 &tracefile_size,
1601 &tracefile_count,
1602 &stream_chunk_id.value);
1603 stream_chunk_id.is_set = true;
1604 }
1605
1606 if (ret < 0) {
1607 goto send_reply;
1608 }
1609
1610 if (conform_channel_path(path_name)) {
1611 goto send_reply;
1612 }
1613
1614 /*
1615 * Backward compatibility for --group-output-by-session.
1616 * Prior to lttng 2.11, the complete path is passed by the stream.
1617 * Starting at 2.11, lttng-relayd uses chunk. When dealing with producer
1618 * >=2.11 the chunk is responsible for the output path. When dealing
1619 * with producer < 2.11 the chunk output_path is the root output path
1620 * and the stream carries the complete path (path_name).
1621 * To support --group-output-by-session with older producer (<2.11), we
1622 * need to craft the path based on the stream path.
1623 */
1624 if (opt_group_output_by == RELAYD_GROUP_OUTPUT_BY_SESSION) {
1625 if (conn->minor < 4) {
1626 /*
1627 * From 2.1 to 2.3, the session_name is not passed on
1628 * the RELAYD_CREATE_SESSION command. The session name
1629 * is necessary to detect the presence of a base_path
1630 * inside the stream path. Without it we cannot perform
1631 * a valid group-output-by-session transformation.
1632 */
1633 WARN("Unable to perform a --group-by-session transformation for session %" PRIu64
1634 " for stream with path \"%s\" as it is produced by a peer using a protocol older than v2.4",
1635 session->id,
1636 path_name);
1637 } else if (conn->minor >= 4 && conn->minor < 11) {
1638 char *group_by_session_path_name;
1639
1640 LTTNG_ASSERT(session->session_name[0] != '\0');
1641
1642 group_by_session_path_name = backward_compat_group_by_session(
1643 path_name, session->session_name, session->creation_time.value);
1644 if (!group_by_session_path_name) {
1645 ERR("Failed to apply group by session to stream of session %" PRIu64,
1646 session->id);
1647 goto send_reply;
1648 }
1649
1650 DBG("Transformed session path from \"%s\" to \"%s\" to honor per-session name grouping",
1651 path_name,
1652 group_by_session_path_name);
1653
1654 free(path_name);
1655 path_name = group_by_session_path_name;
1656 }
1657 }
1658
1659 trace = ctf_trace_get_by_path_or_create(session, path_name);
1660 if (!trace) {
1661 goto send_reply;
1662 }
1663
1664 /* This stream here has one reference on the trace. */
1665 pthread_mutex_lock(&last_relay_stream_id_lock);
1666 stream_handle = ++last_relay_stream_id;
1667 pthread_mutex_unlock(&last_relay_stream_id_lock);
1668
1669 /* We pass ownership of path_name and channel_name. */
1670 stream = stream_create(
1671 trace, stream_handle, path_name, channel_name, tracefile_size, tracefile_count);
1672 path_name = nullptr;
1673 channel_name = nullptr;
1674
1675 /*
1676 * Streams are the owners of their trace. Reference to trace is
1677 * kept within stream_create().
1678 */
1679 ctf_trace_put(trace);
1680
1681 send_reply:
1682 memset(&reply, 0, sizeof(reply));
1683 reply.handle = htobe64(stream_handle);
1684 if (!stream) {
1685 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1686 } else {
1687 reply.ret_code = htobe32(LTTNG_OK);
1688 }
1689
1690 send_ret = conn->sock->ops->sendmsg(
1691 conn->sock, &reply, sizeof(struct lttcomm_relayd_status_stream), 0);
1692 if (send_ret < (ssize_t) sizeof(reply)) {
1693 ERR("Failed to send \"add stream\" command reply (ret = %zd)", send_ret);
1694 ret = -1;
1695 }
1696
1697 end_no_session:
1698 free(path_name);
1699 free(channel_name);
1700 return ret;
1701 }
1702
1703 /*
1704 * relay_close_stream: close a specific stream
1705 */
1706 static int relay_close_stream(const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
1707 struct relay_connection *conn,
1708 const struct lttng_buffer_view *payload)
1709 {
1710 int ret;
1711 ssize_t send_ret;
1712 struct relay_session *session = conn->session;
1713 struct lttcomm_relayd_close_stream stream_info;
1714 struct lttcomm_relayd_generic_reply reply;
1715 struct relay_stream *stream;
1716
1717 DBG("Close stream received");
1718
1719 if (!session || !conn->version_check_done) {
1720 ERR("Trying to close a stream before version check");
1721 ret = -1;
1722 goto end_no_session;
1723 }
1724
1725 if (payload->size < sizeof(stream_info)) {
1726 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1727 sizeof(stream_info),
1728 payload->size);
1729 ret = -1;
1730 goto end_no_session;
1731 }
1732 memcpy(&stream_info, payload->data, sizeof(stream_info));
1733 stream_info.stream_id = be64toh(stream_info.stream_id);
1734 stream_info.last_net_seq_num = be64toh(stream_info.last_net_seq_num);
1735
1736 stream = stream_get_by_id(stream_info.stream_id);
1737 if (!stream) {
1738 ret = -1;
1739 goto end;
1740 }
1741
1742 /*
1743 * Set last_net_seq_num before the close flag. Required by data
1744 * pending check.
1745 */
1746 pthread_mutex_lock(&stream->lock);
1747 stream->last_net_seq_num = stream_info.last_net_seq_num;
1748 pthread_mutex_unlock(&stream->lock);
1749
1750 /*
1751 * This is one of the conditions which may trigger a stream close
1752 * with the others being:
1753 * 1) A close command is received for a stream
1754 * 2) The control connection owning the stream is closed
1755 * 3) We have received all of the stream's data _after_ a close
1756 * request.
1757 */
1758 try_stream_close(stream);
1759 stream_put(stream);
1760 ret = 0;
1761
1762 end:
1763 memset(&reply, 0, sizeof(reply));
1764 if (ret < 0) {
1765 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1766 } else {
1767 reply.ret_code = htobe32(LTTNG_OK);
1768 }
1769 send_ret = conn->sock->ops->sendmsg(
1770 conn->sock, &reply, sizeof(struct lttcomm_relayd_generic_reply), 0);
1771 if (send_ret < (ssize_t) sizeof(reply)) {
1772 ERR("Failed to send \"close stream\" command reply (ret = %zd)", send_ret);
1773 ret = -1;
1774 }
1775
1776 end_no_session:
1777 return ret;
1778 }
1779
1780 /*
1781 * relay_reset_metadata: reset a metadata stream
1782 */
1783 static int relay_reset_metadata(const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
1784 struct relay_connection *conn,
1785 const struct lttng_buffer_view *payload)
1786 {
1787 int ret;
1788 ssize_t send_ret;
1789 struct relay_session *session = conn->session;
1790 struct lttcomm_relayd_reset_metadata stream_info;
1791 struct lttcomm_relayd_generic_reply reply;
1792 struct relay_stream *stream;
1793
1794 DBG("Reset metadata received");
1795
1796 if (!session || !conn->version_check_done) {
1797 ERR("Trying to reset a metadata stream before version check");
1798 ret = -1;
1799 goto end_no_session;
1800 }
1801
1802 if (payload->size < sizeof(stream_info)) {
1803 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1804 sizeof(stream_info),
1805 payload->size);
1806 ret = -1;
1807 goto end_no_session;
1808 }
1809 memcpy(&stream_info, payload->data, sizeof(stream_info));
1810 stream_info.stream_id = be64toh(stream_info.stream_id);
1811 stream_info.version = be64toh(stream_info.version);
1812
1813 DBG("Update metadata to version %" PRIu64, stream_info.version);
1814
1815 /* Unsupported for live sessions for now. */
1816 if (session->live_timer != 0) {
1817 ret = -1;
1818 goto end;
1819 }
1820
1821 stream = stream_get_by_id(stream_info.stream_id);
1822 if (!stream) {
1823 ret = -1;
1824 goto end;
1825 }
1826 pthread_mutex_lock(&stream->lock);
1827 if (!stream->is_metadata) {
1828 ret = -1;
1829 goto end_unlock;
1830 }
1831
1832 ret = stream_reset_file(stream);
1833 if (ret < 0) {
1834 ERR("Failed to reset metadata stream %" PRIu64 ": stream_path = %s, channel = %s",
1835 stream->stream_handle,
1836 stream->path_name,
1837 stream->channel_name);
1838 goto end_unlock;
1839 }
1840 end_unlock:
1841 pthread_mutex_unlock(&stream->lock);
1842 stream_put(stream);
1843
1844 end:
1845 memset(&reply, 0, sizeof(reply));
1846 if (ret < 0) {
1847 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1848 } else {
1849 reply.ret_code = htobe32(LTTNG_OK);
1850 }
1851 send_ret = conn->sock->ops->sendmsg(
1852 conn->sock, &reply, sizeof(struct lttcomm_relayd_generic_reply), 0);
1853 if (send_ret < (ssize_t) sizeof(reply)) {
1854 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)", send_ret);
1855 ret = -1;
1856 }
1857
1858 end_no_session:
1859 return ret;
1860 }
1861
1862 /*
1863 * relay_unknown_command: send -1 if received unknown command
1864 */
1865 static void relay_unknown_command(struct relay_connection *conn)
1866 {
1867 struct lttcomm_relayd_generic_reply reply;
1868 ssize_t send_ret;
1869
1870 memset(&reply, 0, sizeof(reply));
1871 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1872 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1873 if (send_ret < sizeof(reply)) {
1874 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret);
1875 }
1876 }
1877
1878 /*
1879 * relay_start: send an acknowledgment to the client to tell if we are
1880 * ready to receive data. We are ready if a session is established.
1881 */
1882 static int relay_start(const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
1883 struct relay_connection *conn,
1884 const struct lttng_buffer_view *payload __attribute__((unused)))
1885 {
1886 int ret = 0;
1887 ssize_t send_ret;
1888 struct lttcomm_relayd_generic_reply reply;
1889 struct relay_session *session = conn->session;
1890
1891 if (!session) {
1892 DBG("Trying to start the streaming without a session established");
1893 ret = htobe32(LTTNG_ERR_UNK);
1894 }
1895
1896 memset(&reply, 0, sizeof(reply));
1897 reply.ret_code = htobe32(LTTNG_OK);
1898 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1899 if (send_ret < (ssize_t) sizeof(reply)) {
1900 ERR("Failed to send \"relay_start\" command reply (ret = %zd)", send_ret);
1901 ret = -1;
1902 }
1903
1904 return ret;
1905 }
1906
1907 /*
1908 * relay_recv_metadata: receive the metadata for the session.
1909 */
1910 static int relay_recv_metadata(const struct lttcomm_relayd_hdr *recv_hdr,
1911 struct relay_connection *conn,
1912 const struct lttng_buffer_view *payload)
1913 {
1914 int ret = 0;
1915 struct relay_session *session = conn->session;
1916 struct lttcomm_relayd_metadata_payload metadata_payload_header;
1917 struct relay_stream *metadata_stream;
1918 uint64_t metadata_payload_size;
1919 struct lttng_buffer_view packet_view;
1920
1921 if (!session) {
1922 ERR("Metadata sent before version check");
1923 ret = -1;
1924 goto end;
1925 }
1926
1927 if (recv_hdr->data_size < sizeof(struct lttcomm_relayd_metadata_payload)) {
1928 ERR("Incorrect data size");
1929 ret = -1;
1930 goto end;
1931 }
1932 metadata_payload_size =
1933 recv_hdr->data_size - sizeof(struct lttcomm_relayd_metadata_payload);
1934
1935 memcpy(&metadata_payload_header, payload->data, sizeof(metadata_payload_header));
1936 metadata_payload_header.stream_id = be64toh(metadata_payload_header.stream_id);
1937 metadata_payload_header.padding_size = be32toh(metadata_payload_header.padding_size);
1938
1939 metadata_stream = stream_get_by_id(metadata_payload_header.stream_id);
1940 if (!metadata_stream) {
1941 ret = -1;
1942 goto end;
1943 }
1944
1945 packet_view = lttng_buffer_view_from_view(
1946 payload, sizeof(metadata_payload_header), metadata_payload_size);
1947 if (!lttng_buffer_view_is_valid(&packet_view)) {
1948 ERR("Invalid metadata packet length announced by header");
1949 ret = -1;
1950 goto end_put;
1951 }
1952
1953 pthread_mutex_lock(&metadata_stream->lock);
1954 ret = stream_write(metadata_stream, &packet_view, metadata_payload_header.padding_size);
1955 pthread_mutex_unlock(&metadata_stream->lock);
1956 if (ret) {
1957 ret = -1;
1958 goto end_put;
1959 }
1960 end_put:
1961 stream_put(metadata_stream);
1962 end:
1963 return ret;
1964 }
1965
1966 /*
1967 * relay_send_version: send relayd version number
1968 */
1969 static int relay_send_version(const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
1970 struct relay_connection *conn,
1971 const struct lttng_buffer_view *payload)
1972 {
1973 int ret;
1974 ssize_t send_ret;
1975 struct lttcomm_relayd_version reply, msg;
1976 bool compatible = true;
1977
1978 conn->version_check_done = true;
1979
1980 /* Get version from the other side. */
1981 if (payload->size < sizeof(msg)) {
1982 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1983 sizeof(msg),
1984 payload->size);
1985 ret = -1;
1986 goto end;
1987 }
1988
1989 memcpy(&msg, payload->data, sizeof(msg));
1990 msg.major = be32toh(msg.major);
1991 msg.minor = be32toh(msg.minor);
1992
1993 memset(&reply, 0, sizeof(reply));
1994 reply.major = RELAYD_VERSION_COMM_MAJOR;
1995 reply.minor = RELAYD_VERSION_COMM_MINOR;
1996
1997 /* Major versions must be the same */
1998 if (reply.major != msg.major) {
1999 DBG("Incompatible major versions (%u vs %u), deleting session",
2000 reply.major,
2001 msg.major);
2002 compatible = false;
2003 }
2004
2005 conn->major = reply.major;
2006 /* We adapt to the lowest compatible version */
2007 if (reply.minor <= msg.minor) {
2008 conn->minor = reply.minor;
2009 } else {
2010 conn->minor = msg.minor;
2011 }
2012
2013 reply.major = htobe32(reply.major);
2014 reply.minor = htobe32(reply.minor);
2015 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2016 if (send_ret < (ssize_t) sizeof(reply)) {
2017 ERR("Failed to send \"send version\" command reply (ret = %zd)", send_ret);
2018 ret = -1;
2019 goto end;
2020 } else {
2021 ret = 0;
2022 }
2023
2024 if (!compatible) {
2025 ret = -1;
2026 goto end;
2027 }
2028
2029 DBG("Version check done using protocol %u.%u", conn->major, conn->minor);
2030
2031 end:
2032 return ret;
2033 }
2034
2035 /*
2036 * Check for data pending for a given stream id from the session daemon.
2037 */
2038 static int relay_data_pending(const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
2039 struct relay_connection *conn,
2040 const struct lttng_buffer_view *payload)
2041 {
2042 struct relay_session *session = conn->session;
2043 struct lttcomm_relayd_data_pending msg;
2044 struct lttcomm_relayd_generic_reply reply;
2045 struct relay_stream *stream;
2046 ssize_t send_ret;
2047 int ret;
2048 uint64_t stream_seq;
2049
2050 DBG("Data pending command received");
2051
2052 if (!session || !conn->version_check_done) {
2053 ERR("Trying to check for data before version check");
2054 ret = -1;
2055 goto end_no_session;
2056 }
2057
2058 if (payload->size < sizeof(msg)) {
2059 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
2060 sizeof(msg),
2061 payload->size);
2062 ret = -1;
2063 goto end_no_session;
2064 }
2065 memcpy(&msg, payload->data, sizeof(msg));
2066 msg.stream_id = be64toh(msg.stream_id);
2067 msg.last_net_seq_num = be64toh(msg.last_net_seq_num);
2068
2069 stream = stream_get_by_id(msg.stream_id);
2070 if (stream == nullptr) {
2071 ret = -1;
2072 goto end;
2073 }
2074
2075 pthread_mutex_lock(&stream->lock);
2076
2077 if (session_streams_have_index(session)) {
2078 /*
2079 * Ensure that both the index and stream data have been
2080 * flushed up to the requested point.
2081 */
2082 stream_seq = std::min(stream->prev_data_seq, stream->prev_index_seq);
2083 } else {
2084 stream_seq = stream->prev_data_seq;
2085 }
2086 DBG("Data pending for stream id %" PRIu64 ": prev_data_seq %" PRIu64
2087 ", prev_index_seq %" PRIu64 ", and last_seq %" PRIu64,
2088 msg.stream_id,
2089 stream->prev_data_seq,
2090 stream->prev_index_seq,
2091 msg.last_net_seq_num);
2092
2093 /* Avoid wrapping issue */
2094 if (((int64_t) (stream_seq - msg.last_net_seq_num)) >= 0) {
2095 /* Data has in fact been written and is NOT pending */
2096 ret = 0;
2097 } else {
2098 /* Data still being streamed thus pending */
2099 ret = 1;
2100 }
2101
2102 stream->data_pending_check_done = true;
2103 pthread_mutex_unlock(&stream->lock);
2104
2105 stream_put(stream);
2106 end:
2107
2108 memset(&reply, 0, sizeof(reply));
2109 reply.ret_code = htobe32(ret);
2110 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2111 if (send_ret < (ssize_t) sizeof(reply)) {
2112 ERR("Failed to send \"data pending\" command reply (ret = %zd)", send_ret);
2113 ret = -1;
2114 }
2115
2116 end_no_session:
2117 return ret;
2118 }
2119
2120 /*
2121 * Wait for the control socket to reach a quiescent state.
2122 *
2123 * Note that for now, when receiving this command from the session
2124 * daemon, this means that every subsequent commands or data received on
2125 * the control socket has been handled. So, this is why we simply return
2126 * OK here.
2127 */
2128 static int relay_quiescent_control(const struct lttcomm_relayd_hdr *recv_hdr
2129 __attribute__((unused)),
2130 struct relay_connection *conn,
2131 const struct lttng_buffer_view *payload)
2132 {
2133 int ret;
2134 ssize_t send_ret;
2135 struct relay_stream *stream;
2136 struct lttcomm_relayd_quiescent_control msg;
2137 struct lttcomm_relayd_generic_reply reply;
2138
2139 DBG("Checking quiescent state on control socket");
2140
2141 if (!conn->session || !conn->version_check_done) {
2142 ERR("Trying to check for data before version check");
2143 ret = -1;
2144 goto end_no_session;
2145 }
2146
2147 if (payload->size < sizeof(msg)) {
2148 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2149 sizeof(msg),
2150 payload->size);
2151 ret = -1;
2152 goto end_no_session;
2153 }
2154 memcpy(&msg, payload->data, sizeof(msg));
2155 msg.stream_id = be64toh(msg.stream_id);
2156
2157 stream = stream_get_by_id(msg.stream_id);
2158 if (!stream) {
2159 goto reply;
2160 }
2161 pthread_mutex_lock(&stream->lock);
2162 stream->data_pending_check_done = true;
2163 pthread_mutex_unlock(&stream->lock);
2164
2165 DBG("Relay quiescent control pending flag set to %" PRIu64, msg.stream_id);
2166 stream_put(stream);
2167 reply:
2168 memset(&reply, 0, sizeof(reply));
2169 reply.ret_code = htobe32(LTTNG_OK);
2170 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2171 if (send_ret < (ssize_t) sizeof(reply)) {
2172 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)", send_ret);
2173 ret = -1;
2174 } else {
2175 ret = 0;
2176 }
2177
2178 end_no_session:
2179 return ret;
2180 }
2181
2182 /*
2183 * Initialize a data pending command. This means that a consumer is about
2184 * to ask for data pending for each stream it holds. Simply iterate over
2185 * all streams of a session and set the data_pending_check_done flag.
2186 *
2187 * This command returns to the client a LTTNG_OK code.
2188 */
2189 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
2190 struct relay_connection *conn,
2191 const struct lttng_buffer_view *payload)
2192 {
2193 int ret;
2194 ssize_t send_ret;
2195 struct lttng_ht_iter iter;
2196 struct lttcomm_relayd_begin_data_pending msg;
2197 struct lttcomm_relayd_generic_reply reply;
2198 struct relay_stream *stream;
2199
2200 LTTNG_ASSERT(recv_hdr);
2201 LTTNG_ASSERT(conn);
2202
2203 DBG("Init streams for data pending");
2204
2205 if (!conn->session || !conn->version_check_done) {
2206 ERR("Trying to check for data before version check");
2207 ret = -1;
2208 goto end_no_session;
2209 }
2210
2211 if (payload->size < sizeof(msg)) {
2212 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2213 sizeof(msg),
2214 payload->size);
2215 ret = -1;
2216 goto end_no_session;
2217 }
2218 memcpy(&msg, payload->data, sizeof(msg));
2219 msg.session_id = be64toh(msg.session_id);
2220
2221 /*
2222 * Iterate over all streams to set the begin data pending flag.
2223 * For now, the streams are indexed by stream handle so we have
2224 * to iterate over all streams to find the one associated with
2225 * the right session_id.
2226 */
2227 {
2228 lttng::urcu::read_lock_guard read_lock;
2229
2230 cds_lfht_for_each_entry (relay_streams_ht->ht, &iter.iter, stream, node.node) {
2231 if (!stream_get(stream)) {
2232 continue;
2233 }
2234
2235 if (stream->trace->session->id == msg.session_id) {
2236 pthread_mutex_lock(&stream->lock);
2237 stream->data_pending_check_done = false;
2238 pthread_mutex_unlock(&stream->lock);
2239 DBG("Set begin data pending flag to stream %" PRIu64,
2240 stream->stream_handle);
2241 }
2242
2243 stream_put(stream);
2244 }
2245 }
2246
2247 memset(&reply, 0, sizeof(reply));
2248 /* All good, send back reply. */
2249 reply.ret_code = htobe32(LTTNG_OK);
2250
2251 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2252 if (send_ret < (ssize_t) sizeof(reply)) {
2253 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)", send_ret);
2254 ret = -1;
2255 } else {
2256 ret = 0;
2257 }
2258
2259 end_no_session:
2260 return ret;
2261 }
2262
2263 /*
2264 * End data pending command. This will check, for a given session id, if
2265 * each stream associated with it has its data_pending_check_done flag
2266 * set. If not, this means that the client lost track of the stream but
2267 * the data is still being streamed on our side. In this case, we inform
2268 * the client that data is in flight.
2269 *
2270 * Return to the client if there is data in flight or not with a ret_code.
2271 */
2272 static int relay_end_data_pending(const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
2273 struct relay_connection *conn,
2274 const struct lttng_buffer_view *payload)
2275 {
2276 int ret;
2277 ssize_t send_ret;
2278 struct lttng_ht_iter iter;
2279 struct lttcomm_relayd_end_data_pending msg;
2280 struct lttcomm_relayd_generic_reply reply;
2281 struct relay_stream *stream;
2282 uint32_t is_data_inflight = 0;
2283
2284 DBG("End data pending command");
2285
2286 if (!conn->session || !conn->version_check_done) {
2287 ERR("Trying to check for data before version check");
2288 ret = -1;
2289 goto end_no_session;
2290 }
2291
2292 if (payload->size < sizeof(msg)) {
2293 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2294 sizeof(msg),
2295 payload->size);
2296 ret = -1;
2297 goto end_no_session;
2298 }
2299 memcpy(&msg, payload->data, sizeof(msg));
2300 msg.session_id = be64toh(msg.session_id);
2301
2302 /*
2303 * Iterate over all streams to see if the begin data pending
2304 * flag is set.
2305 */
2306 {
2307 lttng::urcu::read_lock_guard read_lock;
2308
2309 cds_lfht_for_each_entry (relay_streams_ht->ht, &iter.iter, stream, node.node) {
2310 if (!stream_get(stream)) {
2311 continue;
2312 }
2313
2314 if (stream->trace->session->id != msg.session_id) {
2315 stream_put(stream);
2316 continue;
2317 }
2318
2319 pthread_mutex_lock(&stream->lock);
2320 if (!stream->data_pending_check_done) {
2321 uint64_t stream_seq;
2322
2323 if (session_streams_have_index(conn->session)) {
2324 /*
2325 * Ensure that both the index and stream data have been
2326 * flushed up to the requested point.
2327 */
2328 stream_seq = std::min(stream->prev_data_seq,
2329 stream->prev_index_seq);
2330 } else {
2331 stream_seq = stream->prev_data_seq;
2332 }
2333
2334 if (!stream->closed ||
2335 !(((int64_t) (stream_seq - stream->last_net_seq_num)) >= 0)) {
2336 is_data_inflight = 1;
2337 DBG("Data is still in flight for stream %" PRIu64,
2338 stream->stream_handle);
2339 pthread_mutex_unlock(&stream->lock);
2340 stream_put(stream);
2341 break;
2342 }
2343 }
2344
2345 pthread_mutex_unlock(&stream->lock);
2346 stream_put(stream);
2347 }
2348 }
2349
2350 memset(&reply, 0, sizeof(reply));
2351 /* All good, send back reply. */
2352 reply.ret_code = htobe32(is_data_inflight);
2353
2354 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2355 if (send_ret < (ssize_t) sizeof(reply)) {
2356 ERR("Failed to send \"end data pending\" command reply (ret = %zd)", send_ret);
2357 ret = -1;
2358 } else {
2359 ret = 0;
2360 }
2361
2362 end_no_session:
2363 return ret;
2364 }
2365
2366 /*
2367 * Receive an index for a specific stream.
2368 *
2369 * Return 0 on success else a negative value.
2370 */
2371 static int relay_recv_index(const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
2372 struct relay_connection *conn,
2373 const struct lttng_buffer_view *payload)
2374 {
2375 int ret;
2376 ssize_t send_ret;
2377 struct relay_session *session = conn->session;
2378 struct lttcomm_relayd_index index_info;
2379 struct lttcomm_relayd_generic_reply reply;
2380 struct relay_stream *stream;
2381 size_t msg_len;
2382
2383 LTTNG_ASSERT(conn);
2384
2385 DBG("Relay receiving index");
2386
2387 if (!session || !conn->version_check_done) {
2388 ERR("Trying to close a stream before version check");
2389 ret = -1;
2390 goto end_no_session;
2391 }
2392
2393 msg_len = lttcomm_relayd_index_len(lttng_to_index_major(conn->major, conn->minor),
2394 lttng_to_index_minor(conn->major, conn->minor));
2395 if (payload->size < msg_len) {
2396 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2397 msg_len,
2398 payload->size);
2399 ret = -1;
2400 goto end_no_session;
2401 }
2402 memcpy(&index_info, payload->data, msg_len);
2403 index_info.relay_stream_id = be64toh(index_info.relay_stream_id);
2404 index_info.net_seq_num = be64toh(index_info.net_seq_num);
2405 index_info.packet_size = be64toh(index_info.packet_size);
2406 index_info.content_size = be64toh(index_info.content_size);
2407 index_info.timestamp_begin = be64toh(index_info.timestamp_begin);
2408 index_info.timestamp_end = be64toh(index_info.timestamp_end);
2409 index_info.events_discarded = be64toh(index_info.events_discarded);
2410 index_info.stream_id = be64toh(index_info.stream_id);
2411
2412 if (conn->minor >= 8) {
2413 index_info.stream_instance_id = be64toh(index_info.stream_instance_id);
2414 index_info.packet_seq_num = be64toh(index_info.packet_seq_num);
2415 } else {
2416 index_info.stream_instance_id = -1ULL;
2417 index_info.packet_seq_num = -1ULL;
2418 }
2419
2420 stream = stream_get_by_id(index_info.relay_stream_id);
2421 if (!stream) {
2422 ERR("stream_get_by_id not found");
2423 ret = -1;
2424 goto end;
2425 }
2426
2427 pthread_mutex_lock(&stream->lock);
2428 ret = stream_add_index(stream, &index_info);
2429 pthread_mutex_unlock(&stream->lock);
2430 if (ret) {
2431 goto end_stream_put;
2432 }
2433
2434 end_stream_put:
2435 stream_put(stream);
2436 end:
2437 memset(&reply, 0, sizeof(reply));
2438 if (ret < 0) {
2439 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2440 } else {
2441 reply.ret_code = htobe32(LTTNG_OK);
2442 }
2443 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2444 if (send_ret < (ssize_t) sizeof(reply)) {
2445 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret);
2446 ret = -1;
2447 }
2448
2449 end_no_session:
2450 return ret;
2451 }
2452
2453 /*
2454 * Receive the streams_sent message.
2455 *
2456 * Return 0 on success else a negative value.
2457 */
2458 static int relay_streams_sent(const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
2459 struct relay_connection *conn,
2460 const struct lttng_buffer_view *payload __attribute__((unused)))
2461 {
2462 int ret;
2463 ssize_t send_ret;
2464 struct lttcomm_relayd_generic_reply reply;
2465
2466 LTTNG_ASSERT(conn);
2467
2468 DBG("Relay receiving streams_sent");
2469
2470 if (!conn->session || !conn->version_check_done) {
2471 ERR("Trying to close a stream before version check");
2472 ret = -1;
2473 goto end_no_session;
2474 }
2475
2476 /*
2477 * Publish every pending stream in the connection recv list which are
2478 * now ready to be used by the viewer.
2479 */
2480 publish_connection_local_streams(conn);
2481
2482 memset(&reply, 0, sizeof(reply));
2483 reply.ret_code = htobe32(LTTNG_OK);
2484 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2485 if (send_ret < (ssize_t) sizeof(reply)) {
2486 ERR("Failed to send \"streams sent\" command reply (ret = %zd)", send_ret);
2487 ret = -1;
2488 } else {
2489 /* Success. */
2490 ret = 0;
2491 }
2492
2493 end_no_session:
2494 return ret;
2495 }
2496
2497 static ssize_t
2498 relay_unpack_rotate_streams_header(const struct lttng_buffer_view *payload,
2499 struct lttcomm_relayd_rotate_streams *_rotate_streams)
2500 {
2501 struct lttcomm_relayd_rotate_streams rotate_streams;
2502 /*
2503 * Set to the smallest version (packed) of `lttcomm_relayd_rotate_streams`.
2504 * This is the smallest version of this structure, but it can be larger;
2505 * this variable is updated once the proper size of the structure is known.
2506 *
2507 * See comment at the declaration of this structure for more information.
2508 */
2509 ssize_t header_len = sizeof(struct lttcomm_relayd_rotate_streams_packed);
2510 size_t expected_payload_size_no_padding, expected_payload_size_3_bytes_padding,
2511 expected_payload_size_7_bytes_padding;
2512
2513 if (payload->size < header_len) {
2514 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2515 header_len,
2516 payload->size);
2517 goto error;
2518 }
2519
2520 /*
2521 * Some versions incorrectly omitted the LTTNG_PACKED annotation on the
2522 * `new_chunk_id` optional field of struct lttcomm_relayd_rotate_streams.
2523 *
2524 * We start by "unpacking" `stream_count` to figure out the padding length
2525 * emited by our peer.
2526 */
2527 {
2528 decltype(rotate_streams.stream_count) stream_count;
2529
2530 memcpy(&stream_count, payload->data, sizeof(stream_count));
2531 rotate_streams.stream_count = be32toh(stream_count);
2532 }
2533
2534 rotate_streams.new_chunk_id = LTTNG_OPTIONAL_INIT_UNSET;
2535
2536 /*
2537 * Payload size expected given the possible padding lengths in
2538 * `struct lttcomm_relayd_rotate_streams`.
2539 */
2540 expected_payload_size_no_padding =
2541 (rotate_streams.stream_count * sizeof(*rotate_streams.rotation_positions)) +
2542 sizeof(lttcomm_relayd_rotate_streams_packed);
2543 expected_payload_size_3_bytes_padding =
2544 (rotate_streams.stream_count * sizeof(*rotate_streams.rotation_positions)) +
2545 sizeof(lttcomm_relayd_rotate_streams_3_bytes_padding);
2546 expected_payload_size_7_bytes_padding =
2547 (rotate_streams.stream_count * sizeof(*rotate_streams.rotation_positions)) +
2548 sizeof(lttcomm_relayd_rotate_streams_7_bytes_padding);
2549
2550 if (payload->size == expected_payload_size_no_padding) {
2551 struct lttcomm_relayd_rotate_streams_packed packed_rotate_streams;
2552
2553 /*
2554 * This handles cases where someone might build with
2555 * -fpack-struct or any other toolchain that wouldn't produce
2556 * padding to align `value`.
2557 */
2558 DBG("Received `struct lttcomm_relayd_rotate_streams` with no padding");
2559
2560 header_len = sizeof(packed_rotate_streams);
2561 memcpy(&packed_rotate_streams, payload->data, header_len);
2562
2563 /* Unpack the packed structure to the natively-packed version. */
2564 _rotate_streams->new_chunk_id = (typeof(_rotate_streams->new_chunk_id)){
2565 .is_set = !!packed_rotate_streams.new_chunk_id.is_set,
2566 .value = be64toh(packed_rotate_streams.new_chunk_id.value),
2567 };
2568 _rotate_streams->stream_count = be32toh(packed_rotate_streams.stream_count);
2569 } else if (payload->size == expected_payload_size_3_bytes_padding) {
2570 struct lttcomm_relayd_rotate_streams_3_bytes_padding padded_rotate_streams;
2571
2572 DBG("Received `struct lttcomm_relayd_rotate_streams` with 3 bytes of padding (4-byte aligned peer)");
2573
2574 header_len = sizeof(padded_rotate_streams);
2575 memcpy(&padded_rotate_streams, payload->data, header_len);
2576
2577 /* Unpack the 3-byte padded structure to the natively-packed version. */
2578 _rotate_streams->new_chunk_id = (typeof(_rotate_streams->new_chunk_id)){
2579 .is_set = !!padded_rotate_streams.new_chunk_id.is_set,
2580 .value = be64toh(padded_rotate_streams.new_chunk_id.value),
2581 };
2582 _rotate_streams->stream_count = be32toh(padded_rotate_streams.stream_count);
2583 } else if (payload->size == expected_payload_size_7_bytes_padding) {
2584 struct lttcomm_relayd_rotate_streams_7_bytes_padding padded_rotate_streams;
2585
2586 DBG("Received `struct lttcomm_relayd_rotate_streams` with 7 bytes of padding (8-byte aligned peer)");
2587
2588 header_len = sizeof(padded_rotate_streams);
2589 memcpy(&padded_rotate_streams, payload->data, header_len);
2590
2591 /* Unpack the 7-byte padded structure to the natively-packed version. */
2592 _rotate_streams->new_chunk_id = (typeof(_rotate_streams->new_chunk_id)){
2593 .is_set = !!padded_rotate_streams.new_chunk_id.is_set,
2594 .value = be64toh(padded_rotate_streams.new_chunk_id.value),
2595 };
2596 _rotate_streams->stream_count = be32toh(padded_rotate_streams.stream_count);
2597
2598 header_len = sizeof(padded_rotate_streams);
2599 } else {
2600 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected %zu, %zu or %zu bytes, got %zu bytes",
2601 expected_payload_size_no_padding,
2602 expected_payload_size_3_bytes_padding,
2603 expected_payload_size_7_bytes_padding,
2604 payload->size);
2605 goto error;
2606 }
2607
2608 return header_len;
2609 error:
2610 return -1;
2611 }
2612
2613 /*
2614 * relay_rotate_session_stream: rotate a stream to a new tracefile for the
2615 * session rotation feature (not the tracefile rotation feature).
2616 */
2617 static int relay_rotate_session_streams(const struct lttcomm_relayd_hdr *recv_hdr
2618 __attribute__((unused)),
2619 struct relay_connection *conn,
2620 const struct lttng_buffer_view *payload)
2621 {
2622 int ret = 0;
2623 uint32_t i;
2624 ssize_t send_ret;
2625 enum lttng_error_code reply_code = LTTNG_ERR_UNK;
2626 struct relay_session *session = conn->session;
2627 struct lttcomm_relayd_rotate_streams rotate_streams;
2628 struct lttcomm_relayd_generic_reply reply = {};
2629 struct relay_stream *stream = nullptr;
2630 struct lttng_trace_chunk *next_trace_chunk = nullptr;
2631 struct lttng_buffer_view stream_positions;
2632 char chunk_id_buf[MAX_INT_DEC_LEN(uint64_t)];
2633 const char *chunk_id_str = "none";
2634 ssize_t header_len;
2635
2636 if (!session || !conn->version_check_done) {
2637 ERR("Trying to rotate a stream before version check");
2638 ret = -1;
2639 goto end_no_reply;
2640 }
2641
2642 if (session->major == 2 && session->minor < 11) {
2643 ERR("Unsupported feature before 2.11");
2644 ret = -1;
2645 goto end_no_reply;
2646 }
2647
2648 header_len = relay_unpack_rotate_streams_header(payload, &rotate_streams);
2649 if (header_len < 0) {
2650 ret = -1;
2651 goto end_no_reply;
2652 }
2653
2654 if (rotate_streams.new_chunk_id.is_set) {
2655 /*
2656 * Retrieve the trace chunk the stream must transition to. As
2657 * per the protocol, this chunk should have been created
2658 * before this command is received.
2659 */
2660 next_trace_chunk = sessiond_trace_chunk_registry_get_chunk(
2661 sessiond_trace_chunk_registry,
2662 session->sessiond_uuid,
2663 conn->session->id_sessiond.is_set ? conn->session->id_sessiond.value :
2664 conn->session->id,
2665 rotate_streams.new_chunk_id.value);
2666 if (!next_trace_chunk) {
2667 char uuid_str[LTTNG_UUID_STR_LEN];
2668
2669 lttng_uuid_to_str(session->sessiond_uuid, uuid_str);
2670 ERR("Unknown next trace chunk in ROTATE_STREAMS command: sessiond_uuid = {%s}, session_id = %" PRIu64
2671 ", trace_chunk_id = %" PRIu64,
2672 uuid_str,
2673 session->id,
2674 rotate_streams.new_chunk_id.value);
2675 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2676 ret = -1;
2677 goto end;
2678 }
2679
2680 ret = snprintf(chunk_id_buf,
2681 sizeof(chunk_id_buf),
2682 "%" PRIu64,
2683 rotate_streams.new_chunk_id.value);
2684 if (ret < 0 || ret >= sizeof(chunk_id_buf)) {
2685 chunk_id_str = "formatting error";
2686 } else {
2687 chunk_id_str = chunk_id_buf;
2688 }
2689 }
2690
2691 DBG("Rotate %" PRIu32 " streams of session \"%s\" to chunk \"%s\"",
2692 rotate_streams.stream_count,
2693 session->session_name,
2694 chunk_id_str);
2695
2696 stream_positions = lttng_buffer_view_from_view(payload, header_len, -1);
2697 if (!stream_positions.data ||
2698 stream_positions.size < (rotate_streams.stream_count *
2699 sizeof(struct lttcomm_relayd_stream_rotation_position))) {
2700 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2701 ret = -1;
2702 goto end;
2703 }
2704
2705 for (i = 0; i < rotate_streams.stream_count; i++) {
2706 struct lttcomm_relayd_stream_rotation_position *position_comm =
2707 &((typeof(position_comm)) stream_positions.data)[i];
2708 const struct lttcomm_relayd_stream_rotation_position pos = {
2709 .stream_id = be64toh(position_comm->stream_id),
2710 .rotate_at_seq_num = be64toh(position_comm->rotate_at_seq_num),
2711 };
2712
2713 stream = stream_get_by_id(pos.stream_id);
2714 if (!stream) {
2715 reply_code = LTTNG_ERR_INVALID;
2716 ret = -1;
2717 goto end;
2718 }
2719
2720 pthread_mutex_lock(&stream->lock);
2721 ret = stream_set_pending_rotation(stream, next_trace_chunk, pos.rotate_at_seq_num);
2722 pthread_mutex_unlock(&stream->lock);
2723 if (ret) {
2724 reply_code = LTTNG_ERR_FILE_CREATION_ERROR;
2725 goto end;
2726 }
2727
2728 stream_put(stream);
2729 stream = nullptr;
2730 }
2731
2732 reply_code = LTTNG_OK;
2733 ret = 0;
2734 end:
2735 if (stream) {
2736 stream_put(stream);
2737 }
2738
2739 reply.ret_code = htobe32((uint32_t) reply_code);
2740 send_ret = conn->sock->ops->sendmsg(
2741 conn->sock, &reply, sizeof(struct lttcomm_relayd_generic_reply), 0);
2742 if (send_ret < (ssize_t) sizeof(reply)) {
2743 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)", send_ret);
2744 ret = -1;
2745 }
2746 end_no_reply:
2747 lttng_trace_chunk_put(next_trace_chunk);
2748 return ret;
2749 }
2750
2751 /*
2752 * relay_create_trace_chunk: create a new trace chunk
2753 */
2754 static int relay_create_trace_chunk(const struct lttcomm_relayd_hdr *recv_hdr
2755 __attribute__((unused)),
2756 struct relay_connection *conn,
2757 const struct lttng_buffer_view *payload)
2758 {
2759 int ret = 0;
2760 ssize_t send_ret;
2761 struct relay_session *session = conn->session;
2762 struct lttcomm_relayd_create_trace_chunk *msg;
2763 struct lttcomm_relayd_generic_reply reply = {};
2764 struct lttng_buffer_view header_view;
2765 struct lttng_trace_chunk *chunk = nullptr, *published_chunk = nullptr;
2766 enum lttng_error_code reply_code = LTTNG_OK;
2767 enum lttng_trace_chunk_status chunk_status;
2768 const char *new_path;
2769
2770 if (!session || !conn->version_check_done) {
2771 ERR("Trying to create a trace chunk before version check");
2772 ret = -1;
2773 goto end_no_reply;
2774 }
2775
2776 if (session->major == 2 && session->minor < 11) {
2777 ERR("Chunk creation command is unsupported before 2.11");
2778 ret = -1;
2779 goto end_no_reply;
2780 }
2781
2782 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
2783 if (!lttng_buffer_view_is_valid(&header_view)) {
2784 ERR("Failed to receive payload of chunk creation command");
2785 ret = -1;
2786 goto end_no_reply;
2787 }
2788
2789 /* Convert to host endianness. */
2790 msg = (typeof(msg)) header_view.data;
2791 msg->chunk_id = be64toh(msg->chunk_id);
2792 msg->creation_timestamp = be64toh(msg->creation_timestamp);
2793 msg->override_name_length = be32toh(msg->override_name_length);
2794
2795 pthread_mutex_lock(&conn->session->lock);
2796 session->ongoing_rotation = true;
2797 if (session->current_trace_chunk &&
2798 !lttng_trace_chunk_get_name_overridden(session->current_trace_chunk)) {
2799 chunk_status = lttng_trace_chunk_rename_path(session->current_trace_chunk,
2800 DEFAULT_CHUNK_TMP_OLD_DIRECTORY);
2801 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2802 ERR("Failed to rename old chunk");
2803 ret = -1;
2804 reply_code = LTTNG_ERR_UNK;
2805 goto end;
2806 }
2807 }
2808 if (!session->current_trace_chunk) {
2809 if (!session->has_rotated) {
2810 new_path = "";
2811 } else {
2812 new_path = nullptr;
2813 }
2814 } else {
2815 new_path = DEFAULT_CHUNK_TMP_NEW_DIRECTORY;
2816 }
2817 chunk = lttng_trace_chunk_create(msg->chunk_id, msg->creation_timestamp, new_path);
2818 if (!chunk) {
2819 ERR("Failed to create trace chunk in trace chunk creation command");
2820 ret = -1;
2821 reply_code = LTTNG_ERR_NOMEM;
2822 goto end;
2823 }
2824 lttng_trace_chunk_set_fd_tracker(chunk, the_fd_tracker);
2825
2826 if (msg->override_name_length) {
2827 const char *name;
2828 const struct lttng_buffer_view chunk_name_view = lttng_buffer_view_from_view(
2829 payload, sizeof(*msg), msg->override_name_length);
2830
2831 if (!lttng_buffer_view_is_valid(&chunk_name_view)) {
2832 ERR("Invalid payload of chunk creation command (protocol error): buffer too short for expected name length");
2833 ret = -1;
2834 reply_code = LTTNG_ERR_INVALID;
2835 goto end;
2836 }
2837
2838 name = chunk_name_view.data;
2839 if (name[msg->override_name_length - 1]) {
2840 ERR("Invalid payload of chunk creation command (protocol error): name is not null-terminated");
2841 ret = -1;
2842 reply_code = LTTNG_ERR_INVALID;
2843 goto end;
2844 }
2845
2846 chunk_status = lttng_trace_chunk_override_name(chunk, chunk_name_view.data);
2847 switch (chunk_status) {
2848 case LTTNG_TRACE_CHUNK_STATUS_OK:
2849 break;
2850 case LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT:
2851 ERR("Failed to set the name of new trace chunk in trace chunk creation command (invalid name)");
2852 reply_code = LTTNG_ERR_INVALID;
2853 ret = -1;
2854 goto end;
2855 default:
2856 ERR("Failed to set the name of new trace chunk in trace chunk creation command (unknown error)");
2857 reply_code = LTTNG_ERR_UNK;
2858 ret = -1;
2859 goto end;
2860 }
2861 }
2862
2863 chunk_status = lttng_trace_chunk_set_credentials_current_user(chunk);
2864 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2865 reply_code = LTTNG_ERR_UNK;
2866 ret = -1;
2867 goto end;
2868 }
2869
2870 LTTNG_ASSERT(conn->session->output_directory);
2871 chunk_status = lttng_trace_chunk_set_as_owner(chunk, conn->session->output_directory);
2872 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2873 reply_code = LTTNG_ERR_UNK;
2874 ret = -1;
2875 goto end;
2876 }
2877
2878 published_chunk = sessiond_trace_chunk_registry_publish_chunk(
2879 sessiond_trace_chunk_registry,
2880 conn->session->sessiond_uuid,
2881 conn->session->id_sessiond.is_set ? conn->session->id_sessiond.value :
2882 conn->session->id,
2883 chunk);
2884 if (!published_chunk) {
2885 char uuid_str[LTTNG_UUID_STR_LEN];
2886
2887 lttng_uuid_to_str(conn->session->sessiond_uuid, uuid_str);
2888 ERR("Failed to publish chunk: sessiond_uuid = %s, session_id = %" PRIu64
2889 ", chunk_id = %" PRIu64,
2890 uuid_str,
2891 conn->session->id,
2892 msg->chunk_id);
2893 ret = -1;
2894 reply_code = LTTNG_ERR_NOMEM;
2895 goto end;
2896 }
2897
2898 if (conn->session->pending_closure_trace_chunk) {
2899 /*
2900 * Invalid; this means a second create_trace_chunk command was
2901 * received before a close_trace_chunk.
2902 */
2903 ERR("Invalid trace chunk close command received; a trace chunk is already waiting for a trace chunk close command");
2904 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2905 ret = -1;
2906 goto end;
2907 }
2908 conn->session->pending_closure_trace_chunk = conn->session->current_trace_chunk;
2909 conn->session->current_trace_chunk = published_chunk;
2910 published_chunk = nullptr;
2911 if (!conn->session->pending_closure_trace_chunk) {
2912 session->ongoing_rotation = false;
2913 }
2914 end:
2915 pthread_mutex_unlock(&conn->session->lock);
2916 reply.ret_code = htobe32((uint32_t) reply_code);
2917 send_ret = conn->sock->ops->sendmsg(
2918 conn->sock, &reply, sizeof(struct lttcomm_relayd_generic_reply), 0);
2919 if (send_ret < (ssize_t) sizeof(reply)) {
2920 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)", send_ret);
2921 ret = -1;
2922 }
2923 end_no_reply:
2924 lttng_trace_chunk_put(chunk);
2925 lttng_trace_chunk_put(published_chunk);
2926 return ret;
2927 }
2928
2929 /*
2930 * relay_close_trace_chunk: close a trace chunk
2931 */
2932 static int relay_close_trace_chunk(const struct lttcomm_relayd_hdr *recv_hdr
2933 __attribute__((unused)),
2934 struct relay_connection *conn,
2935 const struct lttng_buffer_view *payload)
2936 {
2937 int ret = 0, buf_ret;
2938 ssize_t send_ret;
2939 struct relay_session *session = conn->session;
2940 struct lttcomm_relayd_close_trace_chunk *msg;
2941 struct lttcomm_relayd_close_trace_chunk_reply reply = {};
2942 struct lttng_buffer_view header_view;
2943 struct lttng_trace_chunk *chunk = nullptr;
2944 enum lttng_error_code reply_code = LTTNG_OK;
2945 enum lttng_trace_chunk_status chunk_status;
2946 uint64_t chunk_id;
2947 LTTNG_OPTIONAL(enum lttng_trace_chunk_command_type) close_command = {};
2948 time_t close_timestamp;
2949 char closed_trace_chunk_path[LTTNG_PATH_MAX];
2950 size_t path_length = 0;
2951 const char *chunk_name = nullptr;
2952 struct lttng_dynamic_buffer reply_payload;
2953 const char *new_path;
2954
2955 lttng_dynamic_buffer_init(&reply_payload);
2956
2957 if (!session || !conn->version_check_done) {
2958 ERR("Trying to close a trace chunk before version check");
2959 ret = -1;
2960 goto end_no_reply;
2961 }
2962
2963 if (session->major == 2 && session->minor < 11) {
2964 ERR("Chunk close command is unsupported before 2.11");
2965 ret = -1;
2966 goto end_no_reply;
2967 }
2968
2969 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
2970 if (!lttng_buffer_view_is_valid(&header_view)) {
2971 ERR("Failed to receive payload of chunk close command");
2972 ret = -1;
2973 goto end_no_reply;
2974 }
2975
2976 /* Convert to host endianness. */
2977 msg = (typeof(msg)) header_view.data;
2978 chunk_id = be64toh(msg->chunk_id);
2979 close_timestamp = (time_t) be64toh(msg->close_timestamp);
2980 close_command.value = (lttng_trace_chunk_command_type) be32toh(msg->close_command.value);
2981 close_command.is_set = msg->close_command.is_set;
2982
2983 chunk = sessiond_trace_chunk_registry_get_chunk(sessiond_trace_chunk_registry,
2984 conn->session->sessiond_uuid,
2985 conn->session->id_sessiond.is_set ?
2986 conn->session->id_sessiond.value :
2987 conn->session->id,
2988 chunk_id);
2989 if (!chunk) {
2990 char uuid_str[LTTNG_UUID_STR_LEN];
2991
2992 lttng_uuid_to_str(conn->session->sessiond_uuid, uuid_str);
2993 ERR("Failed to find chunk to close: sessiond_uuid = %s, session_id = %" PRIu64
2994 ", chunk_id = %" PRIu64,
2995 uuid_str,
2996 conn->session->id,
2997 msg->chunk_id);
2998 ret = -1;
2999 reply_code = LTTNG_ERR_NOMEM;
3000 goto end;
3001 }
3002
3003 pthread_mutex_lock(&session->lock);
3004 if (close_command.is_set && close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE) {
3005 /*
3006 * Clear command. It is a protocol error to ask for a
3007 * clear on a relay which does not allow it. Querying
3008 * the configuration allows figuring out whether
3009 * clearing is allowed before doing the clear.
3010 */
3011 if (!opt_allow_clear) {
3012 ret = -1;
3013 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
3014 goto end_unlock_session;
3015 }
3016 }
3017 if (session->pending_closure_trace_chunk && session->pending_closure_trace_chunk != chunk) {
3018 ERR("Trace chunk close command for session \"%s\" does not target the trace chunk pending closure",
3019 session->session_name);
3020 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
3021 ret = -1;
3022 goto end_unlock_session;
3023 }
3024
3025 if (session->current_trace_chunk && session->current_trace_chunk != chunk &&
3026 !lttng_trace_chunk_get_name_overridden(session->current_trace_chunk)) {
3027 if (close_command.is_set &&
3028 close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE &&
3029 !session->has_rotated) {
3030 /* New chunk stays in session output directory. */
3031 new_path = "";
3032 } else {
3033 /* Use chunk name for new chunk. */
3034 new_path = nullptr;
3035 }
3036 /* Rename new chunk path. */
3037 chunk_status =
3038 lttng_trace_chunk_rename_path(session->current_trace_chunk, new_path);
3039 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
3040 ret = -1;
3041 goto end_unlock_session;
3042 }
3043 session->ongoing_rotation = false;
3044 }
3045 if ((!close_command.is_set ||
3046 close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION) &&
3047 !lttng_trace_chunk_get_name_overridden(chunk)) {
3048 const char *old_path;
3049
3050 if (!session->has_rotated) {
3051 old_path = "";
3052 } else {
3053 old_path = nullptr;
3054 }
3055 /* We need to move back the .tmp_old_chunk to its rightful place. */
3056 chunk_status = lttng_trace_chunk_rename_path(chunk, old_path);
3057 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
3058 ret = -1;
3059 goto end_unlock_session;
3060 }
3061 }
3062 chunk_status = lttng_trace_chunk_set_close_timestamp(chunk, close_timestamp);
3063 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
3064 ERR("Failed to set trace chunk close timestamp");
3065 ret = -1;
3066 reply_code = LTTNG_ERR_UNK;
3067 goto end_unlock_session;
3068 }
3069
3070 if (close_command.is_set) {
3071 chunk_status = lttng_trace_chunk_set_close_command(chunk, close_command.value);
3072 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
3073 ret = -1;
3074 reply_code = LTTNG_ERR_INVALID;
3075 goto end_unlock_session;
3076 }
3077 }
3078 chunk_status = lttng_trace_chunk_get_name(chunk, &chunk_name, nullptr);
3079 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
3080 ERR("Failed to get chunk name");
3081 ret = -1;
3082 reply_code = LTTNG_ERR_UNK;
3083 goto end_unlock_session;
3084 }
3085 if (!session->has_rotated && !session->snapshot) {
3086 ret = lttng_strncpy(closed_trace_chunk_path,
3087 session->output_path,
3088 sizeof(closed_trace_chunk_path));
3089 if (ret) {
3090 ERR("Failed to send trace chunk path: path length of %zu bytes exceeds the maximal allowed length of %zu bytes",
3091 strlen(session->output_path),
3092 sizeof(closed_trace_chunk_path));
3093 reply_code = LTTNG_ERR_NOMEM;
3094 ret = -1;
3095 goto end_unlock_session;
3096 }
3097 } else {
3098 if (session->snapshot) {
3099 ret = snprintf(closed_trace_chunk_path,
3100 sizeof(closed_trace_chunk_path),
3101 "%s/%s",
3102 session->output_path,
3103 chunk_name);
3104 } else {
3105 ret = snprintf(closed_trace_chunk_path,
3106 sizeof(closed_trace_chunk_path),
3107 "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY "/%s",
3108 session->output_path,
3109 chunk_name);
3110 }
3111 if (ret < 0 || ret == sizeof(closed_trace_chunk_path)) {
3112 ERR("Failed to format closed trace chunk resulting path");
3113 reply_code = ret < 0 ? LTTNG_ERR_UNK : LTTNG_ERR_NOMEM;
3114 ret = -1;
3115 goto end_unlock_session;
3116 }
3117 }
3118 if (close_command.is_set &&
3119 close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED) {
3120 session->has_rotated = true;
3121 }
3122 DBG("Reply chunk path on close: %s", closed_trace_chunk_path);
3123 path_length = strlen(closed_trace_chunk_path) + 1;
3124 if (path_length > UINT32_MAX) {
3125 ERR("Closed trace chunk path exceeds the maximal length allowed by the protocol");
3126 ret = -1;
3127 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
3128 goto end_unlock_session;
3129 }
3130
3131 if (session->current_trace_chunk == chunk) {
3132 /*
3133 * After a trace chunk close command, no new streams
3134 * referencing the chunk may be created. Hence, on the
3135 * event that no new trace chunk have been created for
3136 * the session, the reference to the current trace chunk
3137 * is released in order to allow it to be reclaimed when
3138 * the last stream releases its reference to it.
3139 */
3140 lttng_trace_chunk_put(session->current_trace_chunk);
3141 session->current_trace_chunk = nullptr;
3142 }
3143 lttng_trace_chunk_put(session->pending_closure_trace_chunk);
3144 session->pending_closure_trace_chunk = nullptr;
3145 end_unlock_session:
3146 pthread_mutex_unlock(&session->lock);
3147
3148 end:
3149 reply.generic.ret_code = htobe32((uint32_t) reply_code);
3150 reply.path_length = htobe32((uint32_t) path_length);
3151 buf_ret = lttng_dynamic_buffer_append(&reply_payload, &reply, sizeof(reply));
3152 if (buf_ret) {
3153 ERR("Failed to append \"close trace chunk\" command reply header to payload buffer");
3154 goto end_no_reply;
3155 }
3156
3157 if (reply_code == LTTNG_OK) {
3158 buf_ret = lttng_dynamic_buffer_append(
3159 &reply_payload, closed_trace_chunk_path, path_length);
3160 if (buf_ret) {
3161 ERR("Failed to append \"close trace chunk\" command reply path to payload buffer");
3162 goto end_no_reply;
3163 }
3164 }
3165
3166 send_ret = conn->sock->ops->sendmsg(conn->sock, reply_payload.data, reply_payload.size, 0);
3167 if (send_ret < reply_payload.size) {
3168 ERR("Failed to send \"close trace chunk\" command reply of %zu bytes (ret = %zd)",
3169 reply_payload.size,
3170 send_ret);
3171 ret = -1;
3172 goto end_no_reply;
3173 }
3174 end_no_reply:
3175 lttng_trace_chunk_put(chunk);
3176 lttng_dynamic_buffer_reset(&reply_payload);
3177 return ret;
3178 }
3179
3180 /*
3181 * relay_trace_chunk_exists: check if a trace chunk exists
3182 */
3183 static int relay_trace_chunk_exists(const struct lttcomm_relayd_hdr *recv_hdr
3184 __attribute__((unused)),
3185 struct relay_connection *conn,
3186 const struct lttng_buffer_view *payload)
3187 {
3188 int ret = 0;
3189 ssize_t send_ret;
3190 struct relay_session *session = conn->session;
3191 struct lttcomm_relayd_trace_chunk_exists *msg;
3192 struct lttcomm_relayd_trace_chunk_exists_reply reply = {};
3193 struct lttng_buffer_view header_view;
3194 uint64_t chunk_id;
3195 bool chunk_exists;
3196
3197 if (!session || !conn->version_check_done) {
3198 ERR("Trying to check for the presence of a trace chunk before version check");
3199 ret = -1;
3200 goto end_no_reply;
3201 }
3202
3203 if (session->major == 2 && session->minor < 11) {
3204 ERR("Chunk exists command is unsupported before 2.11");
3205 ret = -1;
3206 goto end_no_reply;
3207 }
3208
3209 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
3210 if (!lttng_buffer_view_is_valid(&header_view)) {
3211 ERR("Failed to receive payload of chunk exists command");
3212 ret = -1;
3213 goto end_no_reply;
3214 }
3215
3216 /* Convert to host endianness. */
3217 msg = (typeof(msg)) header_view.data;
3218 chunk_id = be64toh(msg->chunk_id);
3219
3220 ret = sessiond_trace_chunk_registry_chunk_exists(sessiond_trace_chunk_registry,
3221 conn->session->sessiond_uuid,
3222 conn->session->id,
3223 chunk_id,
3224 &chunk_exists);
3225 /*
3226 * If ret is not 0, send the reply and report the error to the caller.
3227 * It is a protocol (or internal) error and the session/connection
3228 * should be torn down.
3229 */
3230 reply.generic.ret_code =
3231 htobe32((uint32_t) (ret == 0 ? LTTNG_OK : LTTNG_ERR_INVALID_PROTOCOL));
3232 reply.trace_chunk_exists = ret == 0 ? chunk_exists : 0;
3233
3234 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
3235 if (send_ret < (ssize_t) sizeof(reply)) {
3236 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)", send_ret);
3237 ret = -1;
3238 }
3239 end_no_reply:
3240 return ret;
3241 }
3242
3243 /*
3244 * relay_get_configuration: query whether feature is available
3245 */
3246 static int relay_get_configuration(const struct lttcomm_relayd_hdr *recv_hdr
3247 __attribute__((unused)),
3248 struct relay_connection *conn,
3249 const struct lttng_buffer_view *payload)
3250 {
3251 int ret = 0;
3252 ssize_t send_ret;
3253 struct lttcomm_relayd_get_configuration *msg;
3254 struct lttcomm_relayd_get_configuration_reply reply = {};
3255 struct lttng_buffer_view header_view;
3256 uint64_t query_flags = 0;
3257 uint64_t result_flags = 0;
3258
3259 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
3260 if (!lttng_buffer_view_is_valid(&header_view)) {
3261 ERR("Failed to receive payload of chunk close command");
3262 ret = -1;
3263 goto end_no_reply;
3264 }
3265
3266 /* Convert to host endianness. */
3267 msg = (typeof(msg)) header_view.data;
3268 query_flags = be64toh(msg->query_flags);
3269
3270 if (query_flags) {
3271 ret = LTTNG_ERR_INVALID_PROTOCOL;
3272 goto reply;
3273 }
3274 if (opt_allow_clear) {
3275 result_flags |= LTTCOMM_RELAYD_CONFIGURATION_FLAG_CLEAR_ALLOWED;
3276 }
3277 ret = 0;
3278 reply:
3279 reply.generic.ret_code =
3280 htobe32((uint32_t) (ret == 0 ? LTTNG_OK : LTTNG_ERR_INVALID_PROTOCOL));
3281 reply.relayd_configuration_flags = htobe64(result_flags);
3282
3283 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
3284 if (send_ret < (ssize_t) sizeof(reply)) {
3285 ERR("Failed to send \"get configuration\" command reply (ret = %zd)", send_ret);
3286 ret = -1;
3287 }
3288 end_no_reply:
3289 return ret;
3290 }
3291
3292 static int relay_process_control_command(struct relay_connection *conn,
3293 const struct lttcomm_relayd_hdr *header,
3294 const struct lttng_buffer_view *payload)
3295 {
3296 int ret = 0;
3297
3298 DBG3("Processing \"%s\" command for socket %i",
3299 lttcomm_relayd_command_str((lttcomm_relayd_command) header->cmd),
3300 conn->sock->fd);
3301 switch (header->cmd) {
3302 case RELAYD_CREATE_SESSION:
3303 ret = relay_create_session(header, conn, payload);
3304 break;
3305 case RELAYD_ADD_STREAM:
3306 ret = relay_add_stream(header, conn, payload);
3307 break;
3308 case RELAYD_START_DATA:
3309 ret = relay_start(header, conn, payload);
3310 break;
3311 case RELAYD_SEND_METADATA:
3312 ret = relay_recv_metadata(header, conn, payload);
3313 break;
3314 case RELAYD_VERSION:
3315 ret = relay_send_version(header, conn, payload);
3316 break;
3317 case RELAYD_CLOSE_STREAM:
3318 ret = relay_close_stream(header, conn, payload);
3319 break;
3320 case RELAYD_DATA_PENDING:
3321 ret = relay_data_pending(header, conn, payload);
3322 break;
3323 case RELAYD_QUIESCENT_CONTROL:
3324 ret = relay_quiescent_control(header, conn, payload);
3325 break;
3326 case RELAYD_BEGIN_DATA_PENDING:
3327 ret = relay_begin_data_pending(header, conn, payload);
3328 break;
3329 case RELAYD_END_DATA_PENDING:
3330 ret = relay_end_data_pending(header, conn, payload);
3331 break;
3332 case RELAYD_SEND_INDEX:
3333 ret = relay_recv_index(header, conn, payload);
3334 break;
3335 case RELAYD_STREAMS_SENT:
3336 ret = relay_streams_sent(header, conn, payload);
3337 break;
3338 case RELAYD_RESET_METADATA:
3339 ret = relay_reset_metadata(header, conn, payload);
3340 break;
3341 case RELAYD_ROTATE_STREAMS:
3342 ret = relay_rotate_session_streams(header, conn, payload);
3343 break;
3344 case RELAYD_CREATE_TRACE_CHUNK:
3345 ret = relay_create_trace_chunk(header, conn, payload);
3346 break;
3347 case RELAYD_CLOSE_TRACE_CHUNK:
3348 ret = relay_close_trace_chunk(header, conn, payload);
3349 break;
3350 case RELAYD_TRACE_CHUNK_EXISTS:
3351 ret = relay_trace_chunk_exists(header, conn, payload);
3352 break;
3353 case RELAYD_GET_CONFIGURATION:
3354 ret = relay_get_configuration(header, conn, payload);
3355 break;
3356 case RELAYD_UPDATE_SYNC_INFO:
3357 default:
3358 ERR("Received unknown command (%u)", header->cmd);
3359 relay_unknown_command(conn);
3360 ret = -1;
3361 goto end;
3362 }
3363
3364 end:
3365 return ret;
3366 }
3367
3368 static enum relay_connection_status
3369 relay_process_control_receive_payload(struct relay_connection *conn)
3370 {
3371 int ret = 0;
3372 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
3373 struct lttng_dynamic_buffer *reception_buffer = &conn->protocol.ctrl.reception_buffer;
3374 struct ctrl_connection_state_receive_payload *state =
3375 &conn->protocol.ctrl.state.receive_payload;
3376 struct lttng_buffer_view payload_view;
3377
3378 if (state->left_to_receive == 0) {
3379 /* Short-circuit for payload-less commands. */
3380 goto reception_complete;
3381 }
3382
3383 ret = conn->sock->ops->recvmsg(conn->sock,
3384 reception_buffer->data + state->received,
3385 state->left_to_receive,
3386 MSG_DONTWAIT);
3387 if (ret < 0) {
3388 DIAGNOSTIC_PUSH
3389 DIAGNOSTIC_IGNORE_LOGICAL_OP
3390 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3391 DIAGNOSTIC_POP
3392 PERROR("Unable to receive command payload on sock %d", conn->sock->fd);
3393 status = RELAY_CONNECTION_STATUS_ERROR;
3394 }
3395 goto end;
3396 } else if (ret == 0) {
3397 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
3398 status = RELAY_CONNECTION_STATUS_CLOSED;
3399 goto end;
3400 }
3401
3402 LTTNG_ASSERT(ret > 0);
3403 LTTNG_ASSERT(ret <= state->left_to_receive);
3404
3405 state->left_to_receive -= ret;
3406 state->received += ret;
3407
3408 if (state->left_to_receive > 0) {
3409 /*
3410 * Can't transition to the protocol's next state, wait to
3411 * receive the rest of the header.
3412 */
3413 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
3414 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
3415 state->received,
3416 state->left_to_receive,
3417 conn->sock->fd);
3418 goto end;
3419 }
3420
3421 reception_complete:
3422 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64 " bytes",
3423 conn->sock->fd,
3424 state->received);
3425 /*
3426 * The payload required to process the command has been received.
3427 * A view to the reception buffer is forwarded to the various
3428 * commands and the state of the control is reset on success.
3429 *
3430 * Commands are responsible for sending their reply to the peer.
3431 */
3432 payload_view = lttng_buffer_view_from_dynamic_buffer(reception_buffer, 0, -1);
3433 ret = relay_process_control_command(conn, &state->header, &payload_view);
3434 if (ret < 0) {
3435 status = RELAY_CONNECTION_STATUS_ERROR;
3436 goto end;
3437 }
3438
3439 ret = connection_reset_protocol_state(conn);
3440 if (ret) {
3441 status = RELAY_CONNECTION_STATUS_ERROR;
3442 }
3443 end:
3444 return status;
3445 }
3446
3447 static enum relay_connection_status
3448 relay_process_control_receive_header(struct relay_connection *conn)
3449 {
3450 int ret = 0;
3451 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
3452 struct lttcomm_relayd_hdr header;
3453 struct lttng_dynamic_buffer *reception_buffer = &conn->protocol.ctrl.reception_buffer;
3454 struct ctrl_connection_state_receive_header *state =
3455 &conn->protocol.ctrl.state.receive_header;
3456
3457 LTTNG_ASSERT(state->left_to_receive != 0);
3458
3459 ret = conn->sock->ops->recvmsg(conn->sock,
3460 reception_buffer->data + state->received,
3461 state->left_to_receive,
3462 MSG_DONTWAIT);
3463 if (ret < 0) {
3464 DIAGNOSTIC_PUSH
3465 DIAGNOSTIC_IGNORE_LOGICAL_OP
3466 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3467 DIAGNOSTIC_POP
3468 PERROR("Unable to receive control command header on sock %d",
3469 conn->sock->fd);
3470 status = RELAY_CONNECTION_STATUS_ERROR;
3471 }
3472 goto end;
3473 } else if (ret == 0) {
3474 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
3475 status = RELAY_CONNECTION_STATUS_CLOSED;
3476 goto end;
3477 }
3478
3479 LTTNG_ASSERT(ret > 0);
3480 LTTNG_ASSERT(ret <= state->left_to_receive);
3481
3482 state->left_to_receive -= ret;
3483 state->received += ret;
3484
3485 if (state->left_to_receive > 0) {
3486 /*
3487 * Can't transition to the protocol's next state, wait to
3488 * receive the rest of the header.
3489 */
3490 DBG3("Partial reception of control connection protocol header (received %" PRIu64
3491 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
3492 state->received,
3493 state->left_to_receive,
3494 conn->sock->fd);
3495 goto end;
3496 }
3497
3498 /* Transition to next state: receiving the command's payload. */
3499 conn->protocol.ctrl.state_id = CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD;
3500 memcpy(&header, reception_buffer->data, sizeof(header));
3501 header.circuit_id = be64toh(header.circuit_id);
3502 header.data_size = be64toh(header.data_size);
3503 header.cmd = be32toh(header.cmd);
3504 header.cmd_version = be32toh(header.cmd_version);
3505 memcpy(&conn->protocol.ctrl.state.receive_payload.header, &header, sizeof(header));
3506
3507 DBG("Done receiving control command header: fd = %i, cmd = %s, cmd_version = %" PRIu32
3508 ", payload size = %" PRIu64 " bytes",
3509 conn->sock->fd,
3510 lttcomm_relayd_command_str((enum lttcomm_relayd_command) header.cmd),
3511 header.cmd_version,
3512 header.data_size);
3513
3514 if (header.data_size > DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE) {
3515 ERR("Command header indicates a payload (%" PRIu64
3516 " bytes) that exceeds the maximal payload size allowed on a control connection.",
3517 header.data_size);
3518 status = RELAY_CONNECTION_STATUS_ERROR;
3519 goto end;
3520 }
3521
3522 conn->protocol.ctrl.state.receive_payload.left_to_receive = header.data_size;
3523 conn->protocol.ctrl.state.receive_payload.received = 0;
3524 ret = lttng_dynamic_buffer_set_size(reception_buffer, header.data_size);
3525 if (ret) {
3526 status = RELAY_CONNECTION_STATUS_ERROR;
3527 goto end;
3528 }
3529
3530 if (header.data_size == 0) {
3531 /*
3532 * Manually invoke the next state as the poll loop
3533 * will not wake-up to allow us to proceed further.
3534 */
3535 status = relay_process_control_receive_payload(conn);
3536 }
3537 end:
3538 return status;
3539 }
3540
3541 /*
3542 * Process the commands received on the control socket
3543 */
3544 static enum relay_connection_status relay_process_control(struct relay_connection *conn)
3545 {
3546 enum relay_connection_status status;
3547
3548 switch (conn->protocol.ctrl.state_id) {
3549 case CTRL_CONNECTION_STATE_RECEIVE_HEADER:
3550 status = relay_process_control_receive_header(conn);
3551 break;
3552 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD:
3553 status = relay_process_control_receive_payload(conn);
3554 break;
3555 default:
3556 ERR("Unknown control connection protocol state encountered.");
3557 abort();
3558 }
3559
3560 return status;
3561 }
3562
3563 static enum relay_connection_status relay_process_data_receive_header(struct relay_connection *conn)
3564 {
3565 int ret;
3566 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
3567 struct data_connection_state_receive_header *state =
3568 &conn->protocol.data.state.receive_header;
3569 struct lttcomm_relayd_data_hdr header;
3570 struct relay_stream *stream;
3571
3572 LTTNG_ASSERT(state->left_to_receive != 0);
3573
3574 ret = conn->sock->ops->recvmsg(conn->sock,
3575 state->header_reception_buffer + state->received,
3576 state->left_to_receive,
3577 MSG_DONTWAIT);
3578 if (ret < 0) {
3579 DIAGNOSTIC_PUSH
3580 DIAGNOSTIC_IGNORE_LOGICAL_OP
3581 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3582 DIAGNOSTIC_POP
3583 PERROR("Unable to receive data header on sock %d", conn->sock->fd);
3584 status = RELAY_CONNECTION_STATUS_ERROR;
3585 }
3586 goto end;
3587 } else if (ret == 0) {
3588 /* Orderly shutdown. Not necessary to print an error. */
3589 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
3590 status = RELAY_CONNECTION_STATUS_CLOSED;
3591 goto end;
3592 }
3593
3594 LTTNG_ASSERT(ret > 0);
3595 LTTNG_ASSERT(ret <= state->left_to_receive);
3596
3597 state->left_to_receive -= ret;
3598 state->received += ret;
3599
3600 if (state->left_to_receive > 0) {
3601 /*
3602 * Can't transition to the protocol's next state, wait to
3603 * receive the rest of the header.
3604 */
3605 DBG3("Partial reception of data connection header (received %" PRIu64
3606 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
3607 state->received,
3608 state->left_to_receive,
3609 conn->sock->fd);
3610 goto end;
3611 }
3612
3613 /* Transition to next state: receiving the payload. */
3614 conn->protocol.data.state_id = DATA_CONNECTION_STATE_RECEIVE_PAYLOAD;
3615
3616 memcpy(&header, state->header_reception_buffer, sizeof(header));
3617 header.circuit_id = be64toh(header.circuit_id);
3618 header.stream_id = be64toh(header.stream_id);
3619 header.data_size = be32toh(header.data_size);
3620 header.net_seq_num = be64toh(header.net_seq_num);
3621 header.padding_size = be32toh(header.padding_size);
3622 memcpy(&conn->protocol.data.state.receive_payload.header, &header, sizeof(header));
3623
3624 conn->protocol.data.state.receive_payload.left_to_receive = header.data_size;
3625 conn->protocol.data.state.receive_payload.received = 0;
3626 conn->protocol.data.state.receive_payload.rotate_index = false;
3627
3628 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
3629 ", stream_id = %" PRIu64 ", data_size = %" PRIu32 ", net_seq_num = %" PRIu64
3630 ", padding_size = %" PRIu32,
3631 conn->sock->fd,
3632 header.circuit_id,
3633 header.stream_id,
3634 header.data_size,
3635 header.net_seq_num,
3636 header.padding_size);
3637
3638 stream = stream_get_by_id(header.stream_id);
3639 if (!stream) {
3640 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64,
3641 header.stream_id);
3642 /* Protocol error. */
3643 status = RELAY_CONNECTION_STATUS_ERROR;
3644 goto end;
3645 }
3646
3647 pthread_mutex_lock(&stream->lock);
3648 /* Prepare stream for the reception of a new packet. */
3649 ret = stream_init_packet(
3650 stream, header.data_size, &conn->protocol.data.state.receive_payload.rotate_index);
3651 pthread_mutex_unlock(&stream->lock);
3652 if (ret) {
3653 ERR("Failed to rotate stream output file");
3654 status = RELAY_CONNECTION_STATUS_ERROR;
3655 goto end_stream_unlock;
3656 }
3657
3658 end_stream_unlock:
3659 stream_put(stream);
3660 end:
3661 return status;
3662 }
3663
3664 static enum relay_connection_status
3665 relay_process_data_receive_payload(struct relay_connection *conn)
3666 {
3667 int ret;
3668 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
3669 struct relay_stream *stream;
3670 struct data_connection_state_receive_payload *state =
3671 &conn->protocol.data.state.receive_payload;
3672 const size_t chunk_size = RECV_DATA_BUFFER_SIZE;
3673 char data_buffer[chunk_size];
3674 bool partial_recv = false;
3675 bool new_stream = false, close_requested = false, index_flushed = false;
3676 uint64_t left_to_receive = state->left_to_receive;
3677 struct relay_session *session;
3678
3679 DBG3("Receiving data for stream id %" PRIu64 " seqnum %" PRIu64 ", %" PRIu64
3680 " bytes received, %" PRIu64 " bytes left to receive",
3681 state->header.stream_id,
3682 state->header.net_seq_num,
3683 state->received,
3684 left_to_receive);
3685
3686 stream = stream_get_by_id(state->header.stream_id);
3687 if (!stream) {
3688 /* Protocol error. */
3689 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64,
3690 state->header.stream_id);
3691 status = RELAY_CONNECTION_STATUS_ERROR;
3692 goto end;
3693 }
3694
3695 pthread_mutex_lock(&stream->lock);
3696 session = stream->trace->session;
3697 if (!conn->session) {
3698 ret = connection_set_session(conn, session);
3699 if (ret) {
3700 status = RELAY_CONNECTION_STATUS_ERROR;
3701 goto end_stream_unlock;
3702 }
3703 }
3704
3705 /*
3706 * The size of the "chunk" received on any iteration is bounded by:
3707 * - the data left to receive,
3708 * - the data immediately available on the socket,
3709 * - the on-stack data buffer
3710 */
3711 while (left_to_receive > 0 && !partial_recv) {
3712 size_t recv_size = std::min<uint64_t>(left_to_receive, chunk_size);
3713 struct lttng_buffer_view packet_chunk;
3714
3715 ret = conn->sock->ops->recvmsg(conn->sock, data_buffer, recv_size, MSG_DONTWAIT);
3716 if (ret < 0) {
3717 DIAGNOSTIC_PUSH
3718 DIAGNOSTIC_IGNORE_LOGICAL_OP
3719 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3720 DIAGNOSTIC_POP
3721 PERROR("Socket %d error", conn->sock->fd);
3722 status = RELAY_CONNECTION_STATUS_ERROR;
3723 }
3724 goto end_stream_unlock;
3725 } else if (ret == 0) {
3726 /* No more data ready to be consumed on socket. */
3727 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64,
3728 state->header.stream_id);
3729 status = RELAY_CONNECTION_STATUS_CLOSED;
3730 break;
3731 } else if (ret < (int) recv_size) {
3732 /*
3733 * All the data available on the socket has been
3734 * consumed.
3735 */
3736 partial_recv = true;
3737 recv_size = ret;
3738 }
3739
3740 packet_chunk = lttng_buffer_view_init(data_buffer, 0, recv_size);
3741 LTTNG_ASSERT(packet_chunk.data);
3742
3743 ret = stream_write(stream, &packet_chunk, 0);
3744 if (ret) {
3745 ERR("Relay error writing data to file");
3746 status = RELAY_CONNECTION_STATUS_ERROR;
3747 goto end_stream_unlock;
3748 }
3749
3750 left_to_receive -= recv_size;
3751 state->received += recv_size;
3752 state->left_to_receive = left_to_receive;
3753 }
3754
3755 if (state->left_to_receive > 0) {
3756 /*
3757 * Did not receive all the data expected, wait for more data to
3758 * become available on the socket.
3759 */
3760 DBG3("Partial receive on data connection of stream id %" PRIu64 ", %" PRIu64
3761 " bytes received, %" PRIu64 " bytes left to receive",
3762 state->header.stream_id,
3763 state->received,
3764 state->left_to_receive);
3765 goto end_stream_unlock;
3766 }
3767
3768 ret = stream_write(stream, nullptr, state->header.padding_size);
3769 if (ret) {
3770 status = RELAY_CONNECTION_STATUS_ERROR;
3771 goto end_stream_unlock;
3772 }
3773
3774 if (session_streams_have_index(session)) {
3775 ret = stream_update_index(stream,
3776 state->header.net_seq_num,
3777 state->rotate_index,
3778 &index_flushed,
3779 state->header.data_size + state->header.padding_size);
3780 if (ret < 0) {
3781 ERR("Failed to update index: stream %" PRIu64 " net_seq_num %" PRIu64
3782 " ret %d",
3783 stream->stream_handle,
3784 state->header.net_seq_num,
3785 ret);
3786 status = RELAY_CONNECTION_STATUS_ERROR;
3787 goto end_stream_unlock;
3788 }
3789 }
3790
3791 if (stream->prev_data_seq == -1ULL) {
3792 new_stream = true;
3793 }
3794
3795 ret = stream_complete_packet(stream,
3796 state->header.data_size + state->header.padding_size,
3797 state->header.net_seq_num,
3798 index_flushed);
3799 if (ret) {
3800 status = RELAY_CONNECTION_STATUS_ERROR;
3801 goto end_stream_unlock;
3802 }
3803
3804 /*
3805 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3806 * contents of *state which are aliased (union) to the same location as
3807 * the new state. Don't use it beyond this point.
3808 */
3809 connection_reset_protocol_state(conn);
3810 state = nullptr;
3811
3812 end_stream_unlock:
3813 close_requested = stream->close_requested;
3814 pthread_mutex_unlock(&stream->lock);
3815 if (close_requested && left_to_receive == 0) {
3816 try_stream_close(stream);
3817 }
3818
3819 if (new_stream) {
3820 pthread_mutex_lock(&session->lock);
3821 uatomic_set(&session->new_streams, 1);
3822 pthread_mutex_unlock(&session->lock);
3823 }
3824
3825 stream_put(stream);
3826 end:
3827 return status;
3828 }
3829
3830 /*
3831 * relay_process_data: Process the data received on the data socket
3832 */
3833 static enum relay_connection_status relay_process_data(struct relay_connection *conn)
3834 {
3835 enum relay_connection_status status;
3836
3837 switch (conn->protocol.data.state_id) {
3838 case DATA_CONNECTION_STATE_RECEIVE_HEADER:
3839 status = relay_process_data_receive_header(conn);
3840 break;
3841 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD:
3842 status = relay_process_data_receive_payload(conn);
3843 break;
3844 default:
3845 ERR("Unexpected data connection communication state.");
3846 abort();
3847 }
3848
3849 return status;
3850 }
3851
3852 static void cleanup_connection_pollfd(struct lttng_poll_event *events, int pollfd)
3853 {
3854 int ret;
3855
3856 (void) lttng_poll_del(events, pollfd);
3857
3858 ret = fd_tracker_close_unsuspendable_fd(
3859 the_fd_tracker, &pollfd, 1, fd_tracker_util_close_fd, nullptr);
3860 if (ret < 0) {
3861 ERR("Closing pollfd %d", pollfd);
3862 }
3863 }
3864
3865 static void relay_thread_close_connection(struct lttng_poll_event *events,
3866 int pollfd,
3867 struct relay_connection *conn)
3868 {
3869 const char *type_str;
3870
3871 switch (conn->type) {
3872 case RELAY_DATA:
3873 type_str = "Data";
3874 break;
3875 case RELAY_CONTROL:
3876 type_str = "Control";
3877 break;
3878 case RELAY_VIEWER_COMMAND:
3879 type_str = "Viewer Command";
3880 break;
3881 case RELAY_VIEWER_NOTIFICATION:
3882 type_str = "Viewer Notification";
3883 break;
3884 default:
3885 type_str = "Unknown";
3886 }
3887 cleanup_connection_pollfd(events, pollfd);
3888 connection_put(conn);
3889 DBG("%s connection closed with %d", type_str, pollfd);
3890 }
3891
3892 /*
3893 * This thread does the actual work
3894 */
3895 static void *relay_thread_worker(void *data __attribute__((unused)))
3896 {
3897 int ret, err = -1, last_seen_data_fd = -1;
3898 uint32_t nb_fd;
3899 struct lttng_poll_event events;
3900 struct lttng_ht *relay_connections_ht;
3901 struct lttng_ht_iter iter;
3902 struct relay_connection *destroy_conn = nullptr;
3903
3904 DBG("[thread] Relay worker started");
3905
3906 rcu_register_thread();
3907
3908 health_register(health_relayd, HEALTH_RELAYD_TYPE_WORKER);
3909
3910 if (testpoint(relayd_thread_worker)) {
3911 goto error_testpoint;
3912 }
3913
3914 health_code_update();
3915
3916 /* table of connections indexed on socket */
3917 relay_connections_ht = lttng_ht_new(0, LTTNG_HT_TYPE_ULONG);
3918 if (!relay_connections_ht) {
3919 goto relay_connections_ht_error;
3920 }
3921
3922 ret = create_named_thread_poll_set(&events, 2, "Worker thread epoll");
3923 if (ret < 0) {
3924 goto error_poll_create;
3925 }
3926
3927 ret = lttng_poll_add(&events, relay_conn_pipe[0], LPOLLIN | LPOLLRDHUP);
3928 if (ret < 0) {
3929 goto error;
3930 }
3931
3932 restart:
3933 while (true) {
3934 int idx = -1, i, seen_control = 0, last_notdel_data_fd = -1;
3935
3936 health_code_update();
3937
3938 /* Infinite blocking call, waiting for transmission */
3939 DBG3("Relayd worker thread polling...");
3940 health_poll_entry();
3941 ret = lttng_poll_wait(&events, -1);
3942 health_poll_exit();
3943 if (ret < 0) {
3944 /*
3945 * Restart interrupted system call.
3946 */
3947 if (errno == EINTR) {
3948 goto restart;
3949 }
3950 goto error;
3951 }
3952
3953 nb_fd = ret;
3954
3955 /*
3956 * Process control. The control connection is
3957 * prioritized so we don't starve it with high
3958 * throughput tracing data on the data connection.
3959 */
3960 for (i = 0; i < nb_fd; i++) {
3961 /* Fetch once the poll data */
3962 const auto revents = LTTNG_POLL_GETEV(&events, i);
3963 const auto pollfd = LTTNG_POLL_GETFD(&events, i);
3964
3965 health_code_update();
3966
3967 /* Activity on thread quit pipe, exiting. */
3968 if (relayd_is_thread_quit_pipe(pollfd)) {
3969 DBG("Activity on thread quit pipe");
3970 err = 0;
3971 goto exit;
3972 }
3973
3974 /* Inspect the relay conn pipe for new connection */
3975 if (pollfd == relay_conn_pipe[0]) {
3976 if (revents & LPOLLIN) {
3977 struct relay_connection *conn;
3978
3979 ret = lttng_read(relay_conn_pipe[0],
3980 &conn,
3981 sizeof(conn)); /* NOLINT sizeof used on a
3982 pointer. */
3983 if (ret < 0) {
3984 goto error;
3985 }
3986 ret = lttng_poll_add(
3987 &events, conn->sock->fd, LPOLLIN | LPOLLRDHUP);
3988 if (ret) {
3989 ERR("Failed to add new connection file descriptor to poll set");
3990 goto error;
3991 }
3992 connection_ht_add(relay_connections_ht, conn);
3993 DBG("Connection socket %d added", conn->sock->fd);
3994 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
3995 ERR("Relay connection pipe error");
3996 goto error;
3997 } else {
3998 ERR("Unexpected poll events %u for sock %d",
3999 revents,
4000 pollfd);
4001 goto error;
4002 }
4003 } else {
4004 struct relay_connection *ctrl_conn;
4005
4006 ctrl_conn = connection_get_by_sock(relay_connections_ht, pollfd);
4007 /* If not found, there is a synchronization issue. */
4008 LTTNG_ASSERT(ctrl_conn);
4009
4010 if (ctrl_conn->type == RELAY_DATA) {
4011 if (revents & LPOLLIN) {
4012 /*
4013 * Flag the last seen data fd not deleted. It will
4014 * be used as the last seen fd if any fd gets
4015 * deleted in this first loop.
4016 */
4017 last_notdel_data_fd = pollfd;
4018 }
4019 goto put_ctrl_connection;
4020 }
4021 LTTNG_ASSERT(ctrl_conn->type == RELAY_CONTROL);
4022
4023 if (revents & LPOLLIN) {
4024 enum relay_connection_status status;
4025
4026 status = relay_process_control(ctrl_conn);
4027 if (status != RELAY_CONNECTION_STATUS_OK) {
4028 /*
4029 * On socket error flag the session as aborted to
4030 * force the cleanup of its stream otherwise it can
4031 * leak during the lifetime of the relayd.
4032 *
4033 * This prevents situations in which streams can be
4034 * left opened because an index was received, the
4035 * control connection is closed, and the data
4036 * connection is closed (uncleanly) before the
4037 * packet's data provided.
4038 *
4039 * Since the control connection encountered an
4040 * error, it is okay to be conservative and close
4041 * the session right now as we can't rely on the
4042 * protocol being respected anymore.
4043 */
4044 if (status == RELAY_CONNECTION_STATUS_ERROR) {
4045 session_abort(ctrl_conn->session);
4046 }
4047
4048 /* Clear the connection on error or close. */
4049 relay_thread_close_connection(
4050 &events, pollfd, ctrl_conn);
4051 }
4052 seen_control = 1;
4053 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
4054 relay_thread_close_connection(&events, pollfd, ctrl_conn);
4055 if (last_seen_data_fd == pollfd) {
4056 last_seen_data_fd = last_notdel_data_fd;
4057 }
4058 } else {
4059 ERR("Unexpected poll events %u for control sock %d",
4060 revents,
4061 pollfd);
4062 connection_put(ctrl_conn);
4063 goto error;
4064 }
4065 put_ctrl_connection:
4066 connection_put(ctrl_conn);
4067 }
4068 }
4069
4070 /*
4071 * The last loop handled a control request, go back to poll to make
4072 * sure we prioritise the control socket.
4073 */
4074 if (seen_control) {
4075 continue;
4076 }
4077
4078 if (last_seen_data_fd >= 0) {
4079 for (i = 0; i < nb_fd; i++) {
4080 int pollfd = LTTNG_POLL_GETFD(&events, i);
4081
4082 health_code_update();
4083
4084 if (last_seen_data_fd == pollfd) {
4085 idx = i;
4086 break;
4087 }
4088 }
4089 }
4090
4091 /* Process data connection. */
4092 for (i = idx + 1; i < nb_fd; i++) {
4093 /* Fetch the poll data. */
4094 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
4095 int pollfd = LTTNG_POLL_GETFD(&events, i);
4096 struct relay_connection *data_conn;
4097
4098 health_code_update();
4099
4100 if (!revents) {
4101 /* No activity for this FD (poll implementation). */
4102 continue;
4103 }
4104
4105 /* Skip the command pipe. It's handled in the first loop. */
4106 if (pollfd == relay_conn_pipe[0]) {
4107 continue;
4108 }
4109
4110 data_conn = connection_get_by_sock(relay_connections_ht, pollfd);
4111 if (!data_conn) {
4112 /* Skip it. Might be removed before. */
4113 continue;
4114 }
4115 if (data_conn->type == RELAY_CONTROL) {
4116 goto put_data_connection;
4117 }
4118 LTTNG_ASSERT(data_conn->type == RELAY_DATA);
4119
4120 if (revents & LPOLLIN) {
4121 enum relay_connection_status status;
4122
4123 status = relay_process_data(data_conn);
4124 /* Connection closed or error. */
4125 if (status != RELAY_CONNECTION_STATUS_OK) {
4126 /*
4127 * On socket error flag the session as aborted to force
4128 * the cleanup of its stream otherwise it can leak
4129 * during the lifetime of the relayd.
4130 *
4131 * This prevents situations in which streams can be
4132 * left opened because an index was received, the
4133 * control connection is closed, and the data
4134 * connection is closed (uncleanly) before the packet's
4135 * data provided.
4136 *
4137 * Since the data connection encountered an error,
4138 * it is okay to be conservative and close the
4139 * session right now as we can't rely on the protocol
4140 * being respected anymore.
4141 */
4142 if (status == RELAY_CONNECTION_STATUS_ERROR) {
4143 session_abort(data_conn->session);
4144 }
4145 relay_thread_close_connection(&events, pollfd, data_conn);
4146 /*
4147 * Every goto restart call sets the last seen fd where
4148 * here we don't really care since we gracefully
4149 * continue the loop after the connection is deleted.
4150 */
4151 } else {
4152 /* Keep last seen port. */
4153 last_seen_data_fd = pollfd;
4154 connection_put(data_conn);
4155 goto restart;
4156 }
4157 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
4158 relay_thread_close_connection(&events, pollfd, data_conn);
4159 } else {
4160 ERR("Unknown poll events %u for data sock %d", revents, pollfd);
4161 }
4162 put_data_connection:
4163 connection_put(data_conn);
4164 }
4165 last_seen_data_fd = -1;
4166 }
4167
4168 /* Normal exit, no error */
4169 ret = 0;
4170
4171 exit:
4172 error:
4173 /* Cleanup remaining connection object. */
4174 {
4175 lttng::urcu::read_lock_guard read_lock;
4176
4177 cds_lfht_for_each_entry (
4178 relay_connections_ht->ht, &iter.iter, destroy_conn, sock_n.node) {
4179 health_code_update();
4180
4181 session_abort(destroy_conn->session);
4182
4183 /*
4184 * No need to grab another ref, because we own
4185 * destroy_conn.
4186 */
4187 relay_thread_close_connection(
4188 &events, destroy_conn->sock->fd, destroy_conn);
4189 }
4190 }
4191
4192 (void) fd_tracker_util_poll_clean(the_fd_tracker, &events);
4193 error_poll_create:
4194 lttng_ht_destroy(relay_connections_ht);
4195 relay_connections_ht_error:
4196 /* Close relay conn pipes */
4197 (void) fd_tracker_util_pipe_close(the_fd_tracker, relay_conn_pipe);
4198 if (err) {
4199 DBG("Thread exited with error");
4200 }
4201 DBG("Worker thread cleanup complete");
4202 error_testpoint:
4203 if (err) {
4204 health_error();
4205 ERR("Health error occurred in %s", __func__);
4206 }
4207 health_unregister(health_relayd);
4208 rcu_unregister_thread();
4209 lttng_relay_stop_threads();
4210 return nullptr;
4211 }
4212
4213 /*
4214 * Create the relay command pipe to wake thread_manage_apps.
4215 * Closed in cleanup().
4216 */
4217 static int create_relay_conn_pipe()
4218 {
4219 return fd_tracker_util_pipe_open_cloexec(
4220 the_fd_tracker, "Relayd connection pipe", relay_conn_pipe);
4221 }
4222
4223 static int stdio_open(void *data __attribute__((unused)), int *fds)
4224 {
4225 fds[0] = fileno(stdout);
4226 fds[1] = fileno(stderr);
4227 return 0;
4228 }
4229
4230 static int track_stdio()
4231 {
4232 int fds[2];
4233 const char *names[] = { "stdout", "stderr" };
4234
4235 return fd_tracker_open_unsuspendable_fd(the_fd_tracker, fds, names, 2, stdio_open, nullptr);
4236 }
4237
4238 /*
4239 * main
4240 */
4241 int main(int argc, char **argv)
4242 {
4243 bool thread_is_rcu_registered = false;
4244 int ret = 0, retval = 0;
4245 void *status;
4246 char *unlinked_file_directory_path = nullptr, *output_path = nullptr;
4247
4248 /* Parse environment variables */
4249 ret = parse_env_options();
4250 if (ret) {
4251 retval = -1;
4252 goto exit_options;
4253 }
4254
4255 /*
4256 * Parse arguments.
4257 * Command line arguments overwrite environment.
4258 */
4259 progname = argv[0];
4260 if (set_options(argc, argv)) {
4261 retval = -1;
4262 goto exit_options;
4263 }
4264
4265 if (set_signal_handler()) {
4266 retval = -1;
4267 goto exit_options;
4268 }
4269
4270 relayd_config_log();
4271
4272 if (opt_print_version) {
4273 print_version();
4274 retval = 0;
4275 goto exit_options;
4276 }
4277
4278 ret = fclose(stdin);
4279 if (ret) {
4280 PERROR("Failed to close stdin");
4281 goto exit_options;
4282 }
4283
4284 DBG("Clear command %s", opt_allow_clear ? "allowed" : "disallowed");
4285
4286 /* Try to create directory if -o, --output is specified. */
4287 if (opt_output_path) {
4288 if (*opt_output_path != '/') {
4289 ERR("Please specify an absolute path for -o, --output PATH");
4290 retval = -1;
4291 goto exit_options;
4292 }
4293
4294 ret = utils_mkdir_recursive(opt_output_path, S_IRWXU | S_IRWXG, -1, -1);
4295 if (ret < 0) {
4296 ERR("Unable to create %s", opt_output_path);
4297 retval = -1;
4298 goto exit_options;
4299 }
4300 }
4301
4302 /* Daemonize */
4303 if (opt_daemon || opt_background) {
4304 ret = lttng_daemonize(&child_ppid, &recv_child_signal, !opt_background);
4305 if (ret < 0) {
4306 retval = -1;
4307 goto exit_options;
4308 }
4309 }
4310
4311 if (opt_working_directory) {
4312 ret = utils_change_working_directory(opt_working_directory);
4313 if (ret) {
4314 /* All errors are already logged. */
4315 goto exit_options;
4316 }
4317 }
4318
4319 sessiond_trace_chunk_registry = sessiond_trace_chunk_registry_create();
4320 if (!sessiond_trace_chunk_registry) {
4321 ERR("Failed to initialize session daemon trace chunk registry");
4322 retval = -1;
4323 goto exit_options;
4324 }
4325
4326 /*
4327 * The RCU thread registration (and use, through the fd-tracker's
4328 * creation) is done after the daemonization to allow us to not
4329 * deal with liburcu's fork() management as the call RCU needs to
4330 * be restored.
4331 */
4332 rcu_register_thread();
4333 thread_is_rcu_registered = true;
4334
4335 output_path = create_output_path("");
4336 if (!output_path) {
4337 ERR("Failed to get output path");
4338 retval = -1;
4339 goto exit_options;
4340 }
4341 ret = asprintf(&unlinked_file_directory_path,
4342 "%s/%s",
4343 output_path,
4344 DEFAULT_UNLINKED_FILES_DIRECTORY);
4345 free(output_path);
4346 if (ret < 0) {
4347 ERR("Failed to format unlinked file directory path");
4348 retval = -1;
4349 goto exit_options;
4350 }
4351 the_fd_tracker = fd_tracker_create(unlinked_file_directory_path, lttng_opt_fd_pool_size);
4352 free(unlinked_file_directory_path);
4353 if (!the_fd_tracker) {
4354 retval = -1;
4355 goto exit_options;
4356 }
4357
4358 ret = track_stdio();
4359 if (ret) {
4360 retval = -1;
4361 goto exit_options;
4362 }
4363
4364 /* Initialize thread health monitoring */
4365 health_relayd = health_app_create(NR_HEALTH_RELAYD_TYPES);
4366 if (!health_relayd) {
4367 PERROR("health_app_create error");
4368 retval = -1;
4369 goto exit_options;
4370 }
4371
4372 /* Create thread quit pipe */
4373 if (relayd_init_thread_quit_pipe()) {
4374 retval = -1;
4375 goto exit_options;
4376 }
4377
4378 /* Setup the thread apps communication pipe. */
4379 if (create_relay_conn_pipe()) {
4380 retval = -1;
4381 goto exit_options;
4382 }
4383
4384 /* Init relay command queue. */
4385 cds_wfcq_init(&relay_conn_queue.head, &relay_conn_queue.tail);
4386
4387 /* Initialize communication library */
4388 lttcomm_init();
4389 lttcomm_inet_init();
4390
4391 /* tables of sessions indexed by session ID */
4392 sessions_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
4393 if (!sessions_ht) {
4394 retval = -1;
4395 goto exit_options;
4396 }
4397
4398 /* tables of streams indexed by stream ID */
4399 relay_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
4400 if (!relay_streams_ht) {
4401 retval = -1;
4402 goto exit_options;
4403 }
4404
4405 /* tables of streams indexed by stream ID */
4406 viewer_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
4407 if (!viewer_streams_ht) {
4408 retval = -1;
4409 goto exit_options;
4410 }
4411
4412 ret = init_health_quit_pipe();
4413 if (ret) {
4414 retval = -1;
4415 goto exit_options;
4416 }
4417
4418 /* Create thread to manage the client socket */
4419 ret = pthread_create(&health_thread,
4420 default_pthread_attr(),
4421 thread_manage_health_relayd,
4422 (void *) nullptr);
4423 if (ret) {
4424 errno = ret;
4425 PERROR("pthread_create health");
4426 retval = -1;
4427 goto exit_options;
4428 }
4429
4430 /* Setup the dispatcher thread */
4431 ret = pthread_create(&dispatcher_thread,
4432 default_pthread_attr(),
4433 relay_thread_dispatcher,
4434 (void *) nullptr);
4435 if (ret) {
4436 errno = ret;
4437 PERROR("pthread_create dispatcher");
4438 retval = -1;
4439 goto exit_dispatcher_thread;
4440 }
4441
4442 /* Setup the worker thread */
4443 ret = pthread_create(&worker_thread, default_pthread_attr(), relay_thread_worker, nullptr);
4444 if (ret) {
4445 errno = ret;
4446 PERROR("pthread_create worker");
4447 retval = -1;
4448 goto exit_worker_thread;
4449 }
4450
4451 /* Setup the listener thread */
4452 ret = pthread_create(
4453 &listener_thread, default_pthread_attr(), relay_thread_listener, (void *) nullptr);
4454 if (ret) {
4455 errno = ret;
4456 PERROR("pthread_create listener");
4457 retval = -1;
4458 goto exit_listener_thread;
4459 }
4460
4461 ret = relayd_live_create(live_uri);
4462 if (ret) {
4463 ERR("Starting live viewer threads");
4464 retval = -1;
4465 goto exit_live;
4466 }
4467
4468 /*
4469 * This is where we start awaiting program completion (e.g. through
4470 * signal that asks threads to teardown).
4471 */
4472
4473 ret = relayd_live_join();
4474 if (ret) {
4475 retval = -1;
4476 }
4477 exit_live:
4478
4479 ret = pthread_join(listener_thread, &status);
4480 if (ret) {
4481 errno = ret;
4482 PERROR("pthread_join listener_thread");
4483 retval = -1;
4484 }
4485
4486 exit_listener_thread:
4487 ret = pthread_join(worker_thread, &status);
4488 if (ret) {
4489 errno = ret;
4490 PERROR("pthread_join worker_thread");
4491 retval = -1;
4492 }
4493
4494 exit_worker_thread:
4495 ret = pthread_join(dispatcher_thread, &status);
4496 if (ret) {
4497 errno = ret;
4498 PERROR("pthread_join dispatcher_thread");
4499 retval = -1;
4500 }
4501 exit_dispatcher_thread:
4502
4503 ret = pthread_join(health_thread, &status);
4504 if (ret) {
4505 errno = ret;
4506 PERROR("pthread_join health_thread");
4507 retval = -1;
4508 }
4509 exit_options:
4510 /*
4511 * Wait for all pending call_rcu work to complete before tearing
4512 * down data structures. call_rcu worker may be trying to
4513 * perform lookups in those structures.
4514 */
4515 rcu_barrier();
4516 relayd_cleanup();
4517
4518 /* Ensure all prior call_rcu are done. */
4519 rcu_barrier();
4520
4521 if (thread_is_rcu_registered) {
4522 rcu_unregister_thread();
4523 }
4524
4525 if (!retval) {
4526 exit(EXIT_SUCCESS);
4527 } else {
4528 exit(EXIT_FAILURE);
4529 }
4530 }
This page took 0.121557 seconds and 4 git commands to generate.