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