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