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