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