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