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