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