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