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