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