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