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