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