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