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