relayd: do not link lttng-relayd on liblttng-ctl
[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.h>
40 #include <common/compat/poll.h>
41 #include <common/compat/socket.h>
42 #include <common/compat/endian.h>
43 #include <common/compat/getenv.h>
44 #include <common/defaults.h>
45 #include <common/daemonize.h>
46 #include <common/futex.h>
47 #include <common/sessiond-comm/sessiond-comm.h>
48 #include <common/sessiond-comm/inet.h>
49 #include <common/sessiond-comm/relayd.h>
50 #include <common/uri.h>
51 #include <common/utils.h>
52 #include <common/align.h>
53 #include <common/ini-config/ini-config.h>
54 #include <common/dynamic-buffer.h>
55 #include <common/buffer-view.h>
56 #include <common/string-utils/format.h>
57 #include <common/fd-tracker/fd-tracker.h>
58 #include <common/fd-tracker/utils.h>
59
60 #include "backward-compatibility-group-by.h"
61 #include "cmd.h"
62 #include "connection.h"
63 #include "ctf-trace.h"
64 #include "health-relayd.h"
65 #include "index.h"
66 #include "live.h"
67 #include "lttng-relayd.h"
68 #include "session.h"
69 #include "sessiond-trace-chunks.h"
70 #include "stream.h"
71 #include "tcp_keep_alive.h"
72 #include "testpoint.h"
73 #include "tracefile-array.h"
74 #include "utils.h"
75 #include "version.h"
76 #include "viewer-stream.h"
77
78 static const char *help_msg =
79 #ifdef LTTNG_EMBED_HELP
80 #include <lttng-relayd.8.h>
81 #else
82 NULL
83 #endif
84 ;
85
86 enum relay_connection_status {
87 RELAY_CONNECTION_STATUS_OK,
88 /* An error occurred while processing an event on the connection. */
89 RELAY_CONNECTION_STATUS_ERROR,
90 /* Connection closed/shutdown cleanly. */
91 RELAY_CONNECTION_STATUS_CLOSED,
92 };
93
94 /* command line options */
95 char *opt_output_path, *opt_working_directory;
96 static int opt_daemon, opt_background, opt_print_version, opt_allow_clear = 1;
97 enum relay_group_output_by opt_group_output_by = RELAYD_GROUP_OUTPUT_BY_UNKNOWN;
98
99 /* Argument variables */
100 int lttng_opt_quiet; /* not static in error.h */
101 int lttng_opt_verbose; /* not static in error.h */
102 int lttng_opt_mi; /* not static in error.h */
103
104 /*
105 * We need to wait for listener and live listener threads, as well as
106 * health check thread, before being ready to signal readiness.
107 */
108 #define NR_LTTNG_RELAY_READY 3
109 static int lttng_relay_ready = NR_LTTNG_RELAY_READY;
110
111 /* Size of receive buffer. */
112 #define RECV_DATA_BUFFER_SIZE 65536
113
114 static int recv_child_signal; /* Set to 1 when a SIGUSR1 signal is received. */
115 static pid_t child_ppid; /* Internal parent PID use with daemonize. */
116
117 static struct lttng_uri *control_uri;
118 static struct lttng_uri *data_uri;
119 static struct lttng_uri *live_uri;
120
121 const char *progname;
122
123 const char *tracing_group_name = DEFAULT_TRACING_GROUP;
124 static int tracing_group_name_override;
125
126 const char * const config_section_name = "relayd";
127
128 /*
129 * Quit pipe for all threads. This permits a single cancellation point
130 * for all threads when receiving an event on the pipe.
131 */
132 int thread_quit_pipe[2] = { -1, -1 };
133
134 /*
135 * This pipe is used to inform the worker thread that a command is queued and
136 * ready to be processed.
137 */
138 static int relay_conn_pipe[2] = { -1, -1 };
139
140 /* Shared between threads */
141 static int dispatch_thread_exit;
142
143 static pthread_t listener_thread;
144 static pthread_t dispatcher_thread;
145 static pthread_t worker_thread;
146 static pthread_t health_thread;
147
148 /*
149 * last_relay_stream_id_lock protects last_relay_stream_id increment
150 * atomicity on 32-bit architectures.
151 */
152 static pthread_mutex_t last_relay_stream_id_lock = PTHREAD_MUTEX_INITIALIZER;
153 static uint64_t last_relay_stream_id;
154
155 /*
156 * Relay command queue.
157 *
158 * The relay_thread_listener and relay_thread_dispatcher communicate with this
159 * queue.
160 */
161 static struct relay_conn_queue relay_conn_queue;
162
163 /* Cap of file desriptors to be in simultaneous use by the relay daemon. */
164 static unsigned int lttng_opt_fd_pool_size = -1;
165
166 /* Global relay stream hash table. */
167 struct lttng_ht *relay_streams_ht;
168
169 /* Global relay viewer stream hash table. */
170 struct lttng_ht *viewer_streams_ht;
171
172 /* Global relay sessions hash table. */
173 struct lttng_ht *sessions_ht;
174
175 /* Relayd health monitoring */
176 struct health_app *health_relayd;
177
178 struct sessiond_trace_chunk_registry *sessiond_trace_chunk_registry;
179
180 /* Global fd tracker. */
181 struct fd_tracker *the_fd_tracker;
182
183 static struct option long_options[] = {
184 { "control-port", 1, 0, 'C', },
185 { "data-port", 1, 0, 'D', },
186 { "live-port", 1, 0, 'L', },
187 { "daemonize", 0, 0, 'd', },
188 { "background", 0, 0, 'b', },
189 { "group", 1, 0, 'g', },
190 { "fd-pool-size", 1, 0, '\0', },
191 { "help", 0, 0, 'h', },
192 { "output", 1, 0, 'o', },
193 { "verbose", 0, 0, 'v', },
194 { "config", 1, 0, 'f' },
195 { "version", 0, 0, 'V' },
196 { "working-directory", 1, 0, 'w', },
197 { "group-output-by-session", 0, 0, 's', },
198 { "group-output-by-host", 0, 0, 'p', },
199 { "disallow-clear", 0, 0, 'x' },
200 { NULL, 0, 0, 0, },
201 };
202
203 static const char *config_ignore_options[] = { "help", "config", "version" };
204
205 static void print_version(void) {
206 fprintf(stdout, "%s\n", VERSION);
207 }
208
209 static void relayd_config_log(void)
210 {
211 DBG("LTTng-relayd " VERSION " - " VERSION_NAME "%s%s",
212 GIT_VERSION[0] == '\0' ? "" : " - " GIT_VERSION,
213 EXTRA_VERSION_NAME[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME);
214 if (EXTRA_VERSION_DESCRIPTION[0] != '\0') {
215 DBG("LTTng-relayd extra version description:\n\t" EXTRA_VERSION_DESCRIPTION "\n");
216 }
217 if (EXTRA_VERSION_PATCHES[0] != '\0') {
218 DBG("LTTng-relayd extra patches:\n\t" EXTRA_VERSION_PATCHES "\n");
219 }
220 }
221
222 /*
223 * Take an option from the getopt output and set it in the right variable to be
224 * used later.
225 *
226 * Return 0 on success else a negative value.
227 */
228 static int set_option(int opt, const char *arg, const char *optname)
229 {
230 int ret;
231
232 switch (opt) {
233 case 0:
234 if (!strcmp(optname, "fd-pool-size")) {
235 unsigned long v;
236
237 errno = 0;
238 v = strtoul(arg, NULL, 0);
239 if (errno != 0 || !isdigit((unsigned char) arg[0])) {
240 ERR("Wrong value in --fd-pool-size parameter: %s", arg);
241 ret = -1;
242 goto end;
243 }
244 if (v >= UINT_MAX) {
245 ERR("File descriptor cap overflow in --fd-pool-size parameter: %s", arg);
246 ret = -1;
247 goto end;
248 }
249 lttng_opt_fd_pool_size = (unsigned int) v;
250 } else {
251 fprintf(stderr, "unknown option %s", optname);
252 if (arg) {
253 fprintf(stderr, " with arg %s\n", arg);
254 }
255 }
256 break;
257 case 'C':
258 if (lttng_is_setuid_setgid()) {
259 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
260 "-C, --control-port");
261 } else {
262 ret = uri_parse(arg, &control_uri);
263 if (ret < 0) {
264 ERR("Invalid control URI specified");
265 goto end;
266 }
267 if (control_uri->port == 0) {
268 control_uri->port = DEFAULT_NETWORK_CONTROL_PORT;
269 }
270 }
271 break;
272 case 'D':
273 if (lttng_is_setuid_setgid()) {
274 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
275 "-D, -data-port");
276 } else {
277 ret = uri_parse(arg, &data_uri);
278 if (ret < 0) {
279 ERR("Invalid data URI specified");
280 goto end;
281 }
282 if (data_uri->port == 0) {
283 data_uri->port = DEFAULT_NETWORK_DATA_PORT;
284 }
285 }
286 break;
287 case 'L':
288 if (lttng_is_setuid_setgid()) {
289 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
290 "-L, -live-port");
291 } else {
292 ret = uri_parse(arg, &live_uri);
293 if (ret < 0) {
294 ERR("Invalid live URI specified");
295 goto end;
296 }
297 if (live_uri->port == 0) {
298 live_uri->port = DEFAULT_NETWORK_VIEWER_PORT;
299 }
300 }
301 break;
302 case 'd':
303 opt_daemon = 1;
304 break;
305 case 'b':
306 opt_background = 1;
307 break;
308 case 'g':
309 if (lttng_is_setuid_setgid()) {
310 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
311 "-g, --group");
312 } else {
313 tracing_group_name = strdup(arg);
314 if (tracing_group_name == NULL) {
315 ret = -errno;
316 PERROR("strdup");
317 goto end;
318 }
319 tracing_group_name_override = 1;
320 }
321 break;
322 case 'h':
323 ret = utils_show_help(8, "lttng-relayd", help_msg);
324 if (ret) {
325 ERR("Cannot show --help for `lttng-relayd`");
326 perror("exec");
327 }
328 exit(EXIT_FAILURE);
329 case 'V':
330 opt_print_version = 1;
331 break;
332 case 'o':
333 if (lttng_is_setuid_setgid()) {
334 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
335 "-o, --output");
336 } else {
337 ret = asprintf(&opt_output_path, "%s", arg);
338 if (ret < 0) {
339 ret = -errno;
340 PERROR("asprintf opt_output_path");
341 goto end;
342 }
343 }
344 break;
345 case 'w':
346 if (lttng_is_setuid_setgid()) {
347 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
348 "-w, --working-directory");
349 } else {
350 ret = asprintf(&opt_working_directory, "%s", arg);
351 if (ret < 0) {
352 ret = -errno;
353 PERROR("asprintf opt_working_directory");
354 goto end;
355 }
356 }
357 break;
358
359 case 'v':
360 /* Verbose level can increase using multiple -v */
361 if (arg) {
362 lttng_opt_verbose = config_parse_value(arg);
363 } else {
364 /* Only 3 level of verbosity (-vvv). */
365 if (lttng_opt_verbose < 3) {
366 lttng_opt_verbose += 1;
367 }
368 }
369 break;
370 case 's':
371 if (opt_group_output_by != RELAYD_GROUP_OUTPUT_BY_UNKNOWN) {
372 ERR("Cannot set --group-output-by-session, another --group-output-by argument is present");
373 exit(EXIT_FAILURE);
374 }
375 opt_group_output_by = RELAYD_GROUP_OUTPUT_BY_SESSION;
376 break;
377 case 'p':
378 if (opt_group_output_by != RELAYD_GROUP_OUTPUT_BY_UNKNOWN) {
379 ERR("Cannot set --group-output-by-host, another --group-output-by argument is present");
380 exit(EXIT_FAILURE);
381 }
382 opt_group_output_by = RELAYD_GROUP_OUTPUT_BY_HOST;
383 break;
384 case 'x':
385 /* Disallow clear */
386 opt_allow_clear = 0;
387 break;
388 default:
389 /* Unknown option or other error.
390 * Error is printed by getopt, just return */
391 ret = -1;
392 goto end;
393 }
394
395 /* All good. */
396 ret = 0;
397
398 end:
399 return ret;
400 }
401
402 /*
403 * config_entry_handler_cb used to handle options read from a config file.
404 * See config_entry_handler_cb comment in common/config/session-config.h for the
405 * return value conventions.
406 */
407 static int config_entry_handler(const struct config_entry *entry, void *unused)
408 {
409 int ret = 0, i;
410
411 if (!entry || !entry->name || !entry->value) {
412 ret = -EINVAL;
413 goto end;
414 }
415
416 /* Check if the option is to be ignored */
417 for (i = 0; i < sizeof(config_ignore_options) / sizeof(char *); i++) {
418 if (!strcmp(entry->name, config_ignore_options[i])) {
419 goto end;
420 }
421 }
422
423 for (i = 0; i < (sizeof(long_options) / sizeof(struct option)) - 1; i++) {
424 /* Ignore if entry name is not fully matched. */
425 if (strcmp(entry->name, long_options[i].name)) {
426 continue;
427 }
428
429 /*
430 * If the option takes no argument on the command line,
431 * we have to check if the value is "true". We support
432 * non-zero numeric values, true, on and yes.
433 */
434 if (!long_options[i].has_arg) {
435 ret = config_parse_value(entry->value);
436 if (ret <= 0) {
437 if (ret) {
438 WARN("Invalid configuration value \"%s\" for option %s",
439 entry->value, entry->name);
440 }
441 /* False, skip boolean config option. */
442 goto end;
443 }
444 }
445
446 ret = set_option(long_options[i].val, entry->value, entry->name);
447 goto end;
448 }
449
450 WARN("Unrecognized option \"%s\" in daemon configuration file.",
451 entry->name);
452
453 end:
454 return ret;
455 }
456
457 static int parse_env_options(void)
458 {
459 int ret = 0;
460 char *value = NULL;
461
462 value = lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV);
463 if (value) {
464 opt_working_directory = strdup(value);
465 if (!opt_working_directory) {
466 ERR("Failed to allocate working directory string (\"%s\")",
467 value);
468 ret = -1;
469 }
470 }
471 return ret;
472 }
473
474 static int set_fd_pool_size(void)
475 {
476 int ret = 0;
477 struct rlimit rlimit;
478
479 ret = getrlimit(RLIMIT_NOFILE, &rlimit);
480 if (ret) {
481 PERROR("Failed to get file descriptor limit");
482 ret = -1;
483 goto end;
484 }
485
486 DBG("File descriptor count limits are %" PRIu64 " (soft) and %" PRIu64 " (hard)",
487 (uint64_t) rlimit.rlim_cur,
488 (uint64_t) rlimit.rlim_max);
489 if (lttng_opt_fd_pool_size == -1) {
490 /* Use default value (soft limit - reserve). */
491 if (rlimit.rlim_cur < DEFAULT_RELAYD_MIN_FD_POOL_SIZE) {
492 ERR("The process' file number limit is too low (%" PRIu64 "). The process' file number limit must be set to at least %i.",
493 (uint64_t) rlimit.rlim_cur, DEFAULT_RELAYD_MIN_FD_POOL_SIZE);
494 ret = -1;
495 goto end;
496 }
497 lttng_opt_fd_pool_size = rlimit.rlim_cur -
498 DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE;
499 goto end;
500 }
501
502 if (lttng_opt_fd_pool_size < DEFAULT_RELAYD_MIN_FD_POOL_SIZE) {
503 ERR("File descriptor pool size must be set to at least %d",
504 DEFAULT_RELAYD_MIN_FD_POOL_SIZE);
505 ret = -1;
506 goto end;
507 }
508
509 if (lttng_opt_fd_pool_size > rlimit.rlim_cur) {
510 ERR("File descriptor pool size argument (%u) exceeds the process' soft limit (%" PRIu64 ").",
511 lttng_opt_fd_pool_size, (uint64_t) rlimit.rlim_cur);
512 ret = -1;
513 goto end;
514 }
515
516 DBG("File descriptor pool size argument (%u) adjusted to %u to accommodates transient fd uses",
517 lttng_opt_fd_pool_size,
518 lttng_opt_fd_pool_size - DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE);
519 lttng_opt_fd_pool_size -= DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE;
520 end:
521 return ret;
522 }
523
524 static int set_options(int argc, char **argv)
525 {
526 int c, ret = 0, option_index = 0, retval = 0;
527 int orig_optopt = optopt, orig_optind = optind;
528 char *default_address, *optstring;
529 char *config_path = NULL;
530
531 optstring = utils_generate_optstring(long_options,
532 sizeof(long_options) / sizeof(struct option));
533 if (!optstring) {
534 retval = -ENOMEM;
535 goto exit;
536 }
537
538 /* Check for the --config option */
539
540 while ((c = getopt_long(argc, argv, optstring, long_options,
541 &option_index)) != -1) {
542 if (c == '?') {
543 retval = -EINVAL;
544 goto exit;
545 } else if (c != 'f') {
546 continue;
547 }
548
549 if (lttng_is_setuid_setgid()) {
550 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
551 "-f, --config");
552 } else {
553 free(config_path);
554 config_path = utils_expand_path(optarg);
555 if (!config_path) {
556 ERR("Failed to resolve path: %s", optarg);
557 }
558 }
559 }
560
561 ret = config_get_section_entries(config_path, config_section_name,
562 config_entry_handler, NULL);
563 if (ret) {
564 if (ret > 0) {
565 ERR("Invalid configuration option at line %i", ret);
566 }
567 retval = -1;
568 goto exit;
569 }
570
571 /* Reset getopt's global state */
572 optopt = orig_optopt;
573 optind = orig_optind;
574 while (1) {
575 c = getopt_long(argc, argv, optstring, long_options, &option_index);
576 if (c == -1) {
577 break;
578 }
579
580 ret = set_option(c, optarg, long_options[option_index].name);
581 if (ret < 0) {
582 retval = -1;
583 goto exit;
584 }
585 }
586
587 /* assign default values */
588 if (control_uri == NULL) {
589 ret = asprintf(&default_address,
590 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS ":%d",
591 DEFAULT_NETWORK_CONTROL_PORT);
592 if (ret < 0) {
593 PERROR("asprintf default data address");
594 retval = -1;
595 goto exit;
596 }
597
598 ret = uri_parse(default_address, &control_uri);
599 free(default_address);
600 if (ret < 0) {
601 ERR("Invalid control URI specified");
602 retval = -1;
603 goto exit;
604 }
605 }
606 if (data_uri == NULL) {
607 ret = asprintf(&default_address,
608 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS ":%d",
609 DEFAULT_NETWORK_DATA_PORT);
610 if (ret < 0) {
611 PERROR("asprintf default data address");
612 retval = -1;
613 goto exit;
614 }
615
616 ret = uri_parse(default_address, &data_uri);
617 free(default_address);
618 if (ret < 0) {
619 ERR("Invalid data URI specified");
620 retval = -1;
621 goto exit;
622 }
623 }
624 if (live_uri == NULL) {
625 ret = asprintf(&default_address,
626 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS ":%d",
627 DEFAULT_NETWORK_VIEWER_PORT);
628 if (ret < 0) {
629 PERROR("asprintf default viewer control address");
630 retval = -1;
631 goto exit;
632 }
633
634 ret = uri_parse(default_address, &live_uri);
635 free(default_address);
636 if (ret < 0) {
637 ERR("Invalid viewer control URI specified");
638 retval = -1;
639 goto exit;
640 }
641 }
642 ret = set_fd_pool_size();
643 if (ret) {
644 retval = -1;
645 goto exit;
646 }
647
648 if (opt_group_output_by == RELAYD_GROUP_OUTPUT_BY_UNKNOWN) {
649 opt_group_output_by = RELAYD_GROUP_OUTPUT_BY_HOST;
650 }
651 if (opt_allow_clear) {
652 /* Check if env variable exists. */
653 const char *value = lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV);
654 if (value) {
655 ret = config_parse_value(value);
656 if (ret < 0) {
657 ERR("Invalid value for %s specified", DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV);
658 retval = -1;
659 goto exit;
660 }
661 opt_allow_clear = !ret;
662 }
663 }
664
665 exit:
666 free(config_path);
667 free(optstring);
668 return retval;
669 }
670
671 static void print_global_objects(void)
672 {
673 print_viewer_streams();
674 print_relay_streams();
675 print_sessions();
676 }
677
678 static int noop_close(void *data, int *fds)
679 {
680 return 0;
681 }
682
683 static void untrack_stdio(void)
684 {
685 int fds[] = { fileno(stdout), fileno(stderr) };
686
687 /*
688 * noop_close is used since we don't really want to close
689 * the stdio output fds; we merely want to stop tracking them.
690 */
691 (void) fd_tracker_close_unsuspendable_fd(the_fd_tracker,
692 fds, 2, noop_close, NULL);
693 }
694
695 /*
696 * Cleanup the daemon
697 */
698 static void relayd_cleanup(void)
699 {
700 print_global_objects();
701
702 DBG("Cleaning up");
703
704 if (viewer_streams_ht)
705 lttng_ht_destroy(viewer_streams_ht);
706 if (relay_streams_ht)
707 lttng_ht_destroy(relay_streams_ht);
708 if (sessions_ht)
709 lttng_ht_destroy(sessions_ht);
710
711 free(opt_output_path);
712 free(opt_working_directory);
713
714 if (health_relayd) {
715 health_app_destroy(health_relayd);
716 }
717 /* Close thread quit pipes */
718 if (health_quit_pipe[0] != -1) {
719 (void) fd_tracker_util_pipe_close(
720 the_fd_tracker, health_quit_pipe);
721 }
722 if (thread_quit_pipe[0] != -1) {
723 (void) fd_tracker_util_pipe_close(
724 the_fd_tracker, thread_quit_pipe);
725 }
726 if (sessiond_trace_chunk_registry) {
727 sessiond_trace_chunk_registry_destroy(
728 sessiond_trace_chunk_registry);
729 }
730 if (the_fd_tracker) {
731 untrack_stdio();
732 /*
733 * fd_tracker_destroy() will log the contents of the fd-tracker
734 * if a leak is detected.
735 */
736 fd_tracker_destroy(the_fd_tracker);
737 }
738
739 uri_free(control_uri);
740 uri_free(data_uri);
741 /* Live URI is freed in the live thread. */
742
743 if (tracing_group_name_override) {
744 free((void *) tracing_group_name);
745 }
746 }
747
748 /*
749 * Write to writable pipe used to notify a thread.
750 */
751 static int notify_thread_pipe(int wpipe)
752 {
753 ssize_t ret;
754
755 ret = lttng_write(wpipe, "!", 1);
756 if (ret < 1) {
757 PERROR("write poll pipe");
758 goto end;
759 }
760 ret = 0;
761 end:
762 return ret;
763 }
764
765 static int notify_health_quit_pipe(int *pipe)
766 {
767 ssize_t ret;
768
769 ret = lttng_write(pipe[1], "4", 1);
770 if (ret < 1) {
771 PERROR("write relay health quit");
772 goto end;
773 }
774 ret = 0;
775 end:
776 return ret;
777 }
778
779 /*
780 * Stop all relayd and relayd-live threads.
781 */
782 int lttng_relay_stop_threads(void)
783 {
784 int retval = 0;
785
786 /* Stopping all threads */
787 DBG("Terminating all threads");
788 if (notify_thread_pipe(thread_quit_pipe[1])) {
789 ERR("write error on thread quit pipe");
790 retval = -1;
791 }
792
793 if (notify_health_quit_pipe(health_quit_pipe)) {
794 ERR("write error on health quit pipe");
795 }
796
797 /* Dispatch thread */
798 CMM_STORE_SHARED(dispatch_thread_exit, 1);
799 futex_nto1_wake(&relay_conn_queue.futex);
800
801 if (relayd_live_stop()) {
802 ERR("Error stopping live threads");
803 retval = -1;
804 }
805 return retval;
806 }
807
808 /*
809 * Signal handler for the daemon
810 *
811 * Simply stop all worker threads, leaving main() return gracefully after
812 * joining all threads and calling cleanup().
813 */
814 static void sighandler(int sig)
815 {
816 switch (sig) {
817 case SIGINT:
818 DBG("SIGINT caught");
819 if (lttng_relay_stop_threads()) {
820 ERR("Error stopping threads");
821 }
822 break;
823 case SIGTERM:
824 DBG("SIGTERM caught");
825 if (lttng_relay_stop_threads()) {
826 ERR("Error stopping threads");
827 }
828 break;
829 case SIGUSR1:
830 CMM_STORE_SHARED(recv_child_signal, 1);
831 break;
832 default:
833 break;
834 }
835 }
836
837 /*
838 * Setup signal handler for :
839 * SIGINT, SIGTERM, SIGPIPE
840 */
841 static int set_signal_handler(void)
842 {
843 int ret = 0;
844 struct sigaction sa;
845 sigset_t sigset;
846
847 if ((ret = sigemptyset(&sigset)) < 0) {
848 PERROR("sigemptyset");
849 return ret;
850 }
851
852 sa.sa_mask = sigset;
853 sa.sa_flags = 0;
854
855 sa.sa_handler = sighandler;
856 if ((ret = sigaction(SIGTERM, &sa, NULL)) < 0) {
857 PERROR("sigaction");
858 return ret;
859 }
860
861 if ((ret = sigaction(SIGINT, &sa, NULL)) < 0) {
862 PERROR("sigaction");
863 return ret;
864 }
865
866 if ((ret = sigaction(SIGUSR1, &sa, NULL)) < 0) {
867 PERROR("sigaction");
868 return ret;
869 }
870
871 sa.sa_handler = SIG_IGN;
872 if ((ret = sigaction(SIGPIPE, &sa, NULL)) < 0) {
873 PERROR("sigaction");
874 return ret;
875 }
876
877 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
878
879 return ret;
880 }
881
882 void lttng_relay_notify_ready(void)
883 {
884 /* Notify the parent of the fork() process that we are ready. */
885 if (opt_daemon || opt_background) {
886 if (uatomic_sub_return(&lttng_relay_ready, 1) == 0) {
887 kill(child_ppid, SIGUSR1);
888 }
889 }
890 }
891
892 /*
893 * Init thread quit pipe.
894 *
895 * Return -1 on error or 0 if all pipes are created.
896 */
897 static int init_thread_quit_pipe(void)
898 {
899 return fd_tracker_util_pipe_open_cloexec(
900 the_fd_tracker, "Quit pipe", thread_quit_pipe);
901 }
902
903 /*
904 * Init health quit pipe.
905 *
906 * Return -1 on error or 0 if all pipes are created.
907 */
908 static int init_health_quit_pipe(void)
909 {
910 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker,
911 "Health quit pipe", health_quit_pipe);
912 }
913
914 /*
915 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
916 */
917 static int create_named_thread_poll_set(struct lttng_poll_event *events,
918 int size, const char *name)
919 {
920 int ret;
921
922 if (events == NULL || size == 0) {
923 ret = -1;
924 goto error;
925 }
926
927 ret = fd_tracker_util_poll_create(the_fd_tracker,
928 name, events, 1, LTTNG_CLOEXEC);
929 if (ret) {
930 PERROR("Failed to create \"%s\" poll file descriptor", name);
931 goto error;
932 }
933
934 /* Add quit pipe */
935 ret = lttng_poll_add(events, thread_quit_pipe[0], LPOLLIN | LPOLLERR);
936 if (ret < 0) {
937 goto error;
938 }
939
940 return 0;
941
942 error:
943 return ret;
944 }
945
946 /*
947 * Check if the thread quit pipe was triggered.
948 *
949 * Return 1 if it was triggered else 0;
950 */
951 static int check_thread_quit_pipe(int fd, uint32_t events)
952 {
953 if (fd == thread_quit_pipe[0] && (events & LPOLLIN)) {
954 return 1;
955 }
956
957 return 0;
958 }
959
960 static int create_sock(void *data, int *out_fd)
961 {
962 int ret;
963 struct lttcomm_sock *sock = (lttcomm_sock *) data;
964
965 ret = lttcomm_create_sock(sock);
966 if (ret < 0) {
967 goto end;
968 }
969
970 *out_fd = sock->fd;
971 end:
972 return ret;
973 }
974
975 static int close_sock(void *data, int *in_fd)
976 {
977 struct lttcomm_sock *sock = (lttcomm_sock *) data;
978
979 return sock->ops->close(sock);
980 }
981
982 static int accept_sock(void *data, int *out_fd)
983 {
984 int ret = 0;
985 /* Socks is an array of in_sock, out_sock. */
986 struct lttcomm_sock **socks = (lttcomm_sock **) data;
987 struct lttcomm_sock *in_sock = socks[0];
988
989 socks[1] = in_sock->ops->accept(in_sock);
990 if (!socks[1]) {
991 ret = -1;
992 goto end;
993 }
994 *out_fd = socks[1]->fd;
995 end:
996 return ret;
997 }
998
999 /*
1000 * Create and init socket from uri.
1001 */
1002 static struct lttcomm_sock *relay_socket_create(struct lttng_uri *uri,
1003 const char *name)
1004 {
1005 int ret, sock_fd;
1006 struct lttcomm_sock *sock = NULL;
1007 char uri_str[PATH_MAX];
1008 char *formated_name = NULL;
1009
1010 sock = lttcomm_alloc_sock_from_uri(uri);
1011 if (sock == NULL) {
1012 ERR("Allocating socket");
1013 goto error;
1014 }
1015
1016 /*
1017 * Don't fail to create the socket if the name can't be built as it is
1018 * only used for debugging purposes.
1019 */
1020 ret = uri_to_str_url(uri, uri_str, sizeof(uri_str));
1021 uri_str[sizeof(uri_str) - 1] = '\0';
1022 if (ret >= 0) {
1023 ret = asprintf(&formated_name, "%s socket @ %s", name,
1024 uri_str);
1025 if (ret < 0) {
1026 formated_name = NULL;
1027 }
1028 }
1029
1030 ret = fd_tracker_open_unsuspendable_fd(the_fd_tracker, &sock_fd,
1031 (const char **) (formated_name ? &formated_name : NULL),
1032 1, create_sock, sock);
1033 if (ret) {
1034 PERROR("Failed to open \"%s\" relay socket",
1035 formated_name ?: "Unknown");
1036 goto error;
1037 }
1038 DBG("Listening on %s socket %d", name, sock->fd);
1039
1040 ret = sock->ops->bind(sock);
1041 if (ret < 0) {
1042 PERROR("Failed to bind socket");
1043 goto error;
1044 }
1045
1046 ret = sock->ops->listen(sock, -1);
1047 if (ret < 0) {
1048 goto error;
1049
1050 }
1051
1052 free(formated_name);
1053 return sock;
1054
1055 error:
1056 if (sock) {
1057 lttcomm_destroy_sock(sock);
1058 }
1059 free(formated_name);
1060 return NULL;
1061 }
1062
1063 static
1064 struct lttcomm_sock *accept_relayd_sock(struct lttcomm_sock *listening_sock,
1065 const char *name)
1066 {
1067 int out_fd, ret;
1068 struct lttcomm_sock *socks[2] = { listening_sock, NULL };
1069 struct lttcomm_sock *new_sock = NULL;
1070
1071 ret = fd_tracker_open_unsuspendable_fd(
1072 the_fd_tracker, &out_fd,
1073 (const char **) &name,
1074 1, accept_sock, &socks);
1075 if (ret) {
1076 goto end;
1077 }
1078 new_sock = socks[1];
1079 DBG("%s accepted, socket %d", name, new_sock->fd);
1080 end:
1081 return new_sock;
1082 }
1083
1084 /*
1085 * This thread manages the listening for new connections on the network
1086 */
1087 static void *relay_thread_listener(void *data)
1088 {
1089 int i, ret, pollfd, err = -1;
1090 uint32_t revents, nb_fd;
1091 struct lttng_poll_event events;
1092 struct lttcomm_sock *control_sock, *data_sock;
1093
1094 DBG("[thread] Relay listener started");
1095
1096 rcu_register_thread();
1097 health_register(health_relayd, HEALTH_RELAYD_TYPE_LISTENER);
1098
1099 health_code_update();
1100
1101 control_sock = relay_socket_create(control_uri, "Control listener");
1102 if (!control_sock) {
1103 goto error_sock_control;
1104 }
1105
1106 data_sock = relay_socket_create(data_uri, "Data listener");
1107 if (!data_sock) {
1108 goto error_sock_relay;
1109 }
1110
1111 /*
1112 * Pass 3 as size here for the thread quit pipe, control and
1113 * data socket.
1114 */
1115 ret = create_named_thread_poll_set(&events, 3, "Listener thread epoll");
1116 if (ret < 0) {
1117 goto error_create_poll;
1118 }
1119
1120 /* Add the control socket */
1121 ret = lttng_poll_add(&events, control_sock->fd, LPOLLIN | LPOLLRDHUP);
1122 if (ret < 0) {
1123 goto error_poll_add;
1124 }
1125
1126 /* Add the data socket */
1127 ret = lttng_poll_add(&events, data_sock->fd, LPOLLIN | LPOLLRDHUP);
1128 if (ret < 0) {
1129 goto error_poll_add;
1130 }
1131
1132 lttng_relay_notify_ready();
1133
1134 if (testpoint(relayd_thread_listener)) {
1135 goto error_testpoint;
1136 }
1137
1138 while (1) {
1139 health_code_update();
1140
1141 DBG("Listener accepting connections");
1142
1143 restart:
1144 health_poll_entry();
1145 ret = lttng_poll_wait(&events, -1);
1146 health_poll_exit();
1147 if (ret < 0) {
1148 /*
1149 * Restart interrupted system call.
1150 */
1151 if (errno == EINTR) {
1152 goto restart;
1153 }
1154 goto error;
1155 }
1156
1157 nb_fd = ret;
1158
1159 DBG("Relay new connection received");
1160 for (i = 0; i < nb_fd; i++) {
1161 health_code_update();
1162
1163 /* Fetch once the poll data */
1164 revents = LTTNG_POLL_GETEV(&events, i);
1165 pollfd = LTTNG_POLL_GETFD(&events, i);
1166
1167 /* Thread quit pipe has been closed. Killing thread. */
1168 ret = check_thread_quit_pipe(pollfd, revents);
1169 if (ret) {
1170 err = 0;
1171 goto exit;
1172 }
1173
1174 if (revents & LPOLLIN) {
1175 /*
1176 * A new connection is requested, therefore a
1177 * sessiond/consumerd connection is allocated in
1178 * this thread, enqueued to a global queue and
1179 * dequeued (and freed) in the worker thread.
1180 */
1181 int val = 1;
1182 struct relay_connection *new_conn;
1183 struct lttcomm_sock *newsock = NULL;
1184 enum connection_type type;
1185
1186 if (pollfd == data_sock->fd) {
1187 type = RELAY_DATA;
1188 newsock = accept_relayd_sock(data_sock,
1189 "Data socket to relayd");
1190 } else {
1191 LTTNG_ASSERT(pollfd == control_sock->fd);
1192 type = RELAY_CONTROL;
1193 newsock = accept_relayd_sock(control_sock,
1194 "Control socket to relayd");
1195 }
1196 if (!newsock) {
1197 PERROR("accepting sock");
1198 goto error;
1199 }
1200
1201 ret = setsockopt(newsock->fd, SOL_SOCKET, SO_REUSEADDR, &val,
1202 sizeof(val));
1203 if (ret < 0) {
1204 PERROR("setsockopt inet");
1205 lttcomm_destroy_sock(newsock);
1206 goto error;
1207 }
1208
1209 ret = socket_apply_keep_alive_config(newsock->fd);
1210 if (ret < 0) {
1211 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
1212 newsock->fd);
1213 lttcomm_destroy_sock(newsock);
1214 goto error;
1215 }
1216
1217 new_conn = connection_create(newsock, type);
1218 if (!new_conn) {
1219 lttcomm_destroy_sock(newsock);
1220 goto error;
1221 }
1222
1223 /* Enqueue request for the dispatcher thread. */
1224 cds_wfcq_head_ptr_t head;
1225 head.h = &relay_conn_queue.head;
1226 cds_wfcq_enqueue(head, &relay_conn_queue.tail,
1227 &new_conn->qnode);
1228
1229 /*
1230 * Wake the dispatch queue futex.
1231 * Implicit memory barrier with the
1232 * exchange in cds_wfcq_enqueue.
1233 */
1234 futex_nto1_wake(&relay_conn_queue.futex);
1235 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
1236 ERR("socket poll error");
1237 goto error;
1238 } else {
1239 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
1240 goto error;
1241 }
1242 }
1243 }
1244
1245 exit:
1246 error:
1247 error_poll_add:
1248 error_testpoint:
1249 (void) fd_tracker_util_poll_clean(the_fd_tracker, &events);
1250 error_create_poll:
1251 if (data_sock->fd >= 0) {
1252 int data_sock_fd = data_sock->fd;
1253
1254 ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker,
1255 &data_sock_fd, 1, close_sock,
1256 data_sock);
1257 if (ret) {
1258 PERROR("Failed to close the data listener socket file descriptor");
1259 }
1260 data_sock->fd = -1;
1261 }
1262 lttcomm_destroy_sock(data_sock);
1263 error_sock_relay:
1264 if (control_sock->fd >= 0) {
1265 int control_sock_fd = control_sock->fd;
1266
1267 ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker,
1268 &control_sock_fd, 1, close_sock,
1269 control_sock);
1270 if (ret) {
1271 PERROR("Failed to close the control listener socket file descriptor");
1272 }
1273 control_sock->fd = -1;
1274 }
1275 lttcomm_destroy_sock(control_sock);
1276 error_sock_control:
1277 if (err) {
1278 health_error();
1279 ERR("Health error occurred in %s", __func__);
1280 }
1281 health_unregister(health_relayd);
1282 rcu_unregister_thread();
1283 DBG("Relay listener thread cleanup complete");
1284 lttng_relay_stop_threads();
1285 return NULL;
1286 }
1287
1288 /*
1289 * This thread manages the dispatching of the requests to worker threads
1290 */
1291 static void *relay_thread_dispatcher(void *data)
1292 {
1293 int err = -1;
1294 ssize_t ret;
1295 struct cds_wfcq_node *node;
1296 struct relay_connection *new_conn = NULL;
1297
1298 DBG("[thread] Relay dispatcher started");
1299
1300 health_register(health_relayd, HEALTH_RELAYD_TYPE_DISPATCHER);
1301
1302 if (testpoint(relayd_thread_dispatcher)) {
1303 goto error_testpoint;
1304 }
1305
1306 health_code_update();
1307
1308 for (;;) {
1309 health_code_update();
1310
1311 /* Atomically prepare the queue futex */
1312 futex_nto1_prepare(&relay_conn_queue.futex);
1313
1314 if (CMM_LOAD_SHARED(dispatch_thread_exit)) {
1315 break;
1316 }
1317
1318 do {
1319 health_code_update();
1320
1321 /* Dequeue commands */
1322 node = cds_wfcq_dequeue_blocking(&relay_conn_queue.head,
1323 &relay_conn_queue.tail);
1324 if (node == NULL) {
1325 DBG("Woken up but nothing in the relay command queue");
1326 /* Continue thread execution */
1327 break;
1328 }
1329 new_conn = caa_container_of(node, struct relay_connection, qnode);
1330
1331 DBG("Dispatching request waiting on sock %d", new_conn->sock->fd);
1332
1333 /*
1334 * Inform worker thread of the new request. This
1335 * call is blocking so we can be assured that
1336 * the data will be read at some point in time
1337 * or wait to the end of the world :)
1338 */
1339 ret = lttng_write(relay_conn_pipe[1], &new_conn, sizeof(new_conn));
1340 if (ret < 0) {
1341 PERROR("write connection pipe");
1342 connection_put(new_conn);
1343 goto error;
1344 }
1345 } while (node != NULL);
1346
1347 /* Futex wait on queue. Blocking call on futex() */
1348 health_poll_entry();
1349 futex_nto1_wait(&relay_conn_queue.futex);
1350 health_poll_exit();
1351 }
1352
1353 /* Normal exit, no error */
1354 err = 0;
1355
1356 error:
1357 error_testpoint:
1358 if (err) {
1359 health_error();
1360 ERR("Health error occurred in %s", __func__);
1361 }
1362 health_unregister(health_relayd);
1363 DBG("Dispatch thread dying");
1364 lttng_relay_stop_threads();
1365 return NULL;
1366 }
1367
1368 static bool session_streams_have_index(const struct relay_session *session)
1369 {
1370 return session->minor >= 4 && !session->snapshot;
1371 }
1372
1373 /*
1374 * Handle the RELAYD_CREATE_SESSION command.
1375 *
1376 * On success, send back the session id or else return a negative value.
1377 */
1378 static int relay_create_session(const struct lttcomm_relayd_hdr *recv_hdr,
1379 struct relay_connection *conn,
1380 const struct lttng_buffer_view *payload)
1381 {
1382 int ret = 0;
1383 ssize_t send_ret;
1384 struct relay_session *session = NULL;
1385 struct lttcomm_relayd_create_session_reply_2_11 reply = {};
1386 char session_name[LTTNG_NAME_MAX] = {};
1387 char hostname[LTTNG_HOST_NAME_MAX] = {};
1388 uint32_t live_timer = 0;
1389 bool snapshot = false;
1390 bool session_name_contains_creation_timestamp = false;
1391 /* Left nil for peers < 2.11. */
1392 char base_path[LTTNG_PATH_MAX] = {};
1393 lttng_uuid sessiond_uuid = {};
1394 LTTNG_OPTIONAL(uint64_t) id_sessiond = {};
1395 LTTNG_OPTIONAL(uint64_t) current_chunk_id = {};
1396 LTTNG_OPTIONAL(time_t) creation_time = {};
1397 struct lttng_dynamic_buffer reply_payload;
1398
1399 lttng_dynamic_buffer_init(&reply_payload);
1400
1401 if (conn->minor < 4) {
1402 /* From 2.1 to 2.3 */
1403 ret = 0;
1404 } else if (conn->minor >= 4 && conn->minor < 11) {
1405 /* From 2.4 to 2.10 */
1406 ret = cmd_create_session_2_4(payload, session_name,
1407 hostname, &live_timer, &snapshot);
1408 } else {
1409 bool has_current_chunk;
1410 uint64_t current_chunk_id_value;
1411 time_t creation_time_value;
1412 uint64_t id_sessiond_value;
1413
1414 /* From 2.11 to ... */
1415 ret = cmd_create_session_2_11(payload, session_name, hostname,
1416 base_path, &live_timer, &snapshot, &id_sessiond_value,
1417 sessiond_uuid, &has_current_chunk,
1418 &current_chunk_id_value, &creation_time_value,
1419 &session_name_contains_creation_timestamp);
1420 if (lttng_uuid_is_nil(sessiond_uuid)) {
1421 /* The nil UUID is reserved for pre-2.11 clients. */
1422 ERR("Illegal nil UUID announced by peer in create session command");
1423 ret = -1;
1424 goto send_reply;
1425 }
1426 LTTNG_OPTIONAL_SET(&id_sessiond, id_sessiond_value);
1427 LTTNG_OPTIONAL_SET(&creation_time, creation_time_value);
1428 if (has_current_chunk) {
1429 LTTNG_OPTIONAL_SET(&current_chunk_id,
1430 current_chunk_id_value);
1431 }
1432 }
1433
1434 if (ret < 0) {
1435 goto send_reply;
1436 }
1437
1438 session = session_create(session_name, hostname, base_path, live_timer,
1439 snapshot, sessiond_uuid,
1440 id_sessiond.is_set ? &id_sessiond.value : NULL,
1441 current_chunk_id.is_set ? &current_chunk_id.value : NULL,
1442 creation_time.is_set ? &creation_time.value : NULL,
1443 conn->major, conn->minor,
1444 session_name_contains_creation_timestamp);
1445 if (!session) {
1446 ret = -1;
1447 goto send_reply;
1448 }
1449 LTTNG_ASSERT(!conn->session);
1450 conn->session = session;
1451 DBG("Created session %" PRIu64, session->id);
1452
1453 reply.generic.session_id = htobe64(session->id);
1454
1455 send_reply:
1456 if (ret < 0) {
1457 reply.generic.ret_code = htobe32(LTTNG_ERR_FATAL);
1458 } else {
1459 reply.generic.ret_code = htobe32(LTTNG_OK);
1460 }
1461
1462 if (conn->minor < 11) {
1463 /* From 2.1 to 2.10 */
1464 ret = lttng_dynamic_buffer_append(&reply_payload,
1465 &reply.generic, sizeof(reply.generic));
1466 if (ret) {
1467 ERR("Failed to append \"create session\" command reply header to payload buffer");
1468 ret = -1;
1469 goto end;
1470 }
1471 } else {
1472 const uint32_t output_path_length =
1473 session ? strlen(session->output_path) + 1 : 0;
1474
1475 reply.output_path_length = htobe32(output_path_length);
1476 ret = lttng_dynamic_buffer_append(
1477 &reply_payload, &reply, sizeof(reply));
1478 if (ret) {
1479 ERR("Failed to append \"create session\" command reply header to payload buffer");
1480 goto end;
1481 }
1482
1483 if (output_path_length) {
1484 ret = lttng_dynamic_buffer_append(&reply_payload,
1485 session->output_path,
1486 output_path_length);
1487 if (ret) {
1488 ERR("Failed to append \"create session\" command reply path to payload buffer");
1489 goto end;
1490 }
1491 }
1492 }
1493
1494 send_ret = conn->sock->ops->sendmsg(conn->sock, reply_payload.data,
1495 reply_payload.size, 0);
1496 if (send_ret < (ssize_t) reply_payload.size) {
1497 ERR("Failed to send \"create session\" command reply of %zu bytes (ret = %zd)",
1498 reply_payload.size, send_ret);
1499 ret = -1;
1500 }
1501 end:
1502 if (ret < 0 && session) {
1503 session_put(session);
1504 }
1505 lttng_dynamic_buffer_reset(&reply_payload);
1506 return ret;
1507 }
1508
1509 /*
1510 * When we have received all the streams and the metadata for a channel,
1511 * we make them visible to the viewer threads.
1512 */
1513 static void publish_connection_local_streams(struct relay_connection *conn)
1514 {
1515 struct relay_stream *stream;
1516 struct relay_session *session = conn->session;
1517
1518 /*
1519 * We publish all streams belonging to a session atomically wrt
1520 * session lock.
1521 */
1522 pthread_mutex_lock(&session->lock);
1523 rcu_read_lock();
1524 cds_list_for_each_entry_rcu(stream, &session->recv_list,
1525 recv_node) {
1526 stream_publish(stream);
1527 }
1528 rcu_read_unlock();
1529
1530 /*
1531 * Inform the viewer that there are new streams in the session.
1532 */
1533 if (session->viewer_attached) {
1534 uatomic_set(&session->new_streams, 1);
1535 }
1536 pthread_mutex_unlock(&session->lock);
1537 }
1538
1539 static int conform_channel_path(char *channel_path)
1540 {
1541 int ret = 0;
1542
1543 if (strstr("../", channel_path)) {
1544 ERR("Refusing channel path as it walks up the path hierarchy: \"%s\"",
1545 channel_path);
1546 ret = -1;
1547 goto end;
1548 }
1549
1550 if (*channel_path == '/') {
1551 const size_t len = strlen(channel_path);
1552
1553 /*
1554 * Channel paths from peers prior to 2.11 are expressed as an
1555 * absolute path that is, in reality, relative to the relay
1556 * daemon's output directory. Remove the leading slash so it
1557 * is correctly interpreted as a relative path later on.
1558 *
1559 * len (and not len - 1) is used to copy the trailing NULL.
1560 */
1561 bcopy(channel_path + 1, channel_path, len);
1562 }
1563 end:
1564 return ret;
1565 }
1566
1567 /*
1568 * relay_add_stream: allocate a new stream for a session
1569 */
1570 static int relay_add_stream(const struct lttcomm_relayd_hdr *recv_hdr,
1571 struct relay_connection *conn,
1572 const struct lttng_buffer_view *payload)
1573 {
1574 int ret;
1575 ssize_t send_ret;
1576 struct relay_session *session = conn->session;
1577 struct relay_stream *stream = NULL;
1578 struct lttcomm_relayd_status_stream reply;
1579 struct ctf_trace *trace = NULL;
1580 uint64_t stream_handle = -1ULL;
1581 char *path_name = NULL, *channel_name = NULL;
1582 uint64_t tracefile_size = 0, tracefile_count = 0;
1583 LTTNG_OPTIONAL(uint64_t) stream_chunk_id = {};
1584
1585 if (!session || !conn->version_check_done) {
1586 ERR("Trying to add a stream before version check");
1587 ret = -1;
1588 goto end_no_session;
1589 }
1590
1591 if (session->minor == 1) {
1592 /* For 2.1 */
1593 ret = cmd_recv_stream_2_1(payload, &path_name,
1594 &channel_name);
1595 } else if (session->minor > 1 && session->minor < 11) {
1596 /* From 2.2 to 2.10 */
1597 ret = cmd_recv_stream_2_2(payload, &path_name,
1598 &channel_name, &tracefile_size, &tracefile_count);
1599 } else {
1600 /* From 2.11 to ... */
1601 ret = cmd_recv_stream_2_11(payload, &path_name,
1602 &channel_name, &tracefile_size, &tracefile_count,
1603 &stream_chunk_id.value);
1604 stream_chunk_id.is_set = true;
1605 }
1606
1607 if (ret < 0) {
1608 goto send_reply;
1609 }
1610
1611 if (conform_channel_path(path_name)) {
1612 goto send_reply;
1613 }
1614
1615 /*
1616 * Backward compatibility for --group-output-by-session.
1617 * Prior to lttng 2.11, the complete path is passed by the stream.
1618 * Starting at 2.11, lttng-relayd uses chunk. When dealing with producer
1619 * >=2.11 the chunk is responsible for the output path. When dealing
1620 * with producer < 2.11 the chunk output_path is the root output path
1621 * and the stream carries the complete path (path_name).
1622 * To support --group-output-by-session with older producer (<2.11), we
1623 * need to craft the path based on the stream path.
1624 */
1625 if (opt_group_output_by == RELAYD_GROUP_OUTPUT_BY_SESSION) {
1626 if (conn->minor < 4) {
1627 /*
1628 * From 2.1 to 2.3, the session_name is not passed on
1629 * the RELAYD_CREATE_SESSION command. The session name
1630 * is necessary to detect the presence of a base_path
1631 * inside the stream path. Without it we cannot perform
1632 * a valid group-output-by-session transformation.
1633 */
1634 WARN("Unable to perform a --group-by-session transformation for session %" PRIu64
1635 " for stream with path \"%s\" as it is produced by a peer using a protocol older than v2.4",
1636 session->id, path_name);
1637 } else if (conn->minor >= 4 && conn->minor < 11) {
1638 char *group_by_session_path_name;
1639
1640 LTTNG_ASSERT(session->session_name[0] != '\0');
1641
1642 group_by_session_path_name =
1643 backward_compat_group_by_session(
1644 path_name,
1645 session->session_name,
1646 session->creation_time.value);
1647 if (!group_by_session_path_name) {
1648 ERR("Failed to apply group by session to stream of session %" PRIu64,
1649 session->id);
1650 goto send_reply;
1651 }
1652
1653 DBG("Transformed session path from \"%s\" to \"%s\" to honor per-session name grouping",
1654 path_name, group_by_session_path_name);
1655
1656 free(path_name);
1657 path_name = group_by_session_path_name;
1658 }
1659 }
1660
1661 trace = ctf_trace_get_by_path_or_create(session, path_name);
1662 if (!trace) {
1663 goto send_reply;
1664 }
1665
1666 /* This stream here has one reference on the trace. */
1667 pthread_mutex_lock(&last_relay_stream_id_lock);
1668 stream_handle = ++last_relay_stream_id;
1669 pthread_mutex_unlock(&last_relay_stream_id_lock);
1670
1671 /* We pass ownership of path_name and channel_name. */
1672 stream = stream_create(trace, stream_handle, path_name,
1673 channel_name, tracefile_size, tracefile_count);
1674 path_name = NULL;
1675 channel_name = NULL;
1676
1677 /*
1678 * Streams are the owners of their trace. Reference to trace is
1679 * kept within stream_create().
1680 */
1681 ctf_trace_put(trace);
1682
1683 send_reply:
1684 memset(&reply, 0, sizeof(reply));
1685 reply.handle = htobe64(stream_handle);
1686 if (!stream) {
1687 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1688 } else {
1689 reply.ret_code = htobe32(LTTNG_OK);
1690 }
1691
1692 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1693 sizeof(struct lttcomm_relayd_status_stream), 0);
1694 if (send_ret < (ssize_t) sizeof(reply)) {
1695 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1696 send_ret);
1697 ret = -1;
1698 }
1699
1700 end_no_session:
1701 free(path_name);
1702 free(channel_name);
1703 return ret;
1704 }
1705
1706 /*
1707 * relay_close_stream: close a specific stream
1708 */
1709 static int relay_close_stream(const struct lttcomm_relayd_hdr *recv_hdr,
1710 struct relay_connection *conn,
1711 const struct lttng_buffer_view *payload)
1712 {
1713 int ret;
1714 ssize_t send_ret;
1715 struct relay_session *session = conn->session;
1716 struct lttcomm_relayd_close_stream stream_info;
1717 struct lttcomm_relayd_generic_reply reply;
1718 struct relay_stream *stream;
1719
1720 DBG("Close stream received");
1721
1722 if (!session || !conn->version_check_done) {
1723 ERR("Trying to close a stream before version check");
1724 ret = -1;
1725 goto end_no_session;
1726 }
1727
1728 if (payload->size < sizeof(stream_info)) {
1729 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1730 sizeof(stream_info), payload->size);
1731 ret = -1;
1732 goto end_no_session;
1733 }
1734 memcpy(&stream_info, payload->data, sizeof(stream_info));
1735 stream_info.stream_id = be64toh(stream_info.stream_id);
1736 stream_info.last_net_seq_num = be64toh(stream_info.last_net_seq_num);
1737
1738 stream = stream_get_by_id(stream_info.stream_id);
1739 if (!stream) {
1740 ret = -1;
1741 goto end;
1742 }
1743
1744 /*
1745 * Set last_net_seq_num before the close flag. Required by data
1746 * pending check.
1747 */
1748 pthread_mutex_lock(&stream->lock);
1749 stream->last_net_seq_num = stream_info.last_net_seq_num;
1750 pthread_mutex_unlock(&stream->lock);
1751
1752 /*
1753 * This is one of the conditions which may trigger a stream close
1754 * with the others being:
1755 * 1) A close command is received for a stream
1756 * 2) The control connection owning the stream is closed
1757 * 3) We have received all of the stream's data _after_ a close
1758 * request.
1759 */
1760 try_stream_close(stream);
1761 if (stream->is_metadata) {
1762 struct relay_viewer_stream *vstream;
1763
1764 vstream = viewer_stream_get_by_id(stream->stream_handle);
1765 if (vstream) {
1766 if (stream->no_new_metadata_notified) {
1767 /*
1768 * Since all the metadata has been sent to the
1769 * viewer and that we have a request to close
1770 * its stream, we can safely teardown the
1771 * corresponding metadata viewer stream.
1772 */
1773 viewer_stream_put(vstream);
1774 }
1775 /* Put local reference. */
1776 viewer_stream_put(vstream);
1777 }
1778 }
1779 stream_put(stream);
1780 ret = 0;
1781
1782 end:
1783 memset(&reply, 0, sizeof(reply));
1784 if (ret < 0) {
1785 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1786 } else {
1787 reply.ret_code = htobe32(LTTNG_OK);
1788 }
1789 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1790 sizeof(struct lttcomm_relayd_generic_reply), 0);
1791 if (send_ret < (ssize_t) sizeof(reply)) {
1792 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1793 send_ret);
1794 ret = -1;
1795 }
1796
1797 end_no_session:
1798 return ret;
1799 }
1800
1801 /*
1802 * relay_reset_metadata: reset a metadata stream
1803 */
1804 static
1805 int relay_reset_metadata(const struct lttcomm_relayd_hdr *recv_hdr,
1806 struct relay_connection *conn,
1807 const struct lttng_buffer_view *payload)
1808 {
1809 int ret;
1810 ssize_t send_ret;
1811 struct relay_session *session = conn->session;
1812 struct lttcomm_relayd_reset_metadata stream_info;
1813 struct lttcomm_relayd_generic_reply reply;
1814 struct relay_stream *stream;
1815
1816 DBG("Reset metadata received");
1817
1818 if (!session || !conn->version_check_done) {
1819 ERR("Trying to reset a metadata stream before version check");
1820 ret = -1;
1821 goto end_no_session;
1822 }
1823
1824 if (payload->size < sizeof(stream_info)) {
1825 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1826 sizeof(stream_info), payload->size);
1827 ret = -1;
1828 goto end_no_session;
1829 }
1830 memcpy(&stream_info, payload->data, sizeof(stream_info));
1831 stream_info.stream_id = be64toh(stream_info.stream_id);
1832 stream_info.version = be64toh(stream_info.version);
1833
1834 DBG("Update metadata to version %" PRIu64, stream_info.version);
1835
1836 /* Unsupported for live sessions for now. */
1837 if (session->live_timer != 0) {
1838 ret = -1;
1839 goto end;
1840 }
1841
1842 stream = stream_get_by_id(stream_info.stream_id);
1843 if (!stream) {
1844 ret = -1;
1845 goto end;
1846 }
1847 pthread_mutex_lock(&stream->lock);
1848 if (!stream->is_metadata) {
1849 ret = -1;
1850 goto end_unlock;
1851 }
1852
1853 ret = stream_reset_file(stream);
1854 if (ret < 0) {
1855 ERR("Failed to reset metadata stream %" PRIu64
1856 ": stream_path = %s, channel = %s",
1857 stream->stream_handle, stream->path_name,
1858 stream->channel_name);
1859 goto end_unlock;
1860 }
1861 end_unlock:
1862 pthread_mutex_unlock(&stream->lock);
1863 stream_put(stream);
1864
1865 end:
1866 memset(&reply, 0, sizeof(reply));
1867 if (ret < 0) {
1868 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1869 } else {
1870 reply.ret_code = htobe32(LTTNG_OK);
1871 }
1872 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1873 sizeof(struct lttcomm_relayd_generic_reply), 0);
1874 if (send_ret < (ssize_t) sizeof(reply)) {
1875 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1876 send_ret);
1877 ret = -1;
1878 }
1879
1880 end_no_session:
1881 return ret;
1882 }
1883
1884 /*
1885 * relay_unknown_command: send -1 if received unknown command
1886 */
1887 static void relay_unknown_command(struct relay_connection *conn)
1888 {
1889 struct lttcomm_relayd_generic_reply reply;
1890 ssize_t send_ret;
1891
1892 memset(&reply, 0, sizeof(reply));
1893 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1894 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1895 if (send_ret < sizeof(reply)) {
1896 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret);
1897 }
1898 }
1899
1900 /*
1901 * relay_start: send an acknowledgment to the client to tell if we are
1902 * ready to receive data. We are ready if a session is established.
1903 */
1904 static int relay_start(const struct lttcomm_relayd_hdr *recv_hdr,
1905 struct relay_connection *conn,
1906 const struct lttng_buffer_view *payload)
1907 {
1908 int ret = 0;
1909 ssize_t send_ret;
1910 struct lttcomm_relayd_generic_reply reply;
1911 struct relay_session *session = conn->session;
1912
1913 if (!session) {
1914 DBG("Trying to start the streaming without a session established");
1915 ret = htobe32(LTTNG_ERR_UNK);
1916 }
1917
1918 memset(&reply, 0, sizeof(reply));
1919 reply.ret_code = htobe32(LTTNG_OK);
1920 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1921 sizeof(reply), 0);
1922 if (send_ret < (ssize_t) sizeof(reply)) {
1923 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1924 send_ret);
1925 ret = -1;
1926 }
1927
1928 return ret;
1929 }
1930
1931 /*
1932 * relay_recv_metadata: receive the metadata for the session.
1933 */
1934 static int relay_recv_metadata(const struct lttcomm_relayd_hdr *recv_hdr,
1935 struct relay_connection *conn,
1936 const struct lttng_buffer_view *payload)
1937 {
1938 int ret = 0;
1939 struct relay_session *session = conn->session;
1940 struct lttcomm_relayd_metadata_payload metadata_payload_header;
1941 struct relay_stream *metadata_stream;
1942 uint64_t metadata_payload_size;
1943 struct lttng_buffer_view packet_view;
1944
1945 if (!session) {
1946 ERR("Metadata sent before version check");
1947 ret = -1;
1948 goto end;
1949 }
1950
1951 if (recv_hdr->data_size < sizeof(struct lttcomm_relayd_metadata_payload)) {
1952 ERR("Incorrect data size");
1953 ret = -1;
1954 goto end;
1955 }
1956 metadata_payload_size = recv_hdr->data_size -
1957 sizeof(struct lttcomm_relayd_metadata_payload);
1958
1959 memcpy(&metadata_payload_header, payload->data,
1960 sizeof(metadata_payload_header));
1961 metadata_payload_header.stream_id = be64toh(
1962 metadata_payload_header.stream_id);
1963 metadata_payload_header.padding_size = be32toh(
1964 metadata_payload_header.padding_size);
1965
1966 metadata_stream = stream_get_by_id(metadata_payload_header.stream_id);
1967 if (!metadata_stream) {
1968 ret = -1;
1969 goto end;
1970 }
1971
1972 packet_view = lttng_buffer_view_from_view(payload,
1973 sizeof(metadata_payload_header), metadata_payload_size);
1974 if (!lttng_buffer_view_is_valid(&packet_view)) {
1975 ERR("Invalid metadata packet length announced by header");
1976 ret = -1;
1977 goto end_put;
1978 }
1979
1980 pthread_mutex_lock(&metadata_stream->lock);
1981 ret = stream_write(metadata_stream, &packet_view,
1982 metadata_payload_header.padding_size);
1983 pthread_mutex_unlock(&metadata_stream->lock);
1984 if (ret){
1985 ret = -1;
1986 goto end_put;
1987 }
1988 end_put:
1989 stream_put(metadata_stream);
1990 end:
1991 return ret;
1992 }
1993
1994 /*
1995 * relay_send_version: send relayd version number
1996 */
1997 static int relay_send_version(const struct lttcomm_relayd_hdr *recv_hdr,
1998 struct relay_connection *conn,
1999 const struct lttng_buffer_view *payload)
2000 {
2001 int ret;
2002 ssize_t send_ret;
2003 struct lttcomm_relayd_version reply, msg;
2004 bool compatible = true;
2005
2006 conn->version_check_done = true;
2007
2008 /* Get version from the other side. */
2009 if (payload->size < sizeof(msg)) {
2010 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
2011 sizeof(msg), payload->size);
2012 ret = -1;
2013 goto end;
2014 }
2015
2016 memcpy(&msg, payload->data, sizeof(msg));
2017 msg.major = be32toh(msg.major);
2018 msg.minor = be32toh(msg.minor);
2019
2020 memset(&reply, 0, sizeof(reply));
2021 reply.major = RELAYD_VERSION_COMM_MAJOR;
2022 reply.minor = RELAYD_VERSION_COMM_MINOR;
2023
2024 /* Major versions must be the same */
2025 if (reply.major != msg.major) {
2026 DBG("Incompatible major versions (%u vs %u), deleting session",
2027 reply.major, msg.major);
2028 compatible = false;
2029 }
2030
2031 conn->major = reply.major;
2032 /* We adapt to the lowest compatible version */
2033 if (reply.minor <= msg.minor) {
2034 conn->minor = reply.minor;
2035 } else {
2036 conn->minor = msg.minor;
2037 }
2038
2039 reply.major = htobe32(reply.major);
2040 reply.minor = htobe32(reply.minor);
2041 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
2042 sizeof(reply), 0);
2043 if (send_ret < (ssize_t) sizeof(reply)) {
2044 ERR("Failed to send \"send version\" command reply (ret = %zd)",
2045 send_ret);
2046 ret = -1;
2047 goto end;
2048 } else {
2049 ret = 0;
2050 }
2051
2052 if (!compatible) {
2053 ret = -1;
2054 goto end;
2055 }
2056
2057 DBG("Version check done using protocol %u.%u", conn->major,
2058 conn->minor);
2059
2060 end:
2061 return ret;
2062 }
2063
2064 /*
2065 * Check for data pending for a given stream id from the session daemon.
2066 */
2067 static int relay_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
2068 struct relay_connection *conn,
2069 const struct lttng_buffer_view *payload)
2070 {
2071 struct relay_session *session = conn->session;
2072 struct lttcomm_relayd_data_pending msg;
2073 struct lttcomm_relayd_generic_reply reply;
2074 struct relay_stream *stream;
2075 ssize_t send_ret;
2076 int ret;
2077 uint64_t stream_seq;
2078
2079 DBG("Data pending command received");
2080
2081 if (!session || !conn->version_check_done) {
2082 ERR("Trying to check for data before version check");
2083 ret = -1;
2084 goto end_no_session;
2085 }
2086
2087 if (payload->size < sizeof(msg)) {
2088 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
2089 sizeof(msg), payload->size);
2090 ret = -1;
2091 goto end_no_session;
2092 }
2093 memcpy(&msg, payload->data, sizeof(msg));
2094 msg.stream_id = be64toh(msg.stream_id);
2095 msg.last_net_seq_num = be64toh(msg.last_net_seq_num);
2096
2097 stream = stream_get_by_id(msg.stream_id);
2098 if (stream == NULL) {
2099 ret = -1;
2100 goto end;
2101 }
2102
2103 pthread_mutex_lock(&stream->lock);
2104
2105 if (session_streams_have_index(session)) {
2106 /*
2107 * Ensure that both the index and stream data have been
2108 * flushed up to the requested point.
2109 */
2110 stream_seq = std::min(stream->prev_data_seq, stream->prev_index_seq);
2111 } else {
2112 stream_seq = stream->prev_data_seq;
2113 }
2114 DBG("Data pending for stream id %" PRIu64 ": prev_data_seq %" PRIu64
2115 ", prev_index_seq %" PRIu64
2116 ", and last_seq %" PRIu64, msg.stream_id,
2117 stream->prev_data_seq, stream->prev_index_seq,
2118 msg.last_net_seq_num);
2119
2120 /* Avoid wrapping issue */
2121 if (((int64_t) (stream_seq - msg.last_net_seq_num)) >= 0) {
2122 /* Data has in fact been written and is NOT pending */
2123 ret = 0;
2124 } else {
2125 /* Data still being streamed thus pending */
2126 ret = 1;
2127 }
2128
2129 stream->data_pending_check_done = true;
2130 pthread_mutex_unlock(&stream->lock);
2131
2132 stream_put(stream);
2133 end:
2134
2135 memset(&reply, 0, sizeof(reply));
2136 reply.ret_code = htobe32(ret);
2137 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2138 if (send_ret < (ssize_t) sizeof(reply)) {
2139 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
2140 send_ret);
2141 ret = -1;
2142 }
2143
2144 end_no_session:
2145 return ret;
2146 }
2147
2148 /*
2149 * Wait for the control socket to reach a quiescent state.
2150 *
2151 * Note that for now, when receiving this command from the session
2152 * daemon, this means that every subsequent commands or data received on
2153 * the control socket has been handled. So, this is why we simply return
2154 * OK here.
2155 */
2156 static int relay_quiescent_control(const struct lttcomm_relayd_hdr *recv_hdr,
2157 struct relay_connection *conn,
2158 const struct lttng_buffer_view *payload)
2159 {
2160 int ret;
2161 ssize_t send_ret;
2162 struct relay_stream *stream;
2163 struct lttcomm_relayd_quiescent_control msg;
2164 struct lttcomm_relayd_generic_reply reply;
2165
2166 DBG("Checking quiescent state on control socket");
2167
2168 if (!conn->session || !conn->version_check_done) {
2169 ERR("Trying to check for data before version check");
2170 ret = -1;
2171 goto end_no_session;
2172 }
2173
2174 if (payload->size < sizeof(msg)) {
2175 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2176 sizeof(msg), payload->size);
2177 ret = -1;
2178 goto end_no_session;
2179 }
2180 memcpy(&msg, payload->data, sizeof(msg));
2181 msg.stream_id = be64toh(msg.stream_id);
2182
2183 stream = stream_get_by_id(msg.stream_id);
2184 if (!stream) {
2185 goto reply;
2186 }
2187 pthread_mutex_lock(&stream->lock);
2188 stream->data_pending_check_done = true;
2189 pthread_mutex_unlock(&stream->lock);
2190
2191 DBG("Relay quiescent control pending flag set to %" PRIu64, msg.stream_id);
2192 stream_put(stream);
2193 reply:
2194 memset(&reply, 0, sizeof(reply));
2195 reply.ret_code = htobe32(LTTNG_OK);
2196 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2197 if (send_ret < (ssize_t) sizeof(reply)) {
2198 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
2199 send_ret);
2200 ret = -1;
2201 } else {
2202 ret = 0;
2203 }
2204
2205 end_no_session:
2206 return ret;
2207 }
2208
2209 /*
2210 * Initialize a data pending command. This means that a consumer is about
2211 * to ask for data pending for each stream it holds. Simply iterate over
2212 * all streams of a session and set the data_pending_check_done flag.
2213 *
2214 * This command returns to the client a LTTNG_OK code.
2215 */
2216 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
2217 struct relay_connection *conn,
2218 const struct lttng_buffer_view *payload)
2219 {
2220 int ret;
2221 ssize_t send_ret;
2222 struct lttng_ht_iter iter;
2223 struct lttcomm_relayd_begin_data_pending msg;
2224 struct lttcomm_relayd_generic_reply reply;
2225 struct relay_stream *stream;
2226
2227 LTTNG_ASSERT(recv_hdr);
2228 LTTNG_ASSERT(conn);
2229
2230 DBG("Init streams for data pending");
2231
2232 if (!conn->session || !conn->version_check_done) {
2233 ERR("Trying to check for data before version check");
2234 ret = -1;
2235 goto end_no_session;
2236 }
2237
2238 if (payload->size < sizeof(msg)) {
2239 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2240 sizeof(msg), payload->size);
2241 ret = -1;
2242 goto end_no_session;
2243 }
2244 memcpy(&msg, payload->data, sizeof(msg));
2245 msg.session_id = be64toh(msg.session_id);
2246
2247 /*
2248 * Iterate over all streams to set the begin data pending flag.
2249 * For now, the streams are indexed by stream handle so we have
2250 * to iterate over all streams to find the one associated with
2251 * the right session_id.
2252 */
2253 rcu_read_lock();
2254 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2255 node.node) {
2256 if (!stream_get(stream)) {
2257 continue;
2258 }
2259 if (stream->trace->session->id == msg.session_id) {
2260 pthread_mutex_lock(&stream->lock);
2261 stream->data_pending_check_done = false;
2262 pthread_mutex_unlock(&stream->lock);
2263 DBG("Set begin data pending flag to stream %" PRIu64,
2264 stream->stream_handle);
2265 }
2266 stream_put(stream);
2267 }
2268 rcu_read_unlock();
2269
2270 memset(&reply, 0, sizeof(reply));
2271 /* All good, send back reply. */
2272 reply.ret_code = htobe32(LTTNG_OK);
2273
2274 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2275 if (send_ret < (ssize_t) sizeof(reply)) {
2276 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2277 send_ret);
2278 ret = -1;
2279 } else {
2280 ret = 0;
2281 }
2282
2283 end_no_session:
2284 return ret;
2285 }
2286
2287 /*
2288 * End data pending command. This will check, for a given session id, if
2289 * each stream associated with it has its data_pending_check_done flag
2290 * set. If not, this means that the client lost track of the stream but
2291 * the data is still being streamed on our side. In this case, we inform
2292 * the client that data is in flight.
2293 *
2294 * Return to the client if there is data in flight or not with a ret_code.
2295 */
2296 static int relay_end_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
2297 struct relay_connection *conn,
2298 const struct lttng_buffer_view *payload)
2299 {
2300 int ret;
2301 ssize_t send_ret;
2302 struct lttng_ht_iter iter;
2303 struct lttcomm_relayd_end_data_pending msg;
2304 struct lttcomm_relayd_generic_reply reply;
2305 struct relay_stream *stream;
2306 uint32_t is_data_inflight = 0;
2307
2308 DBG("End data pending command");
2309
2310 if (!conn->session || !conn->version_check_done) {
2311 ERR("Trying to check for data before version check");
2312 ret = -1;
2313 goto end_no_session;
2314 }
2315
2316 if (payload->size < sizeof(msg)) {
2317 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2318 sizeof(msg), payload->size);
2319 ret = -1;
2320 goto end_no_session;
2321 }
2322 memcpy(&msg, payload->data, sizeof(msg));
2323 msg.session_id = be64toh(msg.session_id);
2324
2325 /*
2326 * Iterate over all streams to see if the begin data pending
2327 * flag is set.
2328 */
2329 rcu_read_lock();
2330 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2331 node.node) {
2332 if (!stream_get(stream)) {
2333 continue;
2334 }
2335 if (stream->trace->session->id != msg.session_id) {
2336 stream_put(stream);
2337 continue;
2338 }
2339 pthread_mutex_lock(&stream->lock);
2340 if (!stream->data_pending_check_done) {
2341 uint64_t stream_seq;
2342
2343 if (session_streams_have_index(conn->session)) {
2344 /*
2345 * Ensure that both the index and stream data have been
2346 * flushed up to the requested point.
2347 */
2348 stream_seq = std::min(stream->prev_data_seq, stream->prev_index_seq);
2349 } else {
2350 stream_seq = stream->prev_data_seq;
2351 }
2352 if (!stream->closed || !(((int64_t) (stream_seq - stream->last_net_seq_num)) >= 0)) {
2353 is_data_inflight = 1;
2354 DBG("Data is still in flight for stream %" PRIu64,
2355 stream->stream_handle);
2356 pthread_mutex_unlock(&stream->lock);
2357 stream_put(stream);
2358 break;
2359 }
2360 }
2361 pthread_mutex_unlock(&stream->lock);
2362 stream_put(stream);
2363 }
2364 rcu_read_unlock();
2365
2366 memset(&reply, 0, sizeof(reply));
2367 /* All good, send back reply. */
2368 reply.ret_code = htobe32(is_data_inflight);
2369
2370 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2371 if (send_ret < (ssize_t) sizeof(reply)) {
2372 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2373 send_ret);
2374 ret = -1;
2375 } else {
2376 ret = 0;
2377 }
2378
2379 end_no_session:
2380 return ret;
2381 }
2382
2383 /*
2384 * Receive an index for a specific stream.
2385 *
2386 * Return 0 on success else a negative value.
2387 */
2388 static int relay_recv_index(const struct lttcomm_relayd_hdr *recv_hdr,
2389 struct relay_connection *conn,
2390 const struct lttng_buffer_view *payload)
2391 {
2392 int ret;
2393 ssize_t send_ret;
2394 struct relay_session *session = conn->session;
2395 struct lttcomm_relayd_index index_info;
2396 struct lttcomm_relayd_generic_reply reply;
2397 struct relay_stream *stream;
2398 size_t msg_len;
2399
2400 LTTNG_ASSERT(conn);
2401
2402 DBG("Relay receiving index");
2403
2404 if (!session || !conn->version_check_done) {
2405 ERR("Trying to close a stream before version check");
2406 ret = -1;
2407 goto end_no_session;
2408 }
2409
2410 msg_len = lttcomm_relayd_index_len(
2411 lttng_to_index_major(conn->major, conn->minor),
2412 lttng_to_index_minor(conn->major, conn->minor));
2413 if (payload->size < msg_len) {
2414 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2415 msg_len, payload->size);
2416 ret = -1;
2417 goto end_no_session;
2418 }
2419 memcpy(&index_info, payload->data, msg_len);
2420 index_info.relay_stream_id = be64toh(index_info.relay_stream_id);
2421 index_info.net_seq_num = be64toh(index_info.net_seq_num);
2422 index_info.packet_size = be64toh(index_info.packet_size);
2423 index_info.content_size = be64toh(index_info.content_size);
2424 index_info.timestamp_begin = be64toh(index_info.timestamp_begin);
2425 index_info.timestamp_end = be64toh(index_info.timestamp_end);
2426 index_info.events_discarded = be64toh(index_info.events_discarded);
2427 index_info.stream_id = be64toh(index_info.stream_id);
2428
2429 if (conn->minor >= 8) {
2430 index_info.stream_instance_id =
2431 be64toh(index_info.stream_instance_id);
2432 index_info.packet_seq_num = be64toh(index_info.packet_seq_num);
2433 } else {
2434 index_info.stream_instance_id = -1ULL;
2435 index_info.packet_seq_num = -1ULL;
2436 }
2437
2438 stream = stream_get_by_id(index_info.relay_stream_id);
2439 if (!stream) {
2440 ERR("stream_get_by_id not found");
2441 ret = -1;
2442 goto end;
2443 }
2444
2445 pthread_mutex_lock(&stream->lock);
2446 ret = stream_add_index(stream, &index_info);
2447 pthread_mutex_unlock(&stream->lock);
2448 if (ret) {
2449 goto end_stream_put;
2450 }
2451
2452 end_stream_put:
2453 stream_put(stream);
2454 end:
2455 memset(&reply, 0, sizeof(reply));
2456 if (ret < 0) {
2457 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2458 } else {
2459 reply.ret_code = htobe32(LTTNG_OK);
2460 }
2461 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2462 if (send_ret < (ssize_t) sizeof(reply)) {
2463 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret);
2464 ret = -1;
2465 }
2466
2467 end_no_session:
2468 return ret;
2469 }
2470
2471 /*
2472 * Receive the streams_sent message.
2473 *
2474 * Return 0 on success else a negative value.
2475 */
2476 static int relay_streams_sent(const struct lttcomm_relayd_hdr *recv_hdr,
2477 struct relay_connection *conn,
2478 const struct lttng_buffer_view *payload)
2479 {
2480 int ret;
2481 ssize_t send_ret;
2482 struct lttcomm_relayd_generic_reply reply;
2483
2484 LTTNG_ASSERT(conn);
2485
2486 DBG("Relay receiving streams_sent");
2487
2488 if (!conn->session || !conn->version_check_done) {
2489 ERR("Trying to close a stream before version check");
2490 ret = -1;
2491 goto end_no_session;
2492 }
2493
2494 /*
2495 * Publish every pending stream in the connection recv list which are
2496 * now ready to be used by the viewer.
2497 */
2498 publish_connection_local_streams(conn);
2499
2500 memset(&reply, 0, sizeof(reply));
2501 reply.ret_code = htobe32(LTTNG_OK);
2502 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2503 if (send_ret < (ssize_t) sizeof(reply)) {
2504 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2505 send_ret);
2506 ret = -1;
2507 } else {
2508 /* Success. */
2509 ret = 0;
2510 }
2511
2512 end_no_session:
2513 return ret;
2514 }
2515
2516 /*
2517 * relay_rotate_session_stream: rotate a stream to a new tracefile for the
2518 * session rotation feature (not the tracefile rotation feature).
2519 */
2520 static int relay_rotate_session_streams(
2521 const struct lttcomm_relayd_hdr *recv_hdr,
2522 struct relay_connection *conn,
2523 const struct lttng_buffer_view *payload)
2524 {
2525 int ret = 0;
2526 uint32_t i;
2527 ssize_t send_ret;
2528 enum lttng_error_code reply_code = LTTNG_ERR_UNK;
2529 struct relay_session *session = conn->session;
2530 struct lttcomm_relayd_rotate_streams rotate_streams;
2531 struct lttcomm_relayd_generic_reply reply = {};
2532 struct relay_stream *stream = NULL;
2533 const size_t header_len = sizeof(struct lttcomm_relayd_rotate_streams);
2534 struct lttng_trace_chunk *next_trace_chunk = NULL;
2535 struct lttng_buffer_view stream_positions;
2536 char chunk_id_buf[MAX_INT_DEC_LEN(uint64_t)];
2537 const char *chunk_id_str = "none";
2538
2539 if (!session || !conn->version_check_done) {
2540 ERR("Trying to rotate a stream before version check");
2541 ret = -1;
2542 goto end_no_reply;
2543 }
2544
2545 if (session->major == 2 && session->minor < 11) {
2546 ERR("Unsupported feature before 2.11");
2547 ret = -1;
2548 goto end_no_reply;
2549 }
2550
2551 if (payload->size < header_len) {
2552 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2553 header_len, payload->size);
2554 ret = -1;
2555 goto end_no_reply;
2556 }
2557
2558 memcpy(&rotate_streams, payload->data, header_len);
2559
2560 /* Convert header to host endianness. */
2561 rotate_streams = (typeof(rotate_streams)) {
2562 .stream_count = be32toh(rotate_streams.stream_count),
2563 .new_chunk_id = (typeof(rotate_streams.new_chunk_id)) {
2564 .is_set = !!rotate_streams.new_chunk_id.is_set,
2565 .value = be64toh(rotate_streams.new_chunk_id.value),
2566 }
2567 };
2568
2569 if (rotate_streams.new_chunk_id.is_set) {
2570 /*
2571 * Retrieve the trace chunk the stream must transition to. As
2572 * per the protocol, this chunk should have been created
2573 * before this command is received.
2574 */
2575 next_trace_chunk = sessiond_trace_chunk_registry_get_chunk(
2576 sessiond_trace_chunk_registry,
2577 session->sessiond_uuid, session->id,
2578 rotate_streams.new_chunk_id.value);
2579 if (!next_trace_chunk) {
2580 char uuid_str[LTTNG_UUID_STR_LEN];
2581
2582 lttng_uuid_to_str(session->sessiond_uuid, uuid_str);
2583 ERR("Unknown next trace chunk in ROTATE_STREAMS command: sessiond_uuid = {%s}, session_id = %" PRIu64
2584 ", trace_chunk_id = %" PRIu64,
2585 uuid_str, session->id,
2586 rotate_streams.new_chunk_id.value);
2587 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2588 ret = -1;
2589 goto end;
2590 }
2591
2592 ret = snprintf(chunk_id_buf, sizeof(chunk_id_buf), "%" PRIu64,
2593 rotate_streams.new_chunk_id.value);
2594 if (ret < 0 || ret >= sizeof(chunk_id_buf)) {
2595 chunk_id_str = "formatting error";
2596 } else {
2597 chunk_id_str = chunk_id_buf;
2598 }
2599 }
2600
2601 DBG("Rotate %" PRIu32 " streams of session \"%s\" to chunk \"%s\"",
2602 rotate_streams.stream_count, session->session_name,
2603 chunk_id_str);
2604
2605 stream_positions = lttng_buffer_view_from_view(payload,
2606 sizeof(rotate_streams), -1);
2607 if (!stream_positions.data ||
2608 stream_positions.size <
2609 (rotate_streams.stream_count *
2610 sizeof(struct lttcomm_relayd_stream_rotation_position))) {
2611 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2612 ret = -1;
2613 goto end;
2614 }
2615
2616 for (i = 0; i < rotate_streams.stream_count; i++) {
2617 struct lttcomm_relayd_stream_rotation_position *position_comm =
2618 &((typeof(position_comm)) stream_positions.data)[i];
2619 const struct lttcomm_relayd_stream_rotation_position pos = {
2620 .stream_id = be64toh(position_comm->stream_id),
2621 .rotate_at_seq_num = be64toh(
2622 position_comm->rotate_at_seq_num),
2623 };
2624
2625 stream = stream_get_by_id(pos.stream_id);
2626 if (!stream) {
2627 reply_code = LTTNG_ERR_INVALID;
2628 ret = -1;
2629 goto end;
2630 }
2631
2632 pthread_mutex_lock(&stream->lock);
2633 ret = stream_set_pending_rotation(stream, next_trace_chunk,
2634 pos.rotate_at_seq_num);
2635 pthread_mutex_unlock(&stream->lock);
2636 if (ret) {
2637 reply_code = LTTNG_ERR_FILE_CREATION_ERROR;
2638 goto end;
2639 }
2640
2641 stream_put(stream);
2642 stream = NULL;
2643 }
2644
2645 reply_code = LTTNG_OK;
2646 ret = 0;
2647 end:
2648 if (stream) {
2649 stream_put(stream);
2650 }
2651
2652 reply.ret_code = htobe32((uint32_t) reply_code);
2653 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
2654 sizeof(struct lttcomm_relayd_generic_reply), 0);
2655 if (send_ret < (ssize_t) sizeof(reply)) {
2656 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2657 send_ret);
2658 ret = -1;
2659 }
2660 end_no_reply:
2661 lttng_trace_chunk_put(next_trace_chunk);
2662 return ret;
2663 }
2664
2665
2666
2667 /*
2668 * relay_create_trace_chunk: create a new trace chunk
2669 */
2670 static int relay_create_trace_chunk(const struct lttcomm_relayd_hdr *recv_hdr,
2671 struct relay_connection *conn,
2672 const struct lttng_buffer_view *payload)
2673 {
2674 int ret = 0;
2675 ssize_t send_ret;
2676 struct relay_session *session = conn->session;
2677 struct lttcomm_relayd_create_trace_chunk *msg;
2678 struct lttcomm_relayd_generic_reply reply = {};
2679 struct lttng_buffer_view header_view;
2680 struct lttng_trace_chunk *chunk = NULL, *published_chunk = NULL;
2681 enum lttng_error_code reply_code = LTTNG_OK;
2682 enum lttng_trace_chunk_status chunk_status;
2683 const char *new_path;
2684
2685 if (!session || !conn->version_check_done) {
2686 ERR("Trying to create a trace chunk before version check");
2687 ret = -1;
2688 goto end_no_reply;
2689 }
2690
2691 if (session->major == 2 && session->minor < 11) {
2692 ERR("Chunk creation command is unsupported before 2.11");
2693 ret = -1;
2694 goto end_no_reply;
2695 }
2696
2697 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
2698 if (!lttng_buffer_view_is_valid(&header_view)) {
2699 ERR("Failed to receive payload of chunk creation command");
2700 ret = -1;
2701 goto end_no_reply;
2702 }
2703
2704 /* Convert to host endianness. */
2705 msg = (typeof(msg)) header_view.data;
2706 msg->chunk_id = be64toh(msg->chunk_id);
2707 msg->creation_timestamp = be64toh(msg->creation_timestamp);
2708 msg->override_name_length = be32toh(msg->override_name_length);
2709
2710 if (session->current_trace_chunk &&
2711 !lttng_trace_chunk_get_name_overridden(session->current_trace_chunk)) {
2712 chunk_status = lttng_trace_chunk_rename_path(session->current_trace_chunk,
2713 DEFAULT_CHUNK_TMP_OLD_DIRECTORY);
2714 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2715 ERR("Failed to rename old chunk");
2716 ret = -1;
2717 reply_code = LTTNG_ERR_UNK;
2718 goto end;
2719 }
2720 }
2721 session->ongoing_rotation = true;
2722 if (!session->current_trace_chunk) {
2723 if (!session->has_rotated) {
2724 new_path = "";
2725 } else {
2726 new_path = NULL;
2727 }
2728 } else {
2729 new_path = DEFAULT_CHUNK_TMP_NEW_DIRECTORY;
2730 }
2731 chunk = lttng_trace_chunk_create(
2732 msg->chunk_id, msg->creation_timestamp, new_path);
2733 if (!chunk) {
2734 ERR("Failed to create trace chunk in trace chunk creation command");
2735 ret = -1;
2736 reply_code = LTTNG_ERR_NOMEM;
2737 goto end;
2738 }
2739 lttng_trace_chunk_set_fd_tracker(chunk, the_fd_tracker);
2740
2741 if (msg->override_name_length) {
2742 const char *name;
2743 const struct lttng_buffer_view chunk_name_view =
2744 lttng_buffer_view_from_view(payload,
2745 sizeof(*msg),
2746 msg->override_name_length);
2747
2748 if (!lttng_buffer_view_is_valid(&chunk_name_view)) {
2749 ERR("Invalid payload of chunk creation command (protocol error): buffer too short for expected name length");
2750 ret = -1;
2751 reply_code = LTTNG_ERR_INVALID;
2752 goto end;
2753 }
2754
2755 name = chunk_name_view.data;
2756 if (name[msg->override_name_length - 1]) {
2757 ERR("Invalid payload of chunk creation command (protocol error): name is not null-terminated");
2758 ret = -1;
2759 reply_code = LTTNG_ERR_INVALID;
2760 goto end;
2761 }
2762
2763 chunk_status = lttng_trace_chunk_override_name(
2764 chunk, chunk_name_view.data);
2765 switch (chunk_status) {
2766 case LTTNG_TRACE_CHUNK_STATUS_OK:
2767 break;
2768 case LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT:
2769 ERR("Failed to set the name of new trace chunk in trace chunk creation command (invalid name)");
2770 reply_code = LTTNG_ERR_INVALID;
2771 ret = -1;
2772 goto end;
2773 default:
2774 ERR("Failed to set the name of new trace chunk in trace chunk creation command (unknown error)");
2775 reply_code = LTTNG_ERR_UNK;
2776 ret = -1;
2777 goto end;
2778 }
2779 }
2780
2781 chunk_status = lttng_trace_chunk_set_credentials_current_user(chunk);
2782 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2783 reply_code = LTTNG_ERR_UNK;
2784 ret = -1;
2785 goto end;
2786 }
2787
2788 LTTNG_ASSERT(conn->session->output_directory);
2789 chunk_status = lttng_trace_chunk_set_as_owner(chunk,
2790 conn->session->output_directory);
2791 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2792 reply_code = LTTNG_ERR_UNK;
2793 ret = -1;
2794 goto end;
2795 }
2796
2797 published_chunk = sessiond_trace_chunk_registry_publish_chunk(
2798 sessiond_trace_chunk_registry,
2799 conn->session->sessiond_uuid,
2800 conn->session->id,
2801 chunk);
2802 if (!published_chunk) {
2803 char uuid_str[LTTNG_UUID_STR_LEN];
2804
2805 lttng_uuid_to_str(conn->session->sessiond_uuid, uuid_str);
2806 ERR("Failed to publish chunk: sessiond_uuid = %s, session_id = %" PRIu64 ", chunk_id = %" PRIu64,
2807 uuid_str,
2808 conn->session->id,
2809 msg->chunk_id);
2810 ret = -1;
2811 reply_code = LTTNG_ERR_NOMEM;
2812 goto end;
2813 }
2814
2815 pthread_mutex_lock(&conn->session->lock);
2816 if (conn->session->pending_closure_trace_chunk) {
2817 /*
2818 * Invalid; this means a second create_trace_chunk command was
2819 * received before a close_trace_chunk.
2820 */
2821 ERR("Invalid trace chunk close command received; a trace chunk is already waiting for a trace chunk close command");
2822 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2823 ret = -1;
2824 goto end_unlock_session;
2825 }
2826 conn->session->pending_closure_trace_chunk =
2827 conn->session->current_trace_chunk;
2828 conn->session->current_trace_chunk = published_chunk;
2829 published_chunk = NULL;
2830 if (!conn->session->pending_closure_trace_chunk) {
2831 session->ongoing_rotation = false;
2832 }
2833 end_unlock_session:
2834 pthread_mutex_unlock(&conn->session->lock);
2835 end:
2836 reply.ret_code = htobe32((uint32_t) reply_code);
2837 send_ret = conn->sock->ops->sendmsg(conn->sock,
2838 &reply,
2839 sizeof(struct lttcomm_relayd_generic_reply),
2840 0);
2841 if (send_ret < (ssize_t) sizeof(reply)) {
2842 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
2843 send_ret);
2844 ret = -1;
2845 }
2846 end_no_reply:
2847 lttng_trace_chunk_put(chunk);
2848 lttng_trace_chunk_put(published_chunk);
2849 return ret;
2850 }
2851
2852 /*
2853 * relay_close_trace_chunk: close a trace chunk
2854 */
2855 static int relay_close_trace_chunk(const struct lttcomm_relayd_hdr *recv_hdr,
2856 struct relay_connection *conn,
2857 const struct lttng_buffer_view *payload)
2858 {
2859 int ret = 0, buf_ret;
2860 ssize_t send_ret;
2861 struct relay_session *session = conn->session;
2862 struct lttcomm_relayd_close_trace_chunk *msg;
2863 struct lttcomm_relayd_close_trace_chunk_reply reply = {};
2864 struct lttng_buffer_view header_view;
2865 struct lttng_trace_chunk *chunk = NULL;
2866 enum lttng_error_code reply_code = LTTNG_OK;
2867 enum lttng_trace_chunk_status chunk_status;
2868 uint64_t chunk_id;
2869 LTTNG_OPTIONAL(enum lttng_trace_chunk_command_type) close_command = {};
2870 time_t close_timestamp;
2871 char closed_trace_chunk_path[LTTNG_PATH_MAX];
2872 size_t path_length = 0;
2873 const char *chunk_name = NULL;
2874 struct lttng_dynamic_buffer reply_payload;
2875 const char *new_path;
2876
2877 lttng_dynamic_buffer_init(&reply_payload);
2878
2879 if (!session || !conn->version_check_done) {
2880 ERR("Trying to close a trace chunk before version check");
2881 ret = -1;
2882 goto end_no_reply;
2883 }
2884
2885 if (session->major == 2 && session->minor < 11) {
2886 ERR("Chunk close command is unsupported before 2.11");
2887 ret = -1;
2888 goto end_no_reply;
2889 }
2890
2891 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
2892 if (!lttng_buffer_view_is_valid(&header_view)) {
2893 ERR("Failed to receive payload of chunk close command");
2894 ret = -1;
2895 goto end_no_reply;
2896 }
2897
2898 /* Convert to host endianness. */
2899 msg = (typeof(msg)) header_view.data;
2900 chunk_id = be64toh(msg->chunk_id);
2901 close_timestamp = (time_t) be64toh(msg->close_timestamp);
2902 close_command.value = (lttng_trace_chunk_command_type) be32toh(msg->close_command.value);
2903 close_command.is_set = msg->close_command.is_set;
2904
2905 chunk = sessiond_trace_chunk_registry_get_chunk(
2906 sessiond_trace_chunk_registry,
2907 conn->session->sessiond_uuid,
2908 conn->session->id,
2909 chunk_id);
2910 if (!chunk) {
2911 char uuid_str[LTTNG_UUID_STR_LEN];
2912
2913 lttng_uuid_to_str(conn->session->sessiond_uuid, uuid_str);
2914 ERR("Failed to find chunk to close: sessiond_uuid = %s, session_id = %" PRIu64 ", chunk_id = %" PRIu64,
2915 uuid_str,
2916 conn->session->id,
2917 msg->chunk_id);
2918 ret = -1;
2919 reply_code = LTTNG_ERR_NOMEM;
2920 goto end;
2921 }
2922
2923 pthread_mutex_lock(&session->lock);
2924 if (close_command.is_set &&
2925 close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE) {
2926 /*
2927 * Clear command. It is a protocol error to ask for a
2928 * clear on a relay which does not allow it. Querying
2929 * the configuration allows figuring out whether
2930 * clearing is allowed before doing the clear.
2931 */
2932 if (!opt_allow_clear) {
2933 ret = -1;
2934 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2935 goto end_unlock_session;
2936 }
2937 }
2938 if (session->pending_closure_trace_chunk &&
2939 session->pending_closure_trace_chunk != chunk) {
2940 ERR("Trace chunk close command for session \"%s\" does not target the trace chunk pending closure",
2941 session->session_name);
2942 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2943 ret = -1;
2944 goto end_unlock_session;
2945 }
2946
2947 if (session->current_trace_chunk && session->current_trace_chunk != chunk &&
2948 !lttng_trace_chunk_get_name_overridden(session->current_trace_chunk)) {
2949 if (close_command.is_set &&
2950 close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE &&
2951 !session->has_rotated) {
2952 /* New chunk stays in session output directory. */
2953 new_path = "";
2954 } else {
2955 /* Use chunk name for new chunk. */
2956 new_path = NULL;
2957 }
2958 /* Rename new chunk path. */
2959 chunk_status = lttng_trace_chunk_rename_path(session->current_trace_chunk,
2960 new_path);
2961 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2962 ret = -1;
2963 goto end_unlock_session;
2964 }
2965 session->ongoing_rotation = false;
2966 }
2967 if ((!close_command.is_set ||
2968 close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION) &&
2969 !lttng_trace_chunk_get_name_overridden(chunk)) {
2970 const char *old_path;
2971
2972 if (!session->has_rotated) {
2973 old_path = "";
2974 } else {
2975 old_path = NULL;
2976 }
2977 /* We need to move back the .tmp_old_chunk to its rightful place. */
2978 chunk_status = lttng_trace_chunk_rename_path(chunk, old_path);
2979 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2980 ret = -1;
2981 goto end_unlock_session;
2982 }
2983 }
2984 chunk_status = lttng_trace_chunk_set_close_timestamp(
2985 chunk, close_timestamp);
2986 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2987 ERR("Failed to set trace chunk close timestamp");
2988 ret = -1;
2989 reply_code = LTTNG_ERR_UNK;
2990 goto end_unlock_session;
2991 }
2992
2993 if (close_command.is_set) {
2994 chunk_status = lttng_trace_chunk_set_close_command(
2995 chunk, close_command.value);
2996 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2997 ret = -1;
2998 reply_code = LTTNG_ERR_INVALID;
2999 goto end_unlock_session;
3000 }
3001 }
3002 chunk_status = lttng_trace_chunk_get_name(chunk, &chunk_name, NULL);
3003 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
3004 ERR("Failed to get chunk name");
3005 ret = -1;
3006 reply_code = LTTNG_ERR_UNK;
3007 goto end_unlock_session;
3008 }
3009 if (!session->has_rotated && !session->snapshot) {
3010 ret = lttng_strncpy(closed_trace_chunk_path,
3011 session->output_path,
3012 sizeof(closed_trace_chunk_path));
3013 if (ret) {
3014 ERR("Failed to send trace chunk path: path length of %zu bytes exceeds the maximal allowed length of %zu bytes",
3015 strlen(session->output_path),
3016 sizeof(closed_trace_chunk_path));
3017 reply_code = LTTNG_ERR_NOMEM;
3018 ret = -1;
3019 goto end_unlock_session;
3020 }
3021 } else {
3022 if (session->snapshot) {
3023 ret = snprintf(closed_trace_chunk_path,
3024 sizeof(closed_trace_chunk_path),
3025 "%s/%s", session->output_path,
3026 chunk_name);
3027 } else {
3028 ret = snprintf(closed_trace_chunk_path,
3029 sizeof(closed_trace_chunk_path),
3030 "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY
3031 "/%s",
3032 session->output_path, chunk_name);
3033 }
3034 if (ret < 0 || ret == sizeof(closed_trace_chunk_path)) {
3035 ERR("Failed to format closed trace chunk resulting path");
3036 reply_code = ret < 0 ? LTTNG_ERR_UNK : LTTNG_ERR_NOMEM;
3037 ret = -1;
3038 goto end_unlock_session;
3039 }
3040 }
3041 if (close_command.is_set &&
3042 close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED) {
3043 session->has_rotated = true;
3044 }
3045 DBG("Reply chunk path on close: %s", closed_trace_chunk_path);
3046 path_length = strlen(closed_trace_chunk_path) + 1;
3047 if (path_length > UINT32_MAX) {
3048 ERR("Closed trace chunk path exceeds the maximal length allowed by the protocol");
3049 ret = -1;
3050 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
3051 goto end_unlock_session;
3052 }
3053
3054 if (session->current_trace_chunk == chunk) {
3055 /*
3056 * After a trace chunk close command, no new streams
3057 * referencing the chunk may be created. Hence, on the
3058 * event that no new trace chunk have been created for
3059 * the session, the reference to the current trace chunk
3060 * is released in order to allow it to be reclaimed when
3061 * the last stream releases its reference to it.
3062 */
3063 lttng_trace_chunk_put(session->current_trace_chunk);
3064 session->current_trace_chunk = NULL;
3065 }
3066 lttng_trace_chunk_put(session->pending_closure_trace_chunk);
3067 session->pending_closure_trace_chunk = NULL;
3068 end_unlock_session:
3069 pthread_mutex_unlock(&session->lock);
3070
3071 end:
3072 reply.generic.ret_code = htobe32((uint32_t) reply_code);
3073 reply.path_length = htobe32((uint32_t) path_length);
3074 buf_ret = lttng_dynamic_buffer_append(
3075 &reply_payload, &reply, sizeof(reply));
3076 if (buf_ret) {
3077 ERR("Failed to append \"close trace chunk\" command reply header to payload buffer");
3078 goto end_no_reply;
3079 }
3080
3081 if (reply_code == LTTNG_OK) {
3082 buf_ret = lttng_dynamic_buffer_append(&reply_payload,
3083 closed_trace_chunk_path, path_length);
3084 if (buf_ret) {
3085 ERR("Failed to append \"close trace chunk\" command reply path to payload buffer");
3086 goto end_no_reply;
3087 }
3088 }
3089
3090 send_ret = conn->sock->ops->sendmsg(conn->sock,
3091 reply_payload.data,
3092 reply_payload.size,
3093 0);
3094 if (send_ret < reply_payload.size) {
3095 ERR("Failed to send \"close trace chunk\" command reply of %zu bytes (ret = %zd)",
3096 reply_payload.size, send_ret);
3097 ret = -1;
3098 goto end_no_reply;
3099 }
3100 end_no_reply:
3101 lttng_trace_chunk_put(chunk);
3102 lttng_dynamic_buffer_reset(&reply_payload);
3103 return ret;
3104 }
3105
3106 /*
3107 * relay_trace_chunk_exists: check if a trace chunk exists
3108 */
3109 static int relay_trace_chunk_exists(const struct lttcomm_relayd_hdr *recv_hdr,
3110 struct relay_connection *conn,
3111 const struct lttng_buffer_view *payload)
3112 {
3113 int ret = 0;
3114 ssize_t send_ret;
3115 struct relay_session *session = conn->session;
3116 struct lttcomm_relayd_trace_chunk_exists *msg;
3117 struct lttcomm_relayd_trace_chunk_exists_reply reply = {};
3118 struct lttng_buffer_view header_view;
3119 uint64_t chunk_id;
3120 bool chunk_exists;
3121
3122 if (!session || !conn->version_check_done) {
3123 ERR("Trying to check for the presence of a trace chunk before version check");
3124 ret = -1;
3125 goto end_no_reply;
3126 }
3127
3128 if (session->major == 2 && session->minor < 11) {
3129 ERR("Chunk exists command is unsupported before 2.11");
3130 ret = -1;
3131 goto end_no_reply;
3132 }
3133
3134 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
3135 if (!lttng_buffer_view_is_valid(&header_view)) {
3136 ERR("Failed to receive payload of chunk exists command");
3137 ret = -1;
3138 goto end_no_reply;
3139 }
3140
3141 /* Convert to host endianness. */
3142 msg = (typeof(msg)) header_view.data;
3143 chunk_id = be64toh(msg->chunk_id);
3144
3145 ret = sessiond_trace_chunk_registry_chunk_exists(
3146 sessiond_trace_chunk_registry,
3147 conn->session->sessiond_uuid,
3148 conn->session->id,
3149 chunk_id, &chunk_exists);