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