Fix: relayd: live client not notified of inactive streams
[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/path.h>
52 #include <common/align.h>
53 #include <common/config/session-config.h>
54 #include <common/dynamic-buffer.h>
55 #include <common/buffer-view.h>
56 #include <common/string-utils/format.h>
57 #include <common/fd-tracker/fd-tracker.h>
58 #include <common/fd-tracker/utils.h>
59
60 #include "backward-compatibility-group-by.h"
61 #include "cmd.h"
62 #include "connection.h"
63 #include "ctf-trace.h"
64 #include "health-relayd.h"
65 #include "index.h"
66 #include "live.h"
67 #include "lttng-relayd.h"
68 #include "session.h"
69 #include "sessiond-trace-chunks.h"
70 #include "stream.h"
71 #include "tcp_keep_alive.h"
72 #include "testpoint.h"
73 #include "tracefile-array.h"
74 #include "utils.h"
75 #include "version.h"
76 #include "viewer-stream.h"
77
78 static const char *help_msg =
79 #ifdef LTTNG_EMBED_HELP
80 #include <lttng-relayd.8.h>
81 #else
82 NULL
83 #endif
84 ;
85
86 enum relay_connection_status {
87 RELAY_CONNECTION_STATUS_OK,
88 /* An error occurred while processing an event on the connection. */
89 RELAY_CONNECTION_STATUS_ERROR,
90 /* Connection closed/shutdown cleanly. */
91 RELAY_CONNECTION_STATUS_CLOSED,
92 };
93
94 /* command line options */
95 char *opt_output_path, *opt_working_directory;
96 static int opt_daemon, opt_background, opt_print_version, opt_allow_clear = 1;
97 enum relay_group_output_by opt_group_output_by = RELAYD_GROUP_OUTPUT_BY_UNKNOWN;
98
99 /*
100 * We need to wait for listener and live listener threads, as well as
101 * health check thread, before being ready to signal readiness.
102 */
103 #define NR_LTTNG_RELAY_READY 3
104 static int lttng_relay_ready = NR_LTTNG_RELAY_READY;
105
106 /* Size of receive buffer. */
107 #define RECV_DATA_BUFFER_SIZE 65536
108
109 static int recv_child_signal; /* Set to 1 when a SIGUSR1 signal is received. */
110 static pid_t child_ppid; /* Internal parent PID use with daemonize. */
111
112 static struct lttng_uri *control_uri;
113 static struct lttng_uri *data_uri;
114 static struct lttng_uri *live_uri;
115
116 const char *progname;
117
118 const char *tracing_group_name = DEFAULT_TRACING_GROUP;
119 static int tracing_group_name_override;
120
121 const char * const config_section_name = "relayd";
122
123 /*
124 * Quit pipe for all threads. This permits a single cancellation point
125 * for all threads when receiving an event on the pipe.
126 */
127 int thread_quit_pipe[2] = { -1, -1 };
128
129 /*
130 * This pipe is used to inform the worker thread that a command is queued and
131 * ready to be processed.
132 */
133 static int relay_conn_pipe[2] = { -1, -1 };
134
135 /* Shared between threads */
136 static int dispatch_thread_exit;
137
138 static pthread_t listener_thread;
139 static pthread_t dispatcher_thread;
140 static pthread_t worker_thread;
141 static pthread_t health_thread;
142
143 /*
144 * last_relay_stream_id_lock protects last_relay_stream_id increment
145 * atomicity on 32-bit architectures.
146 */
147 static pthread_mutex_t last_relay_stream_id_lock = PTHREAD_MUTEX_INITIALIZER;
148 static uint64_t last_relay_stream_id;
149
150 /*
151 * Relay command queue.
152 *
153 * The relay_thread_listener and relay_thread_dispatcher communicate with this
154 * queue.
155 */
156 static struct relay_conn_queue relay_conn_queue;
157
158 /* Cap of file desriptors to be in simultaneous use by the relay daemon. */
159 static unsigned int lttng_opt_fd_pool_size = -1;
160
161 /* Global relay stream hash table. */
162 struct lttng_ht *relay_streams_ht;
163
164 /* Global relay viewer stream hash table. */
165 struct lttng_ht *viewer_streams_ht;
166
167 /* Global relay sessions hash table. */
168 struct lttng_ht *sessions_ht;
169
170 /* Relayd health monitoring */
171 struct health_app *health_relayd;
172
173 struct sessiond_trace_chunk_registry *sessiond_trace_chunk_registry;
174
175 /* Global fd tracker. */
176 struct fd_tracker *the_fd_tracker;
177
178 static struct option long_options[] = {
179 { "control-port", 1, 0, 'C', },
180 { "data-port", 1, 0, 'D', },
181 { "live-port", 1, 0, 'L', },
182 { "daemonize", 0, 0, 'd', },
183 { "background", 0, 0, 'b', },
184 { "group", 1, 0, 'g', },
185 { "fd-pool-size", 1, 0, '\0', },
186 { "help", 0, 0, 'h', },
187 { "output", 1, 0, 'o', },
188 { "verbose", 0, 0, 'v', },
189 { "config", 1, 0, 'f' },
190 { "version", 0, 0, 'V' },
191 { "working-directory", 1, 0, 'w', },
192 { "group-output-by-session", 0, 0, 's', },
193 { "group-output-by-host", 0, 0, 'p', },
194 { "disallow-clear", 0, 0, 'x' },
195 { NULL, 0, 0, 0, },
196 };
197
198 static const char *config_ignore_options[] = { "help", "config", "version" };
199
200 static void print_version(void) {
201 fprintf(stdout, "%s\n", VERSION);
202 }
203
204 static void relayd_config_log(void)
205 {
206 DBG("LTTng-relayd " VERSION " - " VERSION_NAME "%s%s",
207 GIT_VERSION[0] == '\0' ? "" : " - " GIT_VERSION,
208 EXTRA_VERSION_NAME[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME);
209 if (EXTRA_VERSION_DESCRIPTION[0] != '\0') {
210 DBG("LTTng-relayd extra version description:\n\t" EXTRA_VERSION_DESCRIPTION "\n");
211 }
212 if (EXTRA_VERSION_PATCHES[0] != '\0') {
213 DBG("LTTng-relayd extra patches:\n\t" EXTRA_VERSION_PATCHES "\n");
214 }
215 }
216
217 /*
218 * Take an option from the getopt output and set it in the right variable to be
219 * used later.
220 *
221 * Return 0 on success else a negative value.
222 */
223 static int set_option(int opt, const char *arg, const char *optname)
224 {
225 int ret;
226
227 switch (opt) {
228 case 0:
229 if (!strcmp(optname, "fd-pool-size")) {
230 unsigned long v;
231
232 errno = 0;
233 v = strtoul(arg, NULL, 0);
234 if (errno != 0 || !isdigit((unsigned char) arg[0])) {
235 ERR("Wrong value in --fd-pool-size parameter: %s", arg);
236 ret = -1;
237 goto end;
238 }
239 if (v >= UINT_MAX) {
240 ERR("File descriptor cap overflow in --fd-pool-size parameter: %s", arg);
241 ret = -1;
242 goto end;
243 }
244 lttng_opt_fd_pool_size = (unsigned int) v;
245 } else {
246 fprintf(stderr, "unknown option %s", optname);
247 if (arg) {
248 fprintf(stderr, " with arg %s\n", arg);
249 }
250 }
251 break;
252 case 'C':
253 if (lttng_is_setuid_setgid()) {
254 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
255 "-C, --control-port");
256 } else {
257 ret = uri_parse(arg, &control_uri);
258 if (ret < 0) {
259 ERR("Invalid control URI specified");
260 goto end;
261 }
262 if (control_uri->port == 0) {
263 control_uri->port = DEFAULT_NETWORK_CONTROL_PORT;
264 }
265 }
266 break;
267 case 'D':
268 if (lttng_is_setuid_setgid()) {
269 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
270 "-D, -data-port");
271 } else {
272 ret = uri_parse(arg, &data_uri);
273 if (ret < 0) {
274 ERR("Invalid data URI specified");
275 goto end;
276 }
277 if (data_uri->port == 0) {
278 data_uri->port = DEFAULT_NETWORK_DATA_PORT;
279 }
280 }
281 break;
282 case 'L':
283 if (lttng_is_setuid_setgid()) {
284 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
285 "-L, -live-port");
286 } else {
287 ret = uri_parse(arg, &live_uri);
288 if (ret < 0) {
289 ERR("Invalid live URI specified");
290 goto end;
291 }
292 if (live_uri->port == 0) {
293 live_uri->port = DEFAULT_NETWORK_VIEWER_PORT;
294 }
295 }
296 break;
297 case 'd':
298 opt_daemon = 1;
299 break;
300 case 'b':
301 opt_background = 1;
302 break;
303 case 'g':
304 if (lttng_is_setuid_setgid()) {
305 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
306 "-g, --group");
307 } else {
308 tracing_group_name = strdup(arg);
309 if (tracing_group_name == NULL) {
310 ret = -errno;
311 PERROR("strdup");
312 goto end;
313 }
314 tracing_group_name_override = 1;
315 }
316 break;
317 case 'h':
318 ret = utils_show_help(8, "lttng-relayd", help_msg);
319 if (ret) {
320 ERR("Cannot show --help for `lttng-relayd`");
321 perror("exec");
322 }
323 exit(EXIT_FAILURE);
324 case 'V':
325 opt_print_version = 1;
326 break;
327 case 'o':
328 if (lttng_is_setuid_setgid()) {
329 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
330 "-o, --output");
331 } else {
332 ret = asprintf(&opt_output_path, "%s", arg);
333 if (ret < 0) {
334 ret = -errno;
335 PERROR("asprintf opt_output_path");
336 goto end;
337 }
338 }
339 break;
340 case 'w':
341 if (lttng_is_setuid_setgid()) {
342 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
343 "-w, --working-directory");
344 } else {
345 ret = asprintf(&opt_working_directory, "%s", arg);
346 if (ret < 0) {
347 ret = -errno;
348 PERROR("asprintf opt_working_directory");
349 goto end;
350 }
351 }
352 break;
353
354 case 'v':
355 /* Verbose level can increase using multiple -v */
356 if (arg) {
357 lttng_opt_verbose = config_parse_value(arg);
358 } else {
359 /* Only 3 level of verbosity (-vvv). */
360 if (lttng_opt_verbose < 3) {
361 lttng_opt_verbose += 1;
362 }
363 }
364 break;
365 case 's':
366 if (opt_group_output_by != RELAYD_GROUP_OUTPUT_BY_UNKNOWN) {
367 ERR("Cannot set --group-output-by-session, another --group-output-by argument is present");
368 exit(EXIT_FAILURE);
369 }
370 opt_group_output_by = RELAYD_GROUP_OUTPUT_BY_SESSION;
371 break;
372 case 'p':
373 if (opt_group_output_by != RELAYD_GROUP_OUTPUT_BY_UNKNOWN) {
374 ERR("Cannot set --group-output-by-host, another --group-output-by argument is present");
375 exit(EXIT_FAILURE);
376 }
377 opt_group_output_by = RELAYD_GROUP_OUTPUT_BY_HOST;
378 break;
379 case 'x':
380 /* Disallow clear */
381 opt_allow_clear = 0;
382 break;
383 default:
384 /* Unknown option or other error.
385 * Error is printed by getopt, just return */
386 ret = -1;
387 goto end;
388 }
389
390 /* All good. */
391 ret = 0;
392
393 end:
394 return ret;
395 }
396
397 /*
398 * config_entry_handler_cb used to handle options read from a config file.
399 * See config_entry_handler_cb comment in common/config/session-config.h for the
400 * return value conventions.
401 */
402 static int config_entry_handler(const struct config_entry *entry, void *unused)
403 {
404 int ret = 0, i;
405
406 if (!entry || !entry->name || !entry->value) {
407 ret = -EINVAL;
408 goto end;
409 }
410
411 /* Check if the option is to be ignored */
412 for (i = 0; i < sizeof(config_ignore_options) / sizeof(char *); i++) {
413 if (!strcmp(entry->name, config_ignore_options[i])) {
414 goto end;
415 }
416 }
417
418 for (i = 0; i < (sizeof(long_options) / sizeof(struct option)) - 1; i++) {
419 /* Ignore if entry name is not fully matched. */
420 if (strcmp(entry->name, long_options[i].name)) {
421 continue;
422 }
423
424 /*
425 * If the option takes no argument on the command line,
426 * we have to check if the value is "true". We support
427 * non-zero numeric values, true, on and yes.
428 */
429 if (!long_options[i].has_arg) {
430 ret = config_parse_value(entry->value);
431 if (ret <= 0) {
432 if (ret) {
433 WARN("Invalid configuration value \"%s\" for option %s",
434 entry->value, entry->name);
435 }
436 /* False, skip boolean config option. */
437 goto end;
438 }
439 }
440
441 ret = set_option(long_options[i].val, entry->value, entry->name);
442 goto end;
443 }
444
445 WARN("Unrecognized option \"%s\" in daemon configuration file.",
446 entry->name);
447
448 end:
449 return ret;
450 }
451
452 static int parse_env_options(void)
453 {
454 int ret = 0;
455 char *value = NULL;
456
457 value = lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV);
458 if (value) {
459 opt_working_directory = strdup(value);
460 if (!opt_working_directory) {
461 ERR("Failed to allocate working directory string (\"%s\")",
462 value);
463 ret = -1;
464 }
465 }
466 return ret;
467 }
468
469 static int set_fd_pool_size(void)
470 {
471 int ret = 0;
472 struct rlimit rlimit;
473
474 ret = getrlimit(RLIMIT_NOFILE, &rlimit);
475 if (ret) {
476 PERROR("Failed to get file descriptor limit");
477 ret = -1;
478 goto end;
479 }
480
481 DBG("File descriptor count limits are %" PRIu64 " (soft) and %" PRIu64 " (hard)",
482 (uint64_t) rlimit.rlim_cur,
483 (uint64_t) rlimit.rlim_max);
484 if (lttng_opt_fd_pool_size == -1) {
485 /* Use default value (soft limit - reserve). */
486 if (rlimit.rlim_cur < DEFAULT_RELAYD_MIN_FD_POOL_SIZE) {
487 ERR("The process' file number limit is too low (%" PRIu64 "). The process' file number limit must be set to at least %i.",
488 (uint64_t) rlimit.rlim_cur, DEFAULT_RELAYD_MIN_FD_POOL_SIZE);
489 ret = -1;
490 goto end;
491 }
492 lttng_opt_fd_pool_size = rlimit.rlim_cur -
493 DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE;
494 goto end;
495 }
496
497 if (lttng_opt_fd_pool_size < DEFAULT_RELAYD_MIN_FD_POOL_SIZE) {
498 ERR("File descriptor pool size must be set to at least %d",
499 DEFAULT_RELAYD_MIN_FD_POOL_SIZE);
500 ret = -1;
501 goto end;
502 }
503
504 if (lttng_opt_fd_pool_size > rlimit.rlim_cur) {
505 ERR("File descriptor pool size argument (%u) exceeds the process' soft limit (%" PRIu64 ").",
506 lttng_opt_fd_pool_size, (uint64_t) rlimit.rlim_cur);
507 ret = -1;
508 goto end;
509 }
510
511 DBG("File descriptor pool size argument (%u) adjusted to %u to accommodates transient fd uses",
512 lttng_opt_fd_pool_size,
513 lttng_opt_fd_pool_size - DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE);
514 lttng_opt_fd_pool_size -= DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE;
515 end:
516 return ret;
517 }
518
519 static int set_options(int argc, char **argv)
520 {
521 int c, ret = 0, option_index = 0, retval = 0;
522 int orig_optopt = optopt, orig_optind = optind;
523 char *default_address, *optstring;
524 const char *config_path = NULL;
525
526 optstring = utils_generate_optstring(long_options,
527 sizeof(long_options) / sizeof(struct option));
528 if (!optstring) {
529 retval = -ENOMEM;
530 goto exit;
531 }
532
533 /* Check for the --config option */
534
535 while ((c = getopt_long(argc, argv, optstring, long_options,
536 &option_index)) != -1) {
537 if (c == '?') {
538 retval = -EINVAL;
539 goto exit;
540 } else if (c != 'f') {
541 continue;
542 }
543
544 if (lttng_is_setuid_setgid()) {
545 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
546 "-f, --config");
547 } else {
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(optstring);
661 return retval;
662 }
663
664 static void print_global_objects(void)
665 {
666 print_viewer_streams();
667 print_relay_streams();
668 print_sessions();
669 }
670
671 static int noop_close(void *data, int *fds)
672 {
673 return 0;
674 }
675
676 static void untrack_stdio(void)
677 {
678 int fds[] = { fileno(stdout), fileno(stderr) };
679
680 /*
681 * noop_close is used since we don't really want to close
682 * the stdio output fds; we merely want to stop tracking them.
683 */
684 (void) fd_tracker_close_unsuspendable_fd(the_fd_tracker,
685 fds, 2, noop_close, NULL);
686 }
687
688 /*
689 * Cleanup the daemon
690 */
691 static void relayd_cleanup(void)
692 {
693 print_global_objects();
694
695 DBG("Cleaning up");
696
697 if (viewer_streams_ht)
698 lttng_ht_destroy(viewer_streams_ht);
699 if (relay_streams_ht)
700 lttng_ht_destroy(relay_streams_ht);
701 if (sessions_ht)
702 lttng_ht_destroy(sessions_ht);
703
704 free(opt_output_path);
705 free(opt_working_directory);
706
707 if (health_relayd) {
708 health_app_destroy(health_relayd);
709 }
710 /* Close thread quit pipes */
711 if (health_quit_pipe[0] != -1) {
712 (void) fd_tracker_util_pipe_close(
713 the_fd_tracker, health_quit_pipe);
714 }
715 if (thread_quit_pipe[0] != -1) {
716 (void) fd_tracker_util_pipe_close(
717 the_fd_tracker, thread_quit_pipe);
718 }
719 if (sessiond_trace_chunk_registry) {
720 sessiond_trace_chunk_registry_destroy(
721 sessiond_trace_chunk_registry);
722 }
723 if (the_fd_tracker) {
724 untrack_stdio();
725 /*
726 * fd_tracker_destroy() will log the contents of the fd-tracker
727 * if a leak is detected.
728 */
729 fd_tracker_destroy(the_fd_tracker);
730 }
731
732 uri_free(control_uri);
733 uri_free(data_uri);
734 /* Live URI is freed in the live thread. */
735
736 if (tracing_group_name_override) {
737 free((void *) tracing_group_name);
738 }
739 }
740
741 /*
742 * Write to writable pipe used to notify a thread.
743 */
744 static int notify_thread_pipe(int wpipe)
745 {
746 ssize_t ret;
747
748 ret = lttng_write(wpipe, "!", 1);
749 if (ret < 1) {
750 PERROR("write poll pipe");
751 goto end;
752 }
753 ret = 0;
754 end:
755 return ret;
756 }
757
758 static int notify_health_quit_pipe(int *pipe)
759 {
760 ssize_t ret;
761
762 ret = lttng_write(pipe[1], "4", 1);
763 if (ret < 1) {
764 PERROR("write relay health quit");
765 goto end;
766 }
767 ret = 0;
768 end:
769 return ret;
770 }
771
772 /*
773 * Stop all relayd and relayd-live threads.
774 */
775 int lttng_relay_stop_threads(void)
776 {
777 int retval = 0;
778
779 /* Stopping all threads */
780 DBG("Terminating all threads");
781 if (notify_thread_pipe(thread_quit_pipe[1])) {
782 ERR("write error on thread quit pipe");
783 retval = -1;
784 }
785
786 if (notify_health_quit_pipe(health_quit_pipe)) {
787 ERR("write error on health quit pipe");
788 }
789
790 /* Dispatch thread */
791 CMM_STORE_SHARED(dispatch_thread_exit, 1);
792 futex_nto1_wake(&relay_conn_queue.futex);
793
794 if (relayd_live_stop()) {
795 ERR("Error stopping live threads");
796 retval = -1;
797 }
798 return retval;
799 }
800
801 /*
802 * Signal handler for the daemon
803 *
804 * Simply stop all worker threads, leaving main() return gracefully after
805 * joining all threads and calling cleanup().
806 */
807 static void sighandler(int sig)
808 {
809 switch (sig) {
810 case SIGINT:
811 DBG("SIGINT caught");
812 if (lttng_relay_stop_threads()) {
813 ERR("Error stopping threads");
814 }
815 break;
816 case SIGTERM:
817 DBG("SIGTERM caught");
818 if (lttng_relay_stop_threads()) {
819 ERR("Error stopping threads");
820 }
821 break;
822 case SIGUSR1:
823 CMM_STORE_SHARED(recv_child_signal, 1);
824 break;
825 default:
826 break;
827 }
828 }
829
830 /*
831 * Setup signal handler for :
832 * SIGINT, SIGTERM, SIGPIPE
833 */
834 static int set_signal_handler(void)
835 {
836 int ret = 0;
837 struct sigaction sa;
838 sigset_t sigset;
839
840 if ((ret = sigemptyset(&sigset)) < 0) {
841 PERROR("sigemptyset");
842 return ret;
843 }
844
845 sa.sa_mask = sigset;
846 sa.sa_flags = 0;
847
848 sa.sa_handler = sighandler;
849 if ((ret = sigaction(SIGTERM, &sa, NULL)) < 0) {
850 PERROR("sigaction");
851 return ret;
852 }
853
854 if ((ret = sigaction(SIGINT, &sa, NULL)) < 0) {
855 PERROR("sigaction");
856 return ret;
857 }
858
859 if ((ret = sigaction(SIGUSR1, &sa, NULL)) < 0) {
860 PERROR("sigaction");
861 return ret;
862 }
863
864 sa.sa_handler = SIG_IGN;
865 if ((ret = sigaction(SIGPIPE, &sa, NULL)) < 0) {
866 PERROR("sigaction");
867 return ret;
868 }
869
870 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
871
872 return ret;
873 }
874
875 void lttng_relay_notify_ready(void)
876 {
877 /* Notify the parent of the fork() process that we are ready. */
878 if (opt_daemon || opt_background) {
879 if (uatomic_sub_return(&lttng_relay_ready, 1) == 0) {
880 kill(child_ppid, SIGUSR1);
881 }
882 }
883 }
884
885 /*
886 * Init thread quit pipe.
887 *
888 * Return -1 on error or 0 if all pipes are created.
889 */
890 static int init_thread_quit_pipe(void)
891 {
892 return fd_tracker_util_pipe_open_cloexec(
893 the_fd_tracker, "Quit pipe", thread_quit_pipe);
894 }
895
896 /*
897 * Init health quit pipe.
898 *
899 * Return -1 on error or 0 if all pipes are created.
900 */
901 static int init_health_quit_pipe(void)
902 {
903 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker,
904 "Health quit pipe", health_quit_pipe);
905 }
906
907 /*
908 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
909 */
910 static int create_named_thread_poll_set(struct lttng_poll_event *events,
911 int size, const char *name)
912 {
913 int ret;
914
915 if (events == NULL || size == 0) {
916 ret = -1;
917 goto error;
918 }
919
920 ret = fd_tracker_util_poll_create(the_fd_tracker,
921 name, events, 1, LTTNG_CLOEXEC);
922 if (ret) {
923 PERROR("Failed to create \"%s\" poll file descriptor", name);
924 goto error;
925 }
926
927 /* Add quit pipe */
928 ret = lttng_poll_add(events, thread_quit_pipe[0], LPOLLIN | LPOLLERR);
929 if (ret < 0) {
930 goto error;
931 }
932
933 return 0;
934
935 error:
936 return ret;
937 }
938
939 /*
940 * Check if the thread quit pipe was triggered.
941 *
942 * Return 1 if it was triggered else 0;
943 */
944 static int check_thread_quit_pipe(int fd, uint32_t events)
945 {
946 if (fd == thread_quit_pipe[0] && (events & LPOLLIN)) {
947 return 1;
948 }
949
950 return 0;
951 }
952
953 static int create_sock(void *data, int *out_fd)
954 {
955 int ret;
956 struct lttcomm_sock *sock = data;
957
958 ret = lttcomm_create_sock(sock);
959 if (ret < 0) {
960 goto end;
961 }
962
963 *out_fd = sock->fd;
964 end:
965 return ret;
966 }
967
968 static int close_sock(void *data, int *in_fd)
969 {
970 struct lttcomm_sock *sock = data;
971
972 return sock->ops->close(sock);
973 }
974
975 static int accept_sock(void *data, int *out_fd)
976 {
977 int ret = 0;
978 /* Socks is an array of in_sock, out_sock. */
979 struct lttcomm_sock **socks = data;
980 struct lttcomm_sock *in_sock = socks[0];
981
982 socks[1] = in_sock->ops->accept(in_sock);
983 if (!socks[1]) {
984 ret = -1;
985 goto end;
986 }
987 *out_fd = socks[1]->fd;
988 end:
989 return ret;
990 }
991
992 /*
993 * Create and init socket from uri.
994 */
995 static struct lttcomm_sock *relay_socket_create(struct lttng_uri *uri,
996 const char *name)
997 {
998 int ret, sock_fd;
999 struct lttcomm_sock *sock = NULL;
1000 char uri_str[PATH_MAX];
1001 char *formated_name = NULL;
1002
1003 sock = lttcomm_alloc_sock_from_uri(uri);
1004 if (sock == NULL) {
1005 ERR("Allocating socket");
1006 goto error;
1007 }
1008
1009 /*
1010 * Don't fail to create the socket if the name can't be built as it is
1011 * only used for debugging purposes.
1012 */
1013 ret = uri_to_str_url(uri, uri_str, sizeof(uri_str));
1014 uri_str[sizeof(uri_str) - 1] = '\0';
1015 if (ret >= 0) {
1016 ret = asprintf(&formated_name, "%s socket @ %s", name,
1017 uri_str);
1018 if (ret < 0) {
1019 formated_name = NULL;
1020 }
1021 }
1022
1023 ret = fd_tracker_open_unsuspendable_fd(the_fd_tracker, &sock_fd,
1024 (const char **) (formated_name ? &formated_name : NULL),
1025 1, create_sock, sock);
1026 if (ret) {
1027 PERROR("Failed to open \"%s\" relay socket",
1028 formated_name ?: "Unknown");
1029 goto error;
1030 }
1031 DBG("Listening on %s socket %d", name, sock->fd);
1032
1033 ret = sock->ops->bind(sock);
1034 if (ret < 0) {
1035 PERROR("Failed to bind socket");
1036 goto error;
1037 }
1038
1039 ret = sock->ops->listen(sock, -1);
1040 if (ret < 0) {
1041 goto error;
1042
1043 }
1044
1045 free(formated_name);
1046 return sock;
1047
1048 error:
1049 if (sock) {
1050 lttcomm_destroy_sock(sock);
1051 }
1052 free(formated_name);
1053 return NULL;
1054 }
1055
1056 static
1057 struct lttcomm_sock *accept_relayd_sock(struct lttcomm_sock *listening_sock,
1058 const char *name)
1059 {
1060 int out_fd, ret;
1061 struct lttcomm_sock *socks[2] = { listening_sock, NULL };
1062 struct lttcomm_sock *new_sock = NULL;
1063
1064 ret = fd_tracker_open_unsuspendable_fd(
1065 the_fd_tracker, &out_fd,
1066 (const char **) &name,
1067 1, accept_sock, &socks);
1068 if (ret) {
1069 goto end;
1070 }
1071 new_sock = socks[1];
1072 DBG("%s accepted, socket %d", name, new_sock->fd);
1073 end:
1074 return new_sock;
1075 }
1076
1077 /*
1078 * This thread manages the listening for new connections on the network
1079 */
1080 static void *relay_thread_listener(void *data)
1081 {
1082 int i, ret, pollfd, err = -1;
1083 uint32_t revents, nb_fd;
1084 struct lttng_poll_event events;
1085 struct lttcomm_sock *control_sock, *data_sock;
1086
1087 DBG("[thread] Relay listener started");
1088
1089 rcu_register_thread();
1090 health_register(health_relayd, HEALTH_RELAYD_TYPE_LISTENER);
1091
1092 health_code_update();
1093
1094 control_sock = relay_socket_create(control_uri, "Control listener");
1095 if (!control_sock) {
1096 goto error_sock_control;
1097 }
1098
1099 data_sock = relay_socket_create(data_uri, "Data listener");
1100 if (!data_sock) {
1101 goto error_sock_relay;
1102 }
1103
1104 /*
1105 * Pass 3 as size here for the thread quit pipe, control and
1106 * data socket.
1107 */
1108 ret = create_named_thread_poll_set(&events, 3, "Listener thread epoll");
1109 if (ret < 0) {
1110 goto error_create_poll;
1111 }
1112
1113 /* Add the control socket */
1114 ret = lttng_poll_add(&events, control_sock->fd, LPOLLIN | LPOLLRDHUP);
1115 if (ret < 0) {
1116 goto error_poll_add;
1117 }
1118
1119 /* Add the data socket */
1120 ret = lttng_poll_add(&events, data_sock->fd, LPOLLIN | LPOLLRDHUP);
1121 if (ret < 0) {
1122 goto error_poll_add;
1123 }
1124
1125 lttng_relay_notify_ready();
1126
1127 if (testpoint(relayd_thread_listener)) {
1128 goto error_testpoint;
1129 }
1130
1131 while (1) {
1132 health_code_update();
1133
1134 DBG("Listener accepting connections");
1135
1136 restart:
1137 health_poll_entry();
1138 ret = lttng_poll_wait(&events, -1);
1139 health_poll_exit();
1140 if (ret < 0) {
1141 /*
1142 * Restart interrupted system call.
1143 */
1144 if (errno == EINTR) {
1145 goto restart;
1146 }
1147 goto error;
1148 }
1149
1150 nb_fd = ret;
1151
1152 DBG("Relay new connection received");
1153 for (i = 0; i < nb_fd; i++) {
1154 health_code_update();
1155
1156 /* Fetch once the poll data */
1157 revents = LTTNG_POLL_GETEV(&events, i);
1158 pollfd = LTTNG_POLL_GETFD(&events, i);
1159
1160 /* Thread quit pipe has been closed. Killing thread. */
1161 ret = check_thread_quit_pipe(pollfd, revents);
1162 if (ret) {
1163 err = 0;
1164 goto exit;
1165 }
1166
1167 if (revents & LPOLLIN) {
1168 /*
1169 * A new connection is requested, therefore a
1170 * sessiond/consumerd connection is allocated in
1171 * this thread, enqueued to a global queue and
1172 * dequeued (and freed) in the worker thread.
1173 */
1174 int val = 1;
1175 struct relay_connection *new_conn;
1176 struct lttcomm_sock *newsock = NULL;
1177 enum connection_type type;
1178
1179 if (pollfd == data_sock->fd) {
1180 type = RELAY_DATA;
1181 newsock = accept_relayd_sock(data_sock,
1182 "Data socket to relayd");
1183 } else {
1184 assert(pollfd == control_sock->fd);
1185 type = RELAY_CONTROL;
1186 newsock = accept_relayd_sock(control_sock,
1187 "Control socket to relayd");
1188 }
1189 if (!newsock) {
1190 PERROR("accepting sock");
1191 goto error;
1192 }
1193
1194 ret = setsockopt(newsock->fd, SOL_SOCKET, SO_REUSEADDR, &val,
1195 sizeof(val));
1196 if (ret < 0) {
1197 PERROR("setsockopt inet");
1198 lttcomm_destroy_sock(newsock);
1199 goto error;
1200 }
1201
1202 ret = socket_apply_keep_alive_config(newsock->fd);
1203 if (ret < 0) {
1204 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
1205 newsock->fd);
1206 lttcomm_destroy_sock(newsock);
1207 goto error;
1208 }
1209
1210 new_conn = connection_create(newsock, type);
1211 if (!new_conn) {
1212 lttcomm_destroy_sock(newsock);
1213 goto error;
1214 }
1215
1216 /* Enqueue request for the dispatcher thread. */
1217 cds_wfcq_enqueue(&relay_conn_queue.head, &relay_conn_queue.tail,
1218 &new_conn->qnode);
1219
1220 /*
1221 * Wake the dispatch queue futex.
1222 * Implicit memory barrier with the
1223 * exchange in cds_wfcq_enqueue.
1224 */
1225 futex_nto1_wake(&relay_conn_queue.futex);
1226 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
1227 ERR("socket poll error");
1228 goto error;
1229 } else {
1230 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
1231 goto error;
1232 }
1233 }
1234 }
1235
1236 exit:
1237 error:
1238 error_poll_add:
1239 error_testpoint:
1240 (void) fd_tracker_util_poll_clean(the_fd_tracker, &events);
1241 error_create_poll:
1242 if (data_sock->fd >= 0) {
1243 int data_sock_fd = data_sock->fd;
1244
1245 ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker,
1246 &data_sock_fd, 1, close_sock,
1247 data_sock);
1248 if (ret) {
1249 PERROR("Failed to close the data listener socket file descriptor");
1250 }
1251 data_sock->fd = -1;
1252 }
1253 lttcomm_destroy_sock(data_sock);
1254 error_sock_relay:
1255 if (control_sock->fd >= 0) {
1256 int control_sock_fd = control_sock->fd;
1257
1258 ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker,
1259 &control_sock_fd, 1, close_sock,
1260 control_sock);
1261 if (ret) {
1262 PERROR("Failed to close the control listener socket file descriptor");
1263 }
1264 control_sock->fd = -1;
1265 }
1266 lttcomm_destroy_sock(control_sock);
1267 error_sock_control:
1268 if (err) {
1269 health_error();
1270 ERR("Health error occurred in %s", __func__);
1271 }
1272 health_unregister(health_relayd);
1273 rcu_unregister_thread();
1274 DBG("Relay listener thread cleanup complete");
1275 lttng_relay_stop_threads();
1276 return NULL;
1277 }
1278
1279 /*
1280 * This thread manages the dispatching of the requests to worker threads
1281 */
1282 static void *relay_thread_dispatcher(void *data)
1283 {
1284 int err = -1;
1285 ssize_t ret;
1286 struct cds_wfcq_node *node;
1287 struct relay_connection *new_conn = NULL;
1288
1289 DBG("[thread] Relay dispatcher started");
1290
1291 health_register(health_relayd, HEALTH_RELAYD_TYPE_DISPATCHER);
1292
1293 if (testpoint(relayd_thread_dispatcher)) {
1294 goto error_testpoint;
1295 }
1296
1297 health_code_update();
1298
1299 for (;;) {
1300 health_code_update();
1301
1302 /* Atomically prepare the queue futex */
1303 futex_nto1_prepare(&relay_conn_queue.futex);
1304
1305 if (CMM_LOAD_SHARED(dispatch_thread_exit)) {
1306 break;
1307 }
1308
1309 do {
1310 health_code_update();
1311
1312 /* Dequeue commands */
1313 node = cds_wfcq_dequeue_blocking(&relay_conn_queue.head,
1314 &relay_conn_queue.tail);
1315 if (node == NULL) {
1316 DBG("Woken up but nothing in the relay command queue");
1317 /* Continue thread execution */
1318 break;
1319 }
1320 new_conn = caa_container_of(node, struct relay_connection, qnode);
1321
1322 DBG("Dispatching request waiting on sock %d", new_conn->sock->fd);
1323
1324 /*
1325 * Inform worker thread of the new request. This
1326 * call is blocking so we can be assured that
1327 * the data will be read at some point in time
1328 * or wait to the end of the world :)
1329 */
1330 ret = lttng_write(relay_conn_pipe[1], &new_conn, sizeof(new_conn));
1331 if (ret < 0) {
1332 PERROR("write connection pipe");
1333 connection_put(new_conn);
1334 goto error;
1335 }
1336 } while (node != NULL);
1337
1338 /* Futex wait on queue. Blocking call on futex() */
1339 health_poll_entry();
1340 futex_nto1_wait(&relay_conn_queue.futex);
1341 health_poll_exit();
1342 }
1343
1344 /* Normal exit, no error */
1345 err = 0;
1346
1347 error:
1348 error_testpoint:
1349 if (err) {
1350 health_error();
1351 ERR("Health error occurred in %s", __func__);
1352 }
1353 health_unregister(health_relayd);
1354 DBG("Dispatch thread dying");
1355 lttng_relay_stop_threads();
1356 return NULL;
1357 }
1358
1359 static bool session_streams_have_index(const struct relay_session *session)
1360 {
1361 return session->minor >= 4 && !session->snapshot;
1362 }
1363
1364 /*
1365 * Handle the RELAYD_CREATE_SESSION command.
1366 *
1367 * On success, send back the session id or else return a negative value.
1368 */
1369 static int relay_create_session(const struct lttcomm_relayd_hdr *recv_hdr,
1370 struct relay_connection *conn,
1371 const struct lttng_buffer_view *payload)
1372 {
1373 int ret = 0;
1374 ssize_t send_ret;
1375 struct relay_session *session = NULL;
1376 struct lttcomm_relayd_create_session_reply_2_11 reply = {};
1377 char session_name[LTTNG_NAME_MAX] = {};
1378 char hostname[LTTNG_HOST_NAME_MAX] = {};
1379 uint32_t live_timer = 0;
1380 bool snapshot = false;
1381 bool session_name_contains_creation_timestamp = false;
1382 /* Left nil for peers < 2.11. */
1383 char base_path[LTTNG_PATH_MAX] = {};
1384 lttng_uuid sessiond_uuid = {};
1385 LTTNG_OPTIONAL(uint64_t) id_sessiond = {};
1386 LTTNG_OPTIONAL(uint64_t) current_chunk_id = {};
1387 LTTNG_OPTIONAL(time_t) creation_time = {};
1388 struct lttng_dynamic_buffer reply_payload;
1389
1390 lttng_dynamic_buffer_init(&reply_payload);
1391
1392 if (conn->minor < 4) {
1393 /* From 2.1 to 2.3 */
1394 ret = 0;
1395 } else if (conn->minor >= 4 && conn->minor < 11) {
1396 /* From 2.4 to 2.10 */
1397 ret = cmd_create_session_2_4(payload, session_name,
1398 hostname, &live_timer, &snapshot);
1399 } else {
1400 bool has_current_chunk;
1401 uint64_t current_chunk_id_value;
1402 time_t creation_time_value;
1403 uint64_t id_sessiond_value;
1404
1405 /* From 2.11 to ... */
1406 ret = cmd_create_session_2_11(payload, session_name, hostname,
1407 base_path, &live_timer, &snapshot, &id_sessiond_value,
1408 sessiond_uuid, &has_current_chunk,
1409 &current_chunk_id_value, &creation_time_value,
1410 &session_name_contains_creation_timestamp);
1411 if (lttng_uuid_is_nil(sessiond_uuid)) {
1412 /* The nil UUID is reserved for pre-2.11 clients. */
1413 ERR("Illegal nil UUID announced by peer in create session command");
1414 ret = -1;
1415 goto send_reply;
1416 }
1417 LTTNG_OPTIONAL_SET(&id_sessiond, id_sessiond_value);
1418 LTTNG_OPTIONAL_SET(&creation_time, creation_time_value);
1419 if (has_current_chunk) {
1420 LTTNG_OPTIONAL_SET(&current_chunk_id,
1421 current_chunk_id_value);
1422 }
1423 }
1424
1425 if (ret < 0) {
1426 goto send_reply;
1427 }
1428
1429 session = session_create(session_name, hostname, base_path, live_timer,
1430 snapshot, sessiond_uuid,
1431 id_sessiond.is_set ? &id_sessiond.value : NULL,
1432 current_chunk_id.is_set ? &current_chunk_id.value : NULL,
1433 creation_time.is_set ? &creation_time.value : NULL,
1434 conn->major, conn->minor,
1435 session_name_contains_creation_timestamp);
1436 if (!session) {
1437 ret = -1;
1438 goto send_reply;
1439 }
1440 assert(!conn->session);
1441 conn->session = session;
1442 DBG("Created session %" PRIu64, session->id);
1443
1444 reply.generic.session_id = htobe64(session->id);
1445
1446 send_reply:
1447 if (ret < 0) {
1448 reply.generic.ret_code = htobe32(LTTNG_ERR_FATAL);
1449 } else {
1450 reply.generic.ret_code = htobe32(LTTNG_OK);
1451 }
1452
1453 if (conn->minor < 11) {
1454 /* From 2.1 to 2.10 */
1455 ret = lttng_dynamic_buffer_append(&reply_payload,
1456 &reply.generic, sizeof(reply.generic));
1457 if (ret) {
1458 ERR("Failed to append \"create session\" command reply header to payload buffer");
1459 ret = -1;
1460 goto end;
1461 }
1462 } else {
1463 const uint32_t output_path_length =
1464 session ? strlen(session->output_path) + 1 : 0;
1465
1466 reply.output_path_length = htobe32(output_path_length);
1467 ret = lttng_dynamic_buffer_append(
1468 &reply_payload, &reply, sizeof(reply));
1469 if (ret) {
1470 ERR("Failed to append \"create session\" command reply header to payload buffer");
1471 goto end;
1472 }
1473
1474 if (output_path_length) {
1475 ret = lttng_dynamic_buffer_append(&reply_payload,
1476 session->output_path,
1477 output_path_length);
1478 if (ret) {
1479 ERR("Failed to append \"create session\" command reply path to payload buffer");
1480 goto end;
1481 }
1482 }
1483 }
1484
1485 send_ret = conn->sock->ops->sendmsg(conn->sock, reply_payload.data,
1486 reply_payload.size, 0);
1487 if (send_ret < (ssize_t) reply_payload.size) {
1488 ERR("Failed to send \"create session\" command reply of %zu bytes (ret = %zd)",
1489 reply_payload.size, send_ret);
1490 ret = -1;
1491 }
1492 end:
1493 if (ret < 0 && session) {
1494 session_put(session);
1495 }
1496 lttng_dynamic_buffer_reset(&reply_payload);
1497 return ret;
1498 }
1499
1500 /*
1501 * When we have received all the streams and the metadata for a channel,
1502 * we make them visible to the viewer threads.
1503 */
1504 static void publish_connection_local_streams(struct relay_connection *conn)
1505 {
1506 struct relay_stream *stream;
1507 struct relay_session *session = conn->session;
1508
1509 /*
1510 * We publish all streams belonging to a session atomically wrt
1511 * session lock.
1512 */
1513 pthread_mutex_lock(&session->lock);
1514 rcu_read_lock();
1515 cds_list_for_each_entry_rcu(stream, &session->recv_list,
1516 recv_node) {
1517 stream_publish(stream);
1518 }
1519 rcu_read_unlock();
1520
1521 /*
1522 * Inform the viewer that there are new streams in the session.
1523 */
1524 if (session->viewer_attached) {
1525 uatomic_set(&session->new_streams, 1);
1526 }
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 (!packet_view.data) {
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_buffer_view chunk_name_view;
2763 struct lttng_trace_chunk *chunk = NULL, *published_chunk = NULL;
2764 enum lttng_error_code reply_code = LTTNG_OK;
2765 enum lttng_trace_chunk_status chunk_status;
2766 const char *new_path;
2767
2768 if (!session || !conn->version_check_done) {
2769 ERR("Trying to create a trace chunk before version check");
2770 ret = -1;
2771 goto end_no_reply;
2772 }
2773
2774 if (session->major == 2 && session->minor < 11) {
2775 ERR("Chunk creation command is unsupported before 2.11");
2776 ret = -1;
2777 goto end_no_reply;
2778 }
2779
2780 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
2781 if (!header_view.data) {
2782 ERR("Failed to receive payload of chunk creation command");
2783 ret = -1;
2784 goto end_no_reply;
2785 }
2786
2787 /* Convert to host endianness. */
2788 msg = (typeof(msg)) header_view.data;
2789 msg->chunk_id = be64toh(msg->chunk_id);
2790 msg->creation_timestamp = be64toh(msg->creation_timestamp);
2791 msg->override_name_length = be32toh(msg->override_name_length);
2792
2793 pthread_mutex_lock(&conn->session->lock);
2794 session->ongoing_rotation = true;
2795 if (session->current_trace_chunk &&
2796 !lttng_trace_chunk_get_name_overridden(session->current_trace_chunk)) {
2797 chunk_status = lttng_trace_chunk_rename_path(session->current_trace_chunk,
2798 DEFAULT_CHUNK_TMP_OLD_DIRECTORY);
2799 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2800 ERR("Failed to rename old chunk");
2801 ret = -1;
2802 reply_code = LTTNG_ERR_UNK;
2803 goto end;
2804 }
2805 }
2806 if (!session->current_trace_chunk) {
2807 if (!session->has_rotated) {
2808 new_path = "";
2809 } else {
2810 new_path = NULL;
2811 }
2812 } else {
2813 new_path = DEFAULT_CHUNK_TMP_NEW_DIRECTORY;
2814 }
2815 chunk = lttng_trace_chunk_create(
2816 msg->chunk_id, msg->creation_timestamp, new_path);
2817 if (!chunk) {
2818 ERR("Failed to create trace chunk in trace chunk creation command");
2819 ret = -1;
2820 reply_code = LTTNG_ERR_NOMEM;
2821 goto end;
2822 }
2823 lttng_trace_chunk_set_fd_tracker(chunk, the_fd_tracker);
2824
2825 if (msg->override_name_length) {
2826 const char *name;
2827
2828 chunk_name_view = lttng_buffer_view_from_view(payload,
2829 sizeof(*msg),
2830 msg->override_name_length);
2831 name = chunk_name_view.data;
2832 if (!name || name[msg->override_name_length - 1]) {
2833 ERR("Failed to receive payload of chunk creation command");
2834 ret = -1;
2835 reply_code = LTTNG_ERR_INVALID;
2836 goto end;
2837 }
2838
2839 chunk_status = lttng_trace_chunk_override_name(
2840 chunk, chunk_name_view.data);
2841 switch (chunk_status) {
2842 case LTTNG_TRACE_CHUNK_STATUS_OK:
2843 break;
2844 case LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT:
2845 ERR("Failed to set the name of new trace chunk in trace chunk creation command (invalid name)");
2846 reply_code = LTTNG_ERR_INVALID;
2847 ret = -1;
2848 goto end;
2849 default:
2850 ERR("Failed to set the name of new trace chunk in trace chunk creation command (unknown error)");
2851 reply_code = LTTNG_ERR_UNK;
2852 ret = -1;
2853 goto end;
2854 }
2855 }
2856
2857 chunk_status = lttng_trace_chunk_set_credentials_current_user(chunk);
2858 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2859 reply_code = LTTNG_ERR_UNK;
2860 ret = -1;
2861 goto end;
2862 }
2863
2864 assert(conn->session->output_directory);
2865 chunk_status = lttng_trace_chunk_set_as_owner(chunk,
2866 conn->session->output_directory);
2867 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2868 reply_code = LTTNG_ERR_UNK;
2869 ret = -1;
2870 goto end;
2871 }
2872
2873 published_chunk = sessiond_trace_chunk_registry_publish_chunk(
2874 sessiond_trace_chunk_registry,
2875 conn->session->sessiond_uuid,
2876 conn->session->id_sessiond.is_set ?
2877 conn->session->id_sessiond.value :
2878 conn->session->id,
2879 chunk);
2880 if (!published_chunk) {
2881 char uuid_str[LTTNG_UUID_STR_LEN];
2882
2883 lttng_uuid_to_str(conn->session->sessiond_uuid, uuid_str);
2884 ERR("Failed to publish chunk: sessiond_uuid = %s, session_id = %" PRIu64 ", chunk_id = %" PRIu64,
2885 uuid_str,
2886 conn->session->id,
2887 msg->chunk_id);
2888 ret = -1;
2889 reply_code = LTTNG_ERR_NOMEM;
2890 goto end;
2891 }
2892
2893 if (conn->session->pending_closure_trace_chunk) {
2894 /*
2895 * Invalid; this means a second create_trace_chunk command was
2896 * received before a close_trace_chunk.
2897 */
2898 ERR("Invalid trace chunk close command received; a trace chunk is already waiting for a trace chunk close command");
2899 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2900 ret = -1;
2901 goto end;
2902 }
2903 conn->session->pending_closure_trace_chunk =
2904 conn->session->current_trace_chunk;
2905 conn->session->current_trace_chunk = published_chunk;
2906 published_chunk = NULL;
2907 if (!conn->session->pending_closure_trace_chunk) {
2908 session->ongoing_rotation = false;
2909 }
2910 end:
2911 pthread_mutex_unlock(&conn->session->lock);
2912 reply.ret_code = htobe32((uint32_t) reply_code);
2913 send_ret = conn->sock->ops->sendmsg(conn->sock,
2914 &reply,
2915 sizeof(struct lttcomm_relayd_generic_reply),
2916 0);
2917 if (send_ret < (ssize_t) sizeof(reply)) {
2918 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
2919 send_ret);
2920 ret = -1;
2921 }
2922 end_no_reply:
2923 lttng_trace_chunk_put(chunk);
2924 lttng_trace_chunk_put(published_chunk);
2925 return ret;
2926 }
2927
2928 /*
2929 * relay_close_trace_chunk: close a trace chunk
2930 */
2931 static int relay_close_trace_chunk(const struct lttcomm_relayd_hdr *recv_hdr,
2932 struct relay_connection *conn,
2933 const struct lttng_buffer_view *payload)
2934 {
2935 int ret = 0, buf_ret;
2936 ssize_t send_ret;
2937 struct relay_session *session = conn->session;
2938 struct lttcomm_relayd_close_trace_chunk *msg;
2939 struct lttcomm_relayd_close_trace_chunk_reply reply = {};
2940 struct lttng_buffer_view header_view;
2941 struct lttng_trace_chunk *chunk = NULL;
2942 enum lttng_error_code reply_code = LTTNG_OK;
2943 enum lttng_trace_chunk_status chunk_status;
2944 uint64_t chunk_id;
2945 LTTNG_OPTIONAL(enum lttng_trace_chunk_command_type) close_command = {};
2946 time_t close_timestamp;
2947 char closed_trace_chunk_path[LTTNG_PATH_MAX];
2948 size_t path_length = 0;
2949 const char *chunk_name = NULL;
2950 struct lttng_dynamic_buffer reply_payload;
2951 const char *new_path;
2952
2953 lttng_dynamic_buffer_init(&reply_payload);
2954
2955 if (!session || !conn->version_check_done) {
2956 ERR("Trying to close a trace chunk before version check");
2957 ret = -1;
2958 goto end_no_reply;
2959 }
2960
2961 if (session->major == 2 && session->minor < 11) {
2962 ERR("Chunk close command is unsupported before 2.11");
2963 ret = -1;
2964 goto end_no_reply;
2965 }
2966
2967 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
2968 if (!header_view.data) {
2969 ERR("Failed to receive payload of chunk close command");
2970 ret = -1;
2971 goto end_no_reply;
2972 }
2973
2974 /* Convert to host endianness. */
2975 msg = (typeof(msg)) header_view.data;
2976 chunk_id = be64toh(msg->chunk_id);
2977 close_timestamp = (time_t) be64toh(msg->close_timestamp);
2978 close_command = (typeof(close_command)){
2979 .value = be32toh(msg->close_command.value),
2980 .is_set = msg->close_command.is_set,
2981 };
2982
2983 chunk = sessiond_trace_chunk_registry_get_chunk(
2984 sessiond_trace_chunk_registry,
2985 conn->session->sessiond_uuid,
2986 conn->session->id_sessiond.is_set ?
2987 conn->session->id_sessiond.value :
2988 conn->session->id,
2989 chunk_id);
2990 if (!chunk) {
2991 char uuid_str[LTTNG_UUID_STR_LEN];
2992
2993 lttng_uuid_to_str(conn->session->sessiond_uuid, uuid_str);
2994 ERR("Failed to find chunk to close: sessiond_uuid = %s, session_id = %" PRIu64 ", chunk_id = %" PRIu64,
2995 uuid_str,
2996 conn->session->id,
2997 msg->chunk_id);
2998 ret = -1;
2999 reply_code = LTTNG_ERR_NOMEM;
3000 goto end;
3001 }
3002
3003 pthread_mutex_lock(&session->lock);
3004 if (close_command.is_set &&
3005 close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE) {
3006 /*
3007 * Clear command. It is a protocol error to ask for a
3008 * clear on a relay which does not allow it. Querying
3009 * the configuration allows figuring out whether
3010 * clearing is allowed before doing the clear.
3011 */
3012 if (!opt_allow_clear) {
3013 ret = -1;
3014 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
3015 goto end_unlock_session;
3016 }
3017 }
3018 if (session->pending_closure_trace_chunk &&
3019 session->pending_closure_trace_chunk != chunk) {
3020 ERR("Trace chunk close command for session \"%s\" does not target the trace chunk pending closure",
3021 session->session_name);
3022 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
3023 ret = -1;
3024 goto end_unlock_session;
3025 }
3026
3027 if (session->current_trace_chunk && session->current_trace_chunk != chunk &&
3028 !lttng_trace_chunk_get_name_overridden(session->current_trace_chunk)) {
3029 if (close_command.is_set &&
3030 close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE &&
3031 !session->has_rotated) {
3032 /* New chunk stays in session output directory. */
3033 new_path = "";
3034 } else {
3035 /* Use chunk name for new chunk. */
3036 new_path = NULL;
3037 }
3038 /* Rename new chunk path. */
3039 chunk_status = lttng_trace_chunk_rename_path(session->current_trace_chunk,
3040 new_path);
3041 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
3042 ret = -1;
3043 goto end_unlock_session;
3044 }
3045 session->ongoing_rotation = false;
3046 }
3047 if ((!close_command.is_set ||
3048 close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION) &&
3049 !lttng_trace_chunk_get_name_overridden(chunk)) {
3050 const char *old_path;
3051
3052 if (!session->has_rotated) {
3053 old_path = "";
3054 } else {
3055 old_path = NULL;
3056 }
3057 /* We need to move back the .tmp_old_chunk to its rightful place. */
3058 chunk_status = lttng_trace_chunk_rename_path(chunk, old_path);
3059 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
3060 ret = -1;
3061 goto end_unlock_session;
3062 }
3063 }
3064 chunk_status = lttng_trace_chunk_set_close_timestamp(
3065 chunk, close_timestamp);
3066 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
3067 ERR("Failed to set trace chunk close timestamp");
3068 ret = -1;
3069 reply_code = LTTNG_ERR_UNK;
3070 goto end_unlock_session;
3071 }
3072
3073 if (close_command.is_set) {
3074 chunk_status = lttng_trace_chunk_set_close_command(
3075 chunk, close_command.value);
3076 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
3077 ret = -1;
3078 reply_code = LTTNG_ERR_INVALID;
3079 goto end_unlock_session;
3080 }
3081 }
3082 chunk_status = lttng_trace_chunk_get_name(chunk, &chunk_name, NULL);
3083 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
3084 ERR("Failed to get chunk name");
3085 ret = -1;
3086 reply_code = LTTNG_ERR_UNK;
3087 goto end_unlock_session;
3088 }
3089 if (!session->has_rotated && !session->snapshot) {
3090 ret = lttng_strncpy(closed_trace_chunk_path,
3091 session->output_path,
3092 sizeof(closed_trace_chunk_path));
3093 if (ret) {
3094 ERR("Failed to send trace chunk path: path length of %zu bytes exceeds the maximal allowed length of %zu bytes",
3095 strlen(session->output_path),
3096 sizeof(closed_trace_chunk_path));
3097 reply_code = LTTNG_ERR_NOMEM;
3098 ret = -1;
3099 goto end_unlock_session;
3100 }
3101 } else {
3102 if (session->snapshot) {
3103 ret = snprintf(closed_trace_chunk_path,
3104 sizeof(closed_trace_chunk_path),
3105 "%s/%s", session->output_path,
3106 chunk_name);
3107 } else {
3108 ret = snprintf(closed_trace_chunk_path,
3109 sizeof(closed_trace_chunk_path),
3110 "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY
3111 "/%s",
3112 session->output_path, chunk_name);
3113 }
3114 if (ret < 0 || ret == sizeof(closed_trace_chunk_path)) {
3115 ERR("Failed to format closed trace chunk resulting path");
3116 reply_code = ret < 0 ? LTTNG_ERR_UNK : LTTNG_ERR_NOMEM;
3117 ret = -1;
3118 goto end_unlock_session;
3119 }
3120 }
3121 if (close_command.is_set &&
3122 close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED) {
3123 session->has_rotated = true;
3124 }
3125 DBG("Reply chunk path on close: %s", closed_trace_chunk_path);
3126 path_length = strlen(closed_trace_chunk_path) + 1;
3127 if (path_length > UINT32_MAX) {
3128 ERR("Closed trace chunk path exceeds the maximal length allowed by the protocol");
3129 ret = -1;
3130 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
3131 goto end_unlock_session;
3132 }
3133
3134 if (session->current_trace_chunk == chunk) {
3135 /*
3136 * After a trace chunk close command, no new streams
3137 * referencing the chunk may be created. Hence, on the
3138 * event that no new trace chunk have been created for
3139 * the session, the reference to the current trace chunk
3140 * is released in order to allow it to be reclaimed when
3141 * the last stream releases its reference to it.
3142 */
3143 lttng_trace_chunk_put(session->current_trace_chunk);
3144 session->current_trace_chunk = NULL;
3145 }
3146 lttng_trace_chunk_put(session->pending_closure_trace_chunk);
3147 session->pending_closure_trace_chunk = NULL;
3148 end_unlock_session:
3149 pthread_mutex_unlock(&session->lock);
3150
3151 end:
3152 reply.generic.ret_code = htobe32((uint32_t) reply_code);
3153 reply.path_length = htobe32((uint32_t) path_length);
3154 buf_ret = lttng_dynamic_buffer_append(
3155 &reply_payload, &reply, sizeof(reply));
3156 if (buf_ret) {
3157 ERR("Failed to append \"close trace chunk\" command reply header to payload buffer");
3158 goto end_no_reply;
3159 }
3160
3161 if (reply_code == LTTNG_OK) {
3162 buf_ret = lttng_dynamic_buffer_append(&reply_payload,
3163 closed_trace_chunk_path, path_length);
3164 if (buf_ret) {
3165 ERR("Failed to append \"close trace chunk\" command reply path to payload buffer");
3166 goto end_no_reply;
3167 }
3168 }
3169
3170 send_ret = conn->sock->ops->sendmsg(conn->sock,
3171 reply_payload.data,
3172 reply_payload.size,
3173 0);
3174 if (send_ret < reply_payload.size) {
3175 ERR("Failed to send \"close trace chunk\" command reply of %zu bytes (ret = %zd)",
3176 reply_payload.size, send_ret);
3177 ret = -1;
3178 goto end_no_reply;
3179 }
3180 end_no_reply:
3181 lttng_trace_chunk_put(chunk);
3182 lttng_dynamic_buffer_reset(&reply_payload);
3183 return ret;
3184 }
3185
3186 /*
3187 * relay_trace_chunk_exists: check if a trace chunk exists
3188 */
3189 static int relay_trace_chunk_exists(const struct lttcomm_relayd_hdr *recv_hdr,
3190 struct relay_connection *conn,
3191 const struct lttng_buffer_view *payload)
3192 {
3193 int ret = 0;
3194 ssize_t send_ret;
3195 struct relay_session *session = conn->session;
3196 struct lttcomm_relayd_trace_chunk_exists *msg;
3197 struct lttcomm_relayd_trace_chunk_exists_reply reply = {};
3198 struct lttng_buffer_view header_view;
3199 uint64_t chunk_id;
3200 bool chunk_exists;
3201
3202 if (!session || !conn->version_check_done) {
3203 ERR("Trying to close a trace chunk before version check");
3204 ret = -1;
3205 goto end_no_reply;
3206 }
3207
3208 if (session->major == 2 && session->minor < 11) {
3209 ERR("Chunk close command is unsupported before 2.11");
3210 ret = -1;
3211 goto end_no_reply;
3212 }
3213
3214 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
3215 if (!header_view.data) {
3216 ERR("Failed to receive payload of chunk close command");
3217 ret = -1;
3218 goto end_no_reply;
3219 }
3220
3221 /* Convert to host endianness. */
3222 msg = (typeof(msg)) header_view.data;
3223 chunk_id = be64toh(msg->chunk_id);
3224
3225 ret = sessiond_trace_chunk_registry_chunk_exists(
3226 sessiond_trace_chunk_registry,
3227 conn->session->sessiond_uuid,
3228 conn->session->id,
3229 chunk_id, &chunk_exists);
3230 /*
3231 * If ret is not 0, send the reply and report the error to the caller.
3232 * It is a protocol (or internal) error and the session/connection
3233 * should be torn down.
3234 */
3235 reply = (typeof(reply)){
3236 .generic.ret_code = htobe32((uint32_t)
3237 (ret == 0 ? LTTNG_OK : LTTNG_ERR_INVALID_PROTOCOL)),
3238 .trace_chunk_exists = ret == 0 ? chunk_exists : 0,
3239 };
3240 send_ret = conn->sock->ops->sendmsg(
3241 conn->sock, &reply, sizeof(reply), 0);
3242 if (send_ret < (ssize_t) sizeof(reply)) {
3243 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
3244 send_ret);
3245 ret = -1;
3246 }
3247 end_no_reply:
3248 return ret;
3249 }
3250
3251 /*
3252 * relay_get_configuration: query whether feature is available
3253 */
3254 static int relay_get_configuration(const struct lttcomm_relayd_hdr *recv_hdr,
3255 struct relay_connection *conn,
3256 const struct lttng_buffer_view *payload)
3257 {
3258 int ret = 0;
3259 ssize_t send_ret;
3260 struct lttcomm_relayd_get_configuration *msg;
3261 struct lttcomm_relayd_get_configuration_reply reply = {};
3262 struct lttng_buffer_view header_view;
3263 uint64_t query_flags = 0;
3264 uint64_t result_flags = 0;
3265
3266 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
3267 if (!header_view.data) {
3268 ERR("Failed to receive payload of chunk close command");
3269 ret = -1;
3270 goto end_no_reply;
3271 }
3272
3273 /* Convert to host endianness. */
3274 msg = (typeof(msg)) header_view.data;
3275 query_flags = be64toh(msg->query_flags);
3276
3277 if (query_flags) {
3278 ret = LTTNG_ERR_INVALID_PROTOCOL;
3279 goto reply;
3280 }
3281 if (opt_allow_clear) {
3282 result_flags |= LTTCOMM_RELAYD_CONFIGURATION_FLAG_CLEAR_ALLOWED;
3283 }
3284 ret = 0;
3285 reply:
3286 reply = (typeof(reply)){
3287 .generic.ret_code = htobe32((uint32_t)
3288 (ret == 0 ? LTTNG_OK : LTTNG_ERR_INVALID_PROTOCOL)),
3289 .relayd_configuration_flags = htobe64(result_flags),
3290 };
3291 send_ret = conn->sock->ops->sendmsg(
3292 conn->sock, &reply, sizeof(reply), 0);
3293 if (send_ret < (ssize_t) sizeof(reply)) {
3294 ERR("Failed to send \"get configuration\" command reply (ret = %zd)",
3295 send_ret);
3296 ret = -1;
3297 }
3298 end_no_reply:
3299 return ret;
3300 }
3301
3302 #define DBG_CMD(cmd_name, conn) \
3303 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
3304
3305 static int relay_process_control_command(struct relay_connection *conn,
3306 const struct lttcomm_relayd_hdr *header,
3307 const struct lttng_buffer_view *payload)
3308 {
3309 int ret = 0;
3310
3311 switch (header->cmd) {
3312 case RELAYD_CREATE_SESSION:
3313 DBG_CMD("RELAYD_CREATE_SESSION", conn);
3314 ret = relay_create_session(header, conn, payload);
3315 break;
3316 case RELAYD_ADD_STREAM:
3317 DBG_CMD("RELAYD_ADD_STREAM", conn);
3318 ret = relay_add_stream(header, conn, payload);
3319 break;
3320 case RELAYD_START_DATA:
3321 DBG_CMD("RELAYD_START_DATA", conn);
3322 ret = relay_start(header, conn, payload);
3323 break;
3324 case RELAYD_SEND_METADATA:
3325 DBG_CMD("RELAYD_SEND_METADATA", conn);
3326 ret = relay_recv_metadata(header, conn, payload);
3327 break;
3328 case RELAYD_VERSION:
3329 DBG_CMD("RELAYD_VERSION", conn);
3330 ret = relay_send_version(header, conn, payload);
3331 break;
3332 case RELAYD_CLOSE_STREAM:
3333 DBG_CMD("RELAYD_CLOSE_STREAM", conn);
3334 ret = relay_close_stream(header, conn, payload);
3335 break;
3336 case RELAYD_DATA_PENDING:
3337 DBG_CMD("RELAYD_DATA_PENDING", conn);
3338 ret = relay_data_pending(header, conn, payload);
3339 break;
3340 case RELAYD_QUIESCENT_CONTROL:
3341 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn);
3342 ret = relay_quiescent_control(header, conn, payload);
3343 break;
3344 case RELAYD_BEGIN_DATA_PENDING:
3345 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn);
3346 ret = relay_begin_data_pending(header, conn, payload);
3347 break;
3348 case RELAYD_END_DATA_PENDING:
3349 DBG_CMD("RELAYD_END_DATA_PENDING", conn);
3350 ret = relay_end_data_pending(header, conn, payload);
3351 break;
3352 case RELAYD_SEND_INDEX:
3353 DBG_CMD("RELAYD_SEND_INDEX", conn);
3354 ret = relay_recv_index(header, conn, payload);
3355 break;
3356 case RELAYD_STREAMS_SENT:
3357 DBG_CMD("RELAYD_STREAMS_SENT", conn);
3358 ret = relay_streams_sent(header, conn, payload);
3359 break;
3360 case RELAYD_RESET_METADATA:
3361 DBG_CMD("RELAYD_RESET_METADATA", conn);
3362 ret = relay_reset_metadata(header, conn, payload);
3363 break;
3364 case RELAYD_ROTATE_STREAMS:
3365 DBG_CMD("RELAYD_ROTATE_STREAMS", conn);
3366 ret = relay_rotate_session_streams(header, conn, payload);
3367 break;
3368 case RELAYD_CREATE_TRACE_CHUNK:
3369 DBG_CMD("RELAYD_CREATE_TRACE_CHUNK", conn);
3370 ret = relay_create_trace_chunk(header, conn, payload);
3371 break;
3372 case RELAYD_CLOSE_TRACE_CHUNK:
3373 DBG_CMD("RELAYD_CLOSE_TRACE_CHUNK", conn);
3374 ret = relay_close_trace_chunk(header, conn, payload);
3375 break;
3376 case RELAYD_TRACE_CHUNK_EXISTS:
3377 DBG_CMD("RELAYD_TRACE_CHUNK_EXISTS", conn);
3378 ret = relay_trace_chunk_exists(header, conn, payload);
3379 break;
3380 case RELAYD_GET_CONFIGURATION:
3381 DBG_CMD("RELAYD_GET_CONFIGURATION", conn);
3382 ret = relay_get_configuration(header, conn, payload);
3383 break;
3384 case RELAYD_UPDATE_SYNC_INFO:
3385 default:
3386 ERR("Received unknown command (%u)", header->cmd);
3387 relay_unknown_command(conn);
3388 ret = -1;
3389 goto end;
3390 }
3391
3392 end:
3393 return ret;
3394 }
3395
3396 static enum relay_connection_status relay_process_control_receive_payload(
3397 struct relay_connection *conn)
3398 {
3399 int ret = 0;
3400 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
3401 struct lttng_dynamic_buffer *reception_buffer =
3402 &conn->protocol.ctrl.reception_buffer;
3403 struct ctrl_connection_state_receive_payload *state =
3404 &conn->protocol.ctrl.state.receive_payload;
3405 struct lttng_buffer_view payload_view;
3406
3407 if (state->left_to_receive == 0) {
3408 /* Short-circuit for payload-less commands. */
3409 goto reception_complete;
3410 }
3411
3412 ret = conn->sock->ops->recvmsg(conn->sock,
3413 reception_buffer->data + state->received,
3414 state->left_to_receive, MSG_DONTWAIT);
3415 if (ret < 0) {
3416 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3417 PERROR("Unable to receive command payload on sock %d",
3418 conn->sock->fd);
3419 status = RELAY_CONNECTION_STATUS_ERROR;
3420 }
3421 goto end;
3422 } else if (ret == 0) {
3423 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
3424 status = RELAY_CONNECTION_STATUS_CLOSED;
3425 goto end;
3426 }
3427
3428 assert(ret > 0);
3429 assert(ret <= state->left_to_receive);
3430
3431 state->left_to_receive -= ret;
3432 state->received += ret;
3433
3434 if (state->left_to_receive > 0) {
3435 /*
3436 * Can't transition to the protocol's next state, wait to
3437 * receive the rest of the header.
3438 */
3439 DBG3("Partial reception of control connection protocol payload (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
3440 state->received, state->left_to_receive,
3441 conn->sock->fd);
3442 goto end;
3443 }
3444
3445 reception_complete:
3446 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64 " bytes",
3447 conn->sock->fd, state->received);
3448 /*
3449 * The payload required to process the command has been received.
3450 * A view to the reception buffer is forwarded to the various
3451 * commands and the state of the control is reset on success.
3452 *
3453 * Commands are responsible for sending their reply to the peer.
3454 */
3455 payload_view = lttng_buffer_view_from_dynamic_buffer(reception_buffer,
3456 0, -1);
3457 ret = relay_process_control_command(conn,
3458 &state->header, &payload_view);
3459 if (ret < 0) {
3460 status = RELAY_CONNECTION_STATUS_ERROR;
3461 goto end;
3462 }
3463
3464 ret = connection_reset_protocol_state(conn);
3465 if (ret) {
3466 status = RELAY_CONNECTION_STATUS_ERROR;
3467 }
3468 end:
3469 return status;
3470 }
3471
3472 static enum relay_connection_status relay_process_control_receive_header(
3473 struct relay_connection *conn)
3474 {
3475 int ret = 0;
3476 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
3477 struct lttcomm_relayd_hdr header;
3478 struct lttng_dynamic_buffer *reception_buffer =
3479 &conn->protocol.ctrl.reception_buffer;
3480 struct ctrl_connection_state_receive_header *state =
3481 &conn->protocol.ctrl.state.receive_header;
3482
3483 assert(state->left_to_receive != 0);
3484
3485 ret = conn->sock->ops->recvmsg(conn->sock,
3486 reception_buffer->data + state->received,
3487 state->left_to_receive, MSG_DONTWAIT);
3488 if (ret < 0) {
3489 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3490 PERROR("Unable to receive control command header on sock %d",
3491 conn->sock->fd);
3492 status = RELAY_CONNECTION_STATUS_ERROR;
3493 }
3494 goto end;
3495 } else if (ret == 0) {
3496 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
3497 status = RELAY_CONNECTION_STATUS_CLOSED;
3498 goto end;
3499 }
3500
3501 assert(ret > 0);
3502 assert(ret <= state->left_to_receive);
3503
3504 state->left_to_receive -= ret;
3505 state->received += ret;
3506
3507 if (state->left_to_receive > 0) {
3508 /*
3509 * Can't transition to the protocol's next state, wait to
3510 * receive the rest of the header.
3511 */
3512 DBG3("Partial reception of control connection protocol header (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
3513 state->received, state->left_to_receive,
3514 conn->sock->fd);
3515 goto end;
3516 }
3517
3518 /* Transition to next state: receiving the command's payload. */
3519 conn->protocol.ctrl.state_id =
3520 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD;
3521 memcpy(&header, reception_buffer->data, sizeof(header));
3522 header.circuit_id = be64toh(header.circuit_id);
3523 header.data_size = be64toh(header.data_size);
3524 header.cmd = be32toh(header.cmd);
3525 header.cmd_version = be32toh(header.cmd_version);
3526 memcpy(&conn->protocol.ctrl.state.receive_payload.header,
3527 &header, sizeof(header));
3528
3529 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32 ", cmd_version = %" PRIu32 ", payload size = %" PRIu64 " bytes",
3530 conn->sock->fd, header.cmd, header.cmd_version,
3531 header.data_size);
3532
3533 if (header.data_size > DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE) {
3534 ERR("Command header indicates a payload (%" PRIu64 " bytes) that exceeds the maximal payload size allowed on a control connection.",
3535 header.data_size);
3536 status = RELAY_CONNECTION_STATUS_ERROR;
3537 goto end;
3538 }
3539
3540 conn->protocol.ctrl.state.receive_payload.left_to_receive =
3541 header.data_size;
3542 conn->protocol.ctrl.state.receive_payload.received = 0;
3543 ret = lttng_dynamic_buffer_set_size(reception_buffer,
3544 header.data_size);
3545 if (ret) {
3546 status = RELAY_CONNECTION_STATUS_ERROR;
3547 goto end;
3548 }
3549
3550 if (header.data_size == 0) {
3551 /*
3552 * Manually invoke the next state as the poll loop
3553 * will not wake-up to allow us to proceed further.
3554 */
3555 status = relay_process_control_receive_payload(conn);
3556 }
3557 end:
3558 return status;
3559 }
3560
3561 /*
3562 * Process the commands received on the control socket
3563 */
3564 static enum relay_connection_status relay_process_control(
3565 struct relay_connection *conn)
3566 {
3567 enum relay_connection_status status;
3568
3569 switch (conn->protocol.ctrl.state_id) {
3570 case CTRL_CONNECTION_STATE_RECEIVE_HEADER:
3571 status = relay_process_control_receive_header(conn);
3572 break;
3573 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD:
3574 status = relay_process_control_receive_payload(conn);
3575 break;
3576 default:
3577 ERR("Unknown control connection protocol state encountered.");
3578 abort();
3579 }
3580
3581 return status;
3582 }
3583
3584 static enum relay_connection_status relay_process_data_receive_header(
3585 struct relay_connection *conn)
3586 {
3587 int ret;
3588 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
3589 struct data_connection_state_receive_header *state =
3590 &conn->protocol.data.state.receive_header;
3591 struct lttcomm_relayd_data_hdr header;
3592 struct relay_stream *stream;
3593
3594 assert(state->left_to_receive != 0);
3595
3596 ret = conn->sock->ops->recvmsg(conn->sock,
3597 state->header_reception_buffer + state->received,
3598 state->left_to_receive, MSG_DONTWAIT);
3599 if (ret < 0) {
3600 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3601 PERROR("Unable to receive data header on sock %d", conn->sock->fd);
3602 status = RELAY_CONNECTION_STATUS_ERROR;
3603 }
3604 goto end;
3605 } else if (ret == 0) {
3606 /* Orderly shutdown. Not necessary to print an error. */
3607 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
3608 status = RELAY_CONNECTION_STATUS_CLOSED;
3609 goto end;
3610 }
3611
3612 assert(ret > 0);
3613 assert(ret <= state->left_to_receive);
3614
3615 state->left_to_receive -= ret;
3616 state->received += ret;
3617
3618 if (state->left_to_receive > 0) {
3619 /*
3620 * Can't transition to the protocol's next state, wait to
3621 * receive the rest of the header.
3622 */
3623 DBG3("Partial reception of data connection header (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
3624 state->received, state->left_to_receive,
3625 conn->sock->fd);
3626 goto end;
3627 }
3628
3629 /* Transition to next state: receiving the payload. */
3630 conn->protocol.data.state_id = DATA_CONNECTION_STATE_RECEIVE_PAYLOAD;
3631
3632 memcpy(&header, state->header_reception_buffer, sizeof(header));
3633 header.circuit_id = be64toh(header.circuit_id);
3634 header.stream_id = be64toh(header.stream_id);
3635 header.data_size = be32toh(header.data_size);
3636 header.net_seq_num = be64toh(header.net_seq_num);
3637 header.padding_size = be32toh(header.padding_size);
3638 memcpy(&conn->protocol.data.state.receive_payload.header, &header, sizeof(header));
3639
3640 conn->protocol.data.state.receive_payload.left_to_receive =
3641 header.data_size;
3642 conn->protocol.data.state.receive_payload.received = 0;
3643 conn->protocol.data.state.receive_payload.rotate_index = false;
3644
3645 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64 ", stream_id = %" PRIu64 ", data_size = %" PRIu32 ", net_seq_num = %" PRIu64 ", padding_size = %" PRIu32,
3646 conn->sock->fd, header.circuit_id,
3647 header.stream_id, header.data_size,
3648 header.net_seq_num, header.padding_size);
3649
3650 stream = stream_get_by_id(header.stream_id);
3651 if (!stream) {
3652 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64,
3653 header.stream_id);
3654 /* Protocol error. */
3655 status = RELAY_CONNECTION_STATUS_ERROR;
3656 goto end;
3657 }
3658
3659 pthread_mutex_lock(&stream->lock);
3660 /* Prepare stream for the reception of a new packet. */
3661 ret = stream_init_packet(stream, header.data_size,
3662 &conn->protocol.data.state.receive_payload.rotate_index);
3663 pthread_mutex_unlock(&stream->lock);
3664 if (ret) {
3665 ERR("Failed to rotate stream output file");
3666 status = RELAY_CONNECTION_STATUS_ERROR;
3667 goto end_stream_unlock;
3668 }
3669
3670 end_stream_unlock:
3671 stream_put(stream);
3672 end:
3673 return status;
3674 }
3675
3676 static enum relay_connection_status relay_process_data_receive_payload(
3677 struct relay_connection *conn)
3678 {
3679 int ret;
3680 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
3681 struct relay_stream *stream;
3682 struct data_connection_state_receive_payload *state =
3683 &conn->protocol.data.state.receive_payload;
3684 const size_t chunk_size = RECV_DATA_BUFFER_SIZE;
3685 char data_buffer[chunk_size];
3686 bool partial_recv = false;
3687 bool new_stream = false, close_requested = false, index_flushed = false;
3688 uint64_t left_to_receive = state->left_to_receive;
3689 struct relay_session *session;
3690
3691 DBG3("Receiving data for stream id %" PRIu64 " seqnum %" PRIu64 ", %" PRIu64" bytes received, %" PRIu64 " bytes left to receive",
3692 state->header.stream_id, state->header.net_seq_num,
3693 state->received, left_to_receive);
3694
3695 stream = stream_get_by_id(state->header.stream_id);
3696 if (!stream) {
3697 /* Protocol error. */
3698 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64,
3699 state->header.stream_id);
3700 status = RELAY_CONNECTION_STATUS_ERROR;
3701 goto end;
3702 }
3703
3704 pthread_mutex_lock(&stream->lock);
3705 session = stream->trace->session;
3706 if (!conn->session) {
3707 ret = connection_set_session(conn, session);
3708 if (ret) {
3709 status = RELAY_CONNECTION_STATUS_ERROR;
3710 goto end_stream_unlock;
3711 }
3712 }
3713
3714 /*
3715 * The size of the "chunk" received on any iteration is bounded by:
3716 * - the data left to receive,
3717 * - the data immediately available on the socket,
3718 * - the on-stack data buffer
3719 */
3720 while (left_to_receive > 0 && !partial_recv) {
3721 size_t recv_size = min(left_to_receive, chunk_size);
3722 struct lttng_buffer_view packet_chunk;
3723
3724 ret = conn->sock->ops->recvmsg(conn->sock, data_buffer,
3725 recv_size, MSG_DONTWAIT);
3726 if (ret < 0) {
3727 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3728 PERROR("Socket %d error", conn->sock->fd);
3729 status = RELAY_CONNECTION_STATUS_ERROR;
3730 }
3731 goto end_stream_unlock;
3732 } else if (ret == 0) {
3733 /* No more data ready to be consumed on socket. */
3734 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64,
3735 state->header.stream_id);
3736 status = RELAY_CONNECTION_STATUS_CLOSED;
3737 break;
3738 } else if (ret < (int) recv_size) {
3739 /*
3740 * All the data available on the socket has been
3741 * consumed.
3742 */
3743 partial_recv = true;
3744 recv_size = ret;
3745 }
3746
3747 packet_chunk = lttng_buffer_view_init(data_buffer,
3748 0, recv_size);
3749 assert(packet_chunk.data);
3750
3751 ret = stream_write(stream, &packet_chunk, 0);
3752 if (ret) {
3753 ERR("Relay error writing data to file");
3754 status = RELAY_CONNECTION_STATUS_ERROR;
3755 goto end_stream_unlock;
3756 }
3757
3758 left_to_receive -= recv_size;
3759 state->received += recv_size;
3760 state->left_to_receive = left_to_receive;
3761 }
3762
3763 if (state->left_to_receive > 0) {
3764 /*
3765 * Did not receive all the data expected, wait for more data to
3766 * become available on the socket.
3767 */
3768 DBG3("Partial receive on data connection of stream id %" PRIu64 ", %" PRIu64 " bytes received, %" PRIu64 " bytes left to receive",
3769 state->header.stream_id, state->received,
3770 state->left_to_receive);
3771 goto end_stream_unlock;
3772 }
3773
3774 ret = stream_write(stream, NULL, state->header.padding_size);
3775 if (ret) {
3776 status = RELAY_CONNECTION_STATUS_ERROR;
3777 goto end_stream_unlock;
3778 }
3779
3780 if (session_streams_have_index(session)) {
3781 ret = stream_update_index(stream, state->header.net_seq_num,
3782 state->rotate_index, &index_flushed,
3783 state->header.data_size + state->header.padding_size);
3784 if (ret < 0) {
3785 ERR("Failed to update index: stream %" PRIu64 " net_seq_num %" PRIu64 " ret %d",
3786 stream->stream_handle,
3787 state->header.net_seq_num, ret);
3788 status = RELAY_CONNECTION_STATUS_ERROR;
3789 goto end_stream_unlock;
3790 }
3791 }
3792
3793 if (stream->prev_data_seq == -1ULL) {
3794 new_stream = true;
3795 }
3796
3797 ret = stream_complete_packet(stream, state->header.data_size +
3798 state->header.padding_size, state->header.net_seq_num,
3799 index_flushed);
3800 if (ret) {
3801 status = RELAY_CONNECTION_STATUS_ERROR;
3802 goto end_stream_unlock;
3803 }
3804
3805 /*
3806 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3807 * contents of *state which are aliased (union) to the same location as
3808 * the new state. Don't use it beyond this point.
3809 */
3810 connection_reset_protocol_state(conn);
3811 state = NULL;
3812
3813 end_stream_unlock:
3814 close_requested = stream->close_requested;
3815 pthread_mutex_unlock(&stream->lock);
3816 if (close_requested && left_to_receive == 0) {
3817 try_stream_close(stream);
3818 }
3819
3820 if (new_stream) {
3821 pthread_mutex_lock(&session->lock);
3822 uatomic_set(&session->new_streams, 1);
3823 pthread_mutex_unlock(&session->lock);
3824 }
3825
3826 stream_put(stream);
3827 end:
3828 return status;
3829 }
3830
3831 /*
3832 * relay_process_data: Process the data received on the data socket
3833 */
3834 static enum relay_connection_status relay_process_data(
3835 struct relay_connection *conn)
3836 {
3837 enum relay_connection_status status;
3838
3839 switch (conn->protocol.data.state_id) {
3840 case DATA_CONNECTION_STATE_RECEIVE_HEADER:
3841 status = relay_process_data_receive_header(conn);
3842 break;
3843 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD:
3844 status = relay_process_data_receive_payload(conn);
3845 break;
3846 default:
3847 ERR("Unexpected data connection communication state.");
3848 abort();
3849 }
3850
3851 return status;
3852 }
3853
3854 static void cleanup_connection_pollfd(struct lttng_poll_event *events, int pollfd)
3855 {
3856 int ret;
3857
3858 (void) lttng_poll_del(events, pollfd);
3859
3860 ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker, &pollfd, 1,
3861 fd_tracker_util_close_fd, NULL);
3862 if (ret < 0) {
3863 ERR("Closing pollfd %d", pollfd);
3864 }
3865 }
3866
3867 static void relay_thread_close_connection(struct lttng_poll_event *events,
3868 int pollfd, struct relay_connection *conn)
3869 {
3870 const char *type_str;
3871
3872 switch (conn->type) {
3873 case RELAY_DATA:
3874 type_str = "Data";
3875 break;
3876 case RELAY_CONTROL:
3877 type_str = "Control";
3878 break;
3879 case RELAY_VIEWER_COMMAND:
3880 type_str = "Viewer Command";
3881 break;
3882 case RELAY_VIEWER_NOTIFICATION:
3883 type_str = "Viewer Notification";
3884 break;
3885 default:
3886 type_str = "Unknown";
3887 }
3888 cleanup_connection_pollfd(events, pollfd);
3889 connection_put(conn);
3890 DBG("%s connection closed with %d", type_str, pollfd);
3891 }
3892
3893 /*
3894 * This thread does the actual work
3895 */
3896 static void *relay_thread_worker(void *data)
3897 {
3898 int ret, err = -1, last_seen_data_fd = -1;
3899 uint32_t nb_fd;
3900 struct lttng_poll_event events;
3901 struct lttng_ht *relay_connections_ht;
3902 struct lttng_ht_iter iter;
3903 struct relay_connection *destroy_conn = NULL;
3904
3905 DBG("[thread] Relay worker started");
3906
3907 rcu_register_thread();
3908
3909 health_register(health_relayd, HEALTH_RELAYD_TYPE_WORKER);
3910
3911 if (testpoint(relayd_thread_worker)) {
3912 goto error_testpoint;
3913 }
3914
3915 health_code_update();
3916
3917 /* table of connections indexed on socket */
3918 relay_connections_ht = lttng_ht_new(0, LTTNG_HT_TYPE_ULONG);
3919 if (!relay_connections_ht) {
3920 goto relay_connections_ht_error;
3921 }
3922
3923 ret = create_named_thread_poll_set(&events, 2, "Worker thread epoll");
3924 if (ret < 0) {
3925 goto error_poll_create;
3926 }
3927
3928 ret = lttng_poll_add(&events, relay_conn_pipe[0], LPOLLIN | LPOLLRDHUP);
3929 if (ret < 0) {
3930 goto error;
3931 }
3932
3933 restart:
3934 while (1) {
3935 int idx = -1, i, seen_control = 0, last_notdel_data_fd = -1;
3936
3937 health_code_update();
3938
3939 /* Infinite blocking call, waiting for transmission */
3940 DBG3("Relayd worker thread polling...");
3941 health_poll_entry();
3942 ret = lttng_poll_wait(&events, -1);
3943 health_poll_exit();
3944 if (ret < 0) {
3945 /*
3946 * Restart interrupted system call.
3947 */
3948 if (errno == EINTR) {
3949 goto restart;
3950 }
3951 goto error;
3952 }
3953
3954 nb_fd = ret;
3955
3956 /*
3957 * Process control. The control connection is
3958 * prioritized so we don't starve it with high
3959 * throughput tracing data on the data connection.
3960 */
3961 for (i = 0; i < nb_fd; i++) {
3962 /* Fetch once the poll data */
3963 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
3964 int pollfd = LTTNG_POLL_GETFD(&events, i);
3965
3966 health_code_update();
3967
3968 /* Thread quit pipe has been closed. Killing thread. */
3969 ret = check_thread_quit_pipe(pollfd, revents);
3970 if (ret) {
3971 err = 0;
3972 goto exit;
3973 }
3974
3975 /* Inspect the relay conn pipe for new connection */
3976 if (pollfd == relay_conn_pipe[0]) {
3977 if (revents & LPOLLIN) {
3978 struct relay_connection *conn;
3979
3980 ret = lttng_read(relay_conn_pipe[0], &conn, sizeof(conn));
3981 if (ret < 0) {
3982 goto error;
3983 }
3984 ret = lttng_poll_add(&events,
3985 conn->sock->fd,
3986 LPOLLIN | LPOLLRDHUP);
3987 if (ret) {
3988 ERR("Failed to add new connection file descriptor to poll set");
3989 goto error;
3990 }
3991 connection_ht_add(relay_connections_ht, conn);
3992 DBG("Connection socket %d added", conn->sock->fd);
3993 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
3994 ERR("Relay connection pipe error");
3995 goto error;
3996 } else {
3997 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
3998 goto error;
3999 }
4000 } else {
4001 struct relay_connection *ctrl_conn;
4002
4003 ctrl_conn = connection_get_by_sock(relay_connections_ht, pollfd);
4004 /* If not found, there is a synchronization issue. */
4005 assert(ctrl_conn);
4006
4007 if (ctrl_conn->type == RELAY_DATA) {
4008 if (revents & LPOLLIN) {
4009 /*
4010 * Flag the last seen data fd not deleted. It will be
4011 * used as the last seen fd if any fd gets deleted in
4012 * this first loop.
4013 */
4014 last_notdel_data_fd = pollfd;
4015 }
4016 goto put_ctrl_connection;
4017 }
4018 assert(ctrl_conn->type == RELAY_CONTROL);
4019
4020 if (revents & LPOLLIN) {
4021 enum relay_connection_status status;
4022
4023 status = relay_process_control(ctrl_conn);
4024 if (status != RELAY_CONNECTION_STATUS_OK) {
4025 /*
4026 * On socket error flag the session as aborted to force
4027 * the cleanup of its stream otherwise it can leak
4028 * during the lifetime of the relayd.
4029 *
4030 * This prevents situations in which streams can be
4031 * left opened because an index was received, the
4032 * control connection is closed, and the data
4033 * connection is closed (uncleanly) before the packet's
4034 * data provided.
4035 *
4036 * Since the control connection encountered an error,
4037 * it is okay to be conservative and close the
4038 * session right now as we can't rely on the protocol
4039 * being respected anymore.
4040 */
4041 if (status == RELAY_CONNECTION_STATUS_ERROR) {
4042 session_abort(ctrl_conn->session);
4043 }
4044
4045 /* Clear the connection on error or close. */
4046 relay_thread_close_connection(&events,
4047 pollfd,
4048 ctrl_conn);
4049 }
4050 seen_control = 1;
4051 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
4052 relay_thread_close_connection(&events,
4053 pollfd, ctrl_conn);
4054 if (last_seen_data_fd == pollfd) {
4055 last_seen_data_fd = last_notdel_data_fd;
4056 }
4057 } else {
4058 ERR("Unexpected poll events %u for control sock %d",
4059 revents, pollfd);
4060 connection_put(ctrl_conn);
4061 goto error;
4062 }
4063 put_ctrl_connection:
4064 connection_put(ctrl_conn);
4065 }
4066 }
4067
4068 /*
4069 * The last loop handled a control request, go back to poll to make
4070 * sure we prioritise the control socket.
4071 */
4072 if (seen_control) {
4073 continue;
4074 }
4075
4076 if (last_seen_data_fd >= 0) {
4077 for (i = 0; i < nb_fd; i++) {
4078 int pollfd = LTTNG_POLL_GETFD(&events, i);
4079
4080 health_code_update();
4081
4082 if (last_seen_data_fd == pollfd) {
4083 idx = i;
4084 break;
4085 }
4086 }
4087 }
4088
4089 /* Process data connection. */
4090 for (i = idx + 1; i < nb_fd; i++) {
4091 /* Fetch the poll data. */
4092 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
4093 int pollfd = LTTNG_POLL_GETFD(&events, i);
4094 struct relay_connection *data_conn;
4095
4096 health_code_update();
4097
4098 if (!revents) {
4099 /* No activity for this FD (poll implementation). */
4100 continue;
4101 }
4102
4103 /* Skip the command pipe. It's handled in the first loop. */
4104 if (pollfd == relay_conn_pipe[0]) {
4105 continue;
4106 }
4107
4108 data_conn = connection_get_by_sock(relay_connections_ht, pollfd);
4109 if (!data_conn) {
4110 /* Skip it. Might be removed before. */
4111 continue;
4112 }
4113 if (data_conn->type == RELAY_CONTROL) {
4114 goto put_data_connection;
4115 }
4116 assert(data_conn->type == RELAY_DATA);
4117
4118 if (revents & LPOLLIN) {
4119 enum relay_connection_status status;
4120
4121 status = relay_process_data(data_conn);
4122 /* Connection closed or error. */
4123 if (status != RELAY_CONNECTION_STATUS_OK) {
4124 /*
4125 * On socket error flag the session as aborted to force
4126 * the cleanup of its stream otherwise it can leak
4127 * during the lifetime of the relayd.
4128 *
4129 * This prevents situations in which streams can be
4130 * left opened because an index was received, the
4131 * control connection is closed, and the data
4132 * connection is closed (uncleanly) before the packet's
4133 * data provided.
4134 *
4135 * Since the data connection encountered an error,
4136 * it is okay to be conservative and close the
4137 * session right now as we can't rely on the protocol
4138 * being respected anymore.
4139 */
4140 if (status == RELAY_CONNECTION_STATUS_ERROR) {
4141 session_abort(data_conn->session);
4142 }
4143 relay_thread_close_connection(&events, pollfd,
4144 data_conn);
4145 /*
4146 * Every goto restart call sets the last seen fd where
4147 * here we don't really care since we gracefully
4148 * continue the loop after the connection is deleted.
4149 */
4150 } else {
4151 /* Keep last seen port. */
4152 last_seen_data_fd = pollfd;
4153 connection_put(data_conn);
4154 goto restart;
4155 }
4156 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
4157 relay_thread_close_connection(&events, pollfd,
4158 data_conn);
4159 } else {
4160 ERR("Unknown poll events %u for data sock %d",
4161 revents, pollfd);
4162 }
4163 put_data_connection:
4164 connection_put(data_conn);
4165 }
4166 last_seen_data_fd = -1;
4167 }
4168
4169 /* Normal exit, no error */
4170 ret = 0;
4171
4172 exit:
4173 error:
4174 /* Cleanup remaining connection object. */
4175 rcu_read_lock();
4176 cds_lfht_for_each_entry(relay_connections_ht->ht, &iter.iter,
4177 destroy_conn,
4178 sock_n.node) {
4179 health_code_update();
4180
4181 session_abort(destroy_conn->session);
4182
4183 /*
4184 * No need to grab another ref, because we own
4185 * destroy_conn.
4186 */
4187 relay_thread_close_connection(&events, destroy_conn->sock->fd,
4188 destroy_conn);
4189 }
4190 rcu_read_unlock();
4191
4192 (void) fd_tracker_util_poll_clean(the_fd_tracker, &events);
4193 error_poll_create:
4194 lttng_ht_destroy(relay_connections_ht);
4195 relay_connections_ht_error:
4196 /* Close relay conn pipes */
4197 (void) fd_tracker_util_pipe_close(the_fd_tracker,
4198 relay_conn_pipe);
4199 if (err) {
4200 DBG("Thread exited with error");
4201 }
4202 DBG("Worker thread cleanup complete");
4203 error_testpoint:
4204 if (err) {
4205 health_error();
4206 ERR("Health error occurred in %s", __func__);
4207 }
4208 health_unregister(health_relayd);
4209 rcu_unregister_thread();
4210 lttng_relay_stop_threads();
4211 return NULL;
4212 }
4213
4214 /*
4215 * Create the relay command pipe to wake thread_manage_apps.
4216 * Closed in cleanup().
4217 */
4218 static int create_relay_conn_pipe(void)
4219 {
4220 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker,
4221 "Relayd connection pipe", relay_conn_pipe);
4222 }
4223
4224 static int stdio_open(void *data, int *fds)
4225 {
4226 fds[0] = fileno(stdout);
4227 fds[1] = fileno(stderr);
4228 return 0;
4229 }
4230
4231 static int track_stdio(void)
4232 {
4233 int fds[2];
4234 const char *names[] = { "stdout", "stderr" };
4235
4236 return fd_tracker_open_unsuspendable_fd(the_fd_tracker, fds,
4237 names, 2, stdio_open, NULL);
4238 }
4239
4240 /*
4241 * main
4242 */
4243 int main(int argc, char **argv)
4244 {
4245 bool thread_is_rcu_registered = false;
4246 int ret = 0, retval = 0;
4247 void *status;
4248 char *unlinked_file_directory_path = NULL, *output_path = NULL;
4249
4250 /* Parse environment variables */
4251 ret = parse_env_options();
4252 if (ret) {
4253 retval = -1;
4254 goto exit_options;
4255 }
4256
4257 /*
4258 * Parse arguments.
4259 * Command line arguments overwrite environment.
4260 */
4261 progname = argv[0];
4262 if (set_options(argc, argv)) {
4263 retval = -1;
4264 goto exit_options;
4265 }
4266
4267 if (set_signal_handler()) {
4268 retval = -1;
4269 goto exit_options;
4270 }
4271
4272 relayd_config_log();
4273
4274 if (opt_print_version) {
4275 print_version();
4276 retval = 0;
4277 goto exit_options;
4278 }
4279
4280 ret = fclose(stdin);
4281 if (ret) {
4282 PERROR("Failed to close stdin");
4283 goto exit_options;
4284 }
4285
4286 DBG("Clear command %s", opt_allow_clear ? "allowed" : "disallowed");
4287
4288 /* Try to create directory if -o, --output is specified. */
4289 if (opt_output_path) {
4290 if (*opt_output_path != '/') {
4291 ERR("Please specify an absolute path for -o, --output PATH");
4292 retval = -1;
4293 goto exit_options;
4294 }
4295
4296 ret = utils_mkdir_recursive(opt_output_path, S_IRWXU | S_IRWXG,
4297 -1, -1);
4298 if (ret < 0) {
4299 ERR("Unable to create %s", opt_output_path);
4300 retval = -1;
4301 goto exit_options;
4302 }
4303 }
4304
4305 /* Daemonize */
4306 if (opt_daemon || opt_background) {
4307 ret = lttng_daemonize(&child_ppid, &recv_child_signal,
4308 !opt_background);
4309 if (ret < 0) {
4310 retval = -1;
4311 goto exit_options;
4312 }
4313 }
4314
4315 if (opt_working_directory) {
4316 ret = utils_change_working_directory(opt_working_directory);
4317 if (ret) {
4318 /* All errors are already logged. */
4319 goto exit_options;
4320 }
4321 }
4322
4323 sessiond_trace_chunk_registry = sessiond_trace_chunk_registry_create();
4324 if (!sessiond_trace_chunk_registry) {
4325 ERR("Failed to initialize session daemon trace chunk registry");
4326 retval = -1;
4327 goto exit_options;
4328 }
4329
4330 /*
4331 * The RCU thread registration (and use, through the fd-tracker's
4332 * creation) is done after the daemonization to allow us to not
4333 * deal with liburcu's fork() management as the call RCU needs to
4334 * be restored.
4335 */
4336 rcu_register_thread();
4337 thread_is_rcu_registered = true;
4338
4339 output_path = create_output_path("");
4340 if (!output_path) {
4341 ERR("Failed to get output path");
4342 retval = -1;
4343 goto exit_options;
4344 }
4345 ret = asprintf(&unlinked_file_directory_path, "%s/%s", output_path,
4346 DEFAULT_UNLINKED_FILES_DIRECTORY);
4347 free(output_path);
4348 if (ret < 0) {
4349 ERR("Failed to format unlinked file directory path");
4350 retval = -1;
4351 goto exit_options;
4352 }
4353 the_fd_tracker = fd_tracker_create(
4354 unlinked_file_directory_path, lttng_opt_fd_pool_size);
4355 free(unlinked_file_directory_path);
4356 if (!the_fd_tracker) {
4357 retval = -1;
4358 goto exit_options;
4359 }
4360
4361 ret = track_stdio();
4362 if (ret) {
4363 retval = -1;
4364 goto exit_options;
4365 }
4366
4367 /* Initialize thread health monitoring */
4368 health_relayd = health_app_create(NR_HEALTH_RELAYD_TYPES);
4369 if (!health_relayd) {
4370 PERROR("health_app_create error");
4371 retval = -1;
4372 goto exit_options;
4373 }
4374
4375 /* Create thread quit pipe */
4376 if (init_thread_quit_pipe()) {
4377 retval = -1;
4378 goto exit_options;
4379 }
4380
4381 /* Setup the thread apps communication pipe. */
4382 if (create_relay_conn_pipe()) {
4383 retval = -1;
4384 goto exit_options;
4385 }
4386
4387 /* Init relay command queue. */
4388 cds_wfcq_init(&relay_conn_queue.head, &relay_conn_queue.tail);
4389
4390 /* Initialize communication library */
4391 lttcomm_init();
4392 lttcomm_inet_init();
4393
4394 /* tables of sessions indexed by session ID */
4395 sessions_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
4396 if (!sessions_ht) {
4397 retval = -1;
4398 goto exit_options;
4399 }
4400
4401 /* tables of streams indexed by stream ID */
4402 relay_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
4403 if (!relay_streams_ht) {
4404 retval = -1;
4405 goto exit_options;
4406 }
4407
4408 /* tables of streams indexed by stream ID */
4409 viewer_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
4410 if (!viewer_streams_ht) {
4411 retval = -1;
4412 goto exit_options;
4413 }
4414
4415 ret = init_health_quit_pipe();
4416 if (ret) {
4417 retval = -1;
4418 goto exit_options;
4419 }
4420
4421 /* Create thread to manage the client socket */
4422 ret = pthread_create(&health_thread, default_pthread_attr(),
4423 thread_manage_health, (void *) NULL);
4424 if (ret) {
4425 errno = ret;
4426 PERROR("pthread_create health");
4427 retval = -1;
4428 goto exit_options;
4429 }
4430
4431 /* Setup the dispatcher thread */
4432 ret = pthread_create(&dispatcher_thread, default_pthread_attr(),
4433 relay_thread_dispatcher, (void *) NULL);
4434 if (ret) {
4435 errno = ret;
4436 PERROR("pthread_create dispatcher");
4437 retval = -1;
4438 goto exit_dispatcher_thread;
4439 }
4440
4441 /* Setup the worker thread */
4442 ret = pthread_create(&worker_thread, default_pthread_attr(),
4443 relay_thread_worker, NULL);
4444 if (ret) {
4445 errno = ret;
4446 PERROR("pthread_create worker");
4447 retval = -1;
4448 goto exit_worker_thread;
4449 }
4450
4451 /* Setup the listener thread */
4452 ret = pthread_create(&listener_thread, default_pthread_attr(),
4453 relay_thread_listener, (void *) NULL);
4454 if (ret) {
4455 errno = ret;
4456 PERROR("pthread_create listener");
4457 retval = -1;
4458 goto exit_listener_thread;
4459 }
4460
4461 ret = relayd_live_create(live_uri);
4462 if (ret) {
4463 ERR("Starting live viewer threads");
4464 retval = -1;
4465 goto exit_live;
4466 }
4467
4468 /*
4469 * This is where we start awaiting program completion (e.g. through
4470 * signal that asks threads to teardown).
4471 */
4472
4473 ret = relayd_live_join();
4474 if (ret) {
4475 retval = -1;
4476 }
4477 exit_live:
4478
4479 ret = pthread_join(listener_thread, &status);
4480 if (ret) {
4481 errno = ret;
4482 PERROR("pthread_join listener_thread");
4483 retval = -1;
4484 }
4485
4486 exit_listener_thread:
4487 ret = pthread_join(worker_thread, &status);
4488 if (ret) {
4489 errno = ret;
4490 PERROR("pthread_join worker_thread");
4491 retval = -1;
4492 }
4493
4494 exit_worker_thread:
4495 ret = pthread_join(dispatcher_thread, &status);
4496 if (ret) {
4497 errno = ret;
4498 PERROR("pthread_join dispatcher_thread");
4499 retval = -1;
4500 }
4501 exit_dispatcher_thread:
4502
4503 ret = pthread_join(health_thread, &status);
4504 if (ret) {
4505 errno = ret;
4506 PERROR("pthread_join health_thread");
4507 retval = -1;
4508 }
4509 exit_options:
4510 /*
4511 * Wait for all pending call_rcu work to complete before tearing
4512 * down data structures. call_rcu worker may be trying to
4513 * perform lookups in those structures.
4514 */
4515 rcu_barrier();
4516 relayd_cleanup();
4517
4518 /* Ensure all prior call_rcu are done. */
4519 rcu_barrier();
4520
4521 if (thread_is_rcu_registered) {
4522 rcu_unregister_thread();
4523 }
4524
4525 if (!retval) {
4526 exit(EXIT_SUCCESS);
4527 } else {
4528 exit(EXIT_FAILURE);
4529 }
4530 }
This page took 0.133563 seconds and 4 git commands to generate.