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