Fix: relayd comm: improperly packed rotate streams command header
[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
MD
1761 if (stream->is_metadata) {
1762 struct relay_viewer_stream *vstream;
173af62f 1763
7591bab1
MD
1764 vstream = viewer_stream_get_by_id(stream->stream_handle);
1765 if (vstream) {
94f73d08 1766 if (stream->no_new_metadata_notified) {
7591bab1
MD
1767 /*
1768 * Since all the metadata has been sent to the
1769 * viewer and that we have a request to close
1770 * its stream, we can safely teardown the
1771 * corresponding metadata viewer stream.
1772 */
1773 viewer_stream_put(vstream);
1774 }
1775 /* Put local reference. */
1776 viewer_stream_put(vstream);
1777 }
1778 }
7591bab1 1779 stream_put(stream);
5312a3ed 1780 ret = 0;
173af62f 1781
7591bab1 1782end:
53efb85a 1783 memset(&reply, 0, sizeof(reply));
173af62f 1784 if (ret < 0) {
f73fabfd 1785 reply.ret_code = htobe32(LTTNG_ERR_UNK);
173af62f 1786 } else {
f73fabfd 1787 reply.ret_code = htobe32(LTTNG_OK);
173af62f 1788 }
58eb9381 1789 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
173af62f 1790 sizeof(struct lttcomm_relayd_generic_reply), 0);
5312a3ed
JG
1791 if (send_ret < (ssize_t) sizeof(reply)) {
1792 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1793 send_ret);
1794 ret = -1;
173af62f
DG
1795 }
1796
1797end_no_session:
1798 return ret;
1799}
1800
93ec662e
JD
1801/*
1802 * relay_reset_metadata: reset a metadata stream
1803 */
1804static
5312a3ed
JG
1805int relay_reset_metadata(const struct lttcomm_relayd_hdr *recv_hdr,
1806 struct relay_connection *conn,
1807 const struct lttng_buffer_view *payload)
93ec662e 1808{
5312a3ed
JG
1809 int ret;
1810 ssize_t send_ret;
93ec662e
JD
1811 struct relay_session *session = conn->session;
1812 struct lttcomm_relayd_reset_metadata stream_info;
1813 struct lttcomm_relayd_generic_reply reply;
1814 struct relay_stream *stream;
1815
1816 DBG("Reset metadata received");
1817
5312a3ed 1818 if (!session || !conn->version_check_done) {
93ec662e
JD
1819 ERR("Trying to reset a metadata stream before version check");
1820 ret = -1;
1821 goto end_no_session;
1822 }
1823
5312a3ed
JG
1824 if (payload->size < sizeof(stream_info)) {
1825 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1826 sizeof(stream_info), payload->size);
93ec662e
JD
1827 ret = -1;
1828 goto end_no_session;
1829 }
5312a3ed
JG
1830 memcpy(&stream_info, payload->data, sizeof(stream_info));
1831 stream_info.stream_id = be64toh(stream_info.stream_id);
1832 stream_info.version = be64toh(stream_info.version);
1833
1834 DBG("Update metadata to version %" PRIu64, stream_info.version);
93ec662e
JD
1835
1836 /* Unsupported for live sessions for now. */
1837 if (session->live_timer != 0) {
1838 ret = -1;
1839 goto end;
1840 }
1841
5312a3ed 1842 stream = stream_get_by_id(stream_info.stream_id);
93ec662e
JD
1843 if (!stream) {
1844 ret = -1;
1845 goto end;
1846 }
1847 pthread_mutex_lock(&stream->lock);
1848 if (!stream->is_metadata) {
1849 ret = -1;
1850 goto end_unlock;
1851 }
1852
c35f9726 1853 ret = stream_reset_file(stream);
93ec662e 1854 if (ret < 0) {
c35f9726
JG
1855 ERR("Failed to reset metadata stream %" PRIu64
1856 ": stream_path = %s, channel = %s",
1857 stream->stream_handle, stream->path_name,
1858 stream->channel_name);
93ec662e
JD
1859 goto end_unlock;
1860 }
93ec662e
JD
1861end_unlock:
1862 pthread_mutex_unlock(&stream->lock);
1863 stream_put(stream);
1864
1865end:
1866 memset(&reply, 0, sizeof(reply));
1867 if (ret < 0) {
1868 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1869 } else {
1870 reply.ret_code = htobe32(LTTNG_OK);
1871 }
1872 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1873 sizeof(struct lttcomm_relayd_generic_reply), 0);
5312a3ed
JG
1874 if (send_ret < (ssize_t) sizeof(reply)) {
1875 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1876 send_ret);
1877 ret = -1;
93ec662e
JD
1878 }
1879
1880end_no_session:
1881 return ret;
1882}
1883
b8aa1682
JD
1884/*
1885 * relay_unknown_command: send -1 if received unknown command
1886 */
7591bab1 1887static void relay_unknown_command(struct relay_connection *conn)
b8aa1682
JD
1888{
1889 struct lttcomm_relayd_generic_reply reply;
5312a3ed 1890 ssize_t send_ret;
b8aa1682 1891
53efb85a 1892 memset(&reply, 0, sizeof(reply));
f73fabfd 1893 reply.ret_code = htobe32(LTTNG_ERR_UNK);
5312a3ed
JG
1894 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1895 if (send_ret < sizeof(reply)) {
1896 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret);
b8aa1682
JD
1897 }
1898}
1899
1900/*
1901 * relay_start: send an acknowledgment to the client to tell if we are
1902 * ready to receive data. We are ready if a session is established.
1903 */
5312a3ed
JG
1904static int relay_start(const struct lttcomm_relayd_hdr *recv_hdr,
1905 struct relay_connection *conn,
1906 const struct lttng_buffer_view *payload)
b8aa1682 1907{
5312a3ed
JG
1908 int ret = 0;
1909 ssize_t send_ret;
b8aa1682 1910 struct lttcomm_relayd_generic_reply reply;
58eb9381 1911 struct relay_session *session = conn->session;
b8aa1682
JD
1912
1913 if (!session) {
1914 DBG("Trying to start the streaming without a session established");
f73fabfd 1915 ret = htobe32(LTTNG_ERR_UNK);
b8aa1682
JD
1916 }
1917
53efb85a 1918 memset(&reply, 0, sizeof(reply));
5312a3ed
JG
1919 reply.ret_code = htobe32(LTTNG_OK);
1920 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1921 sizeof(reply), 0);
1922 if (send_ret < (ssize_t) sizeof(reply)) {
1923 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1924 send_ret);
1925 ret = -1;
b8aa1682
JD
1926 }
1927
1928 return ret;
1929}
1930
b8aa1682 1931/*
7591bab1 1932 * relay_recv_metadata: receive the metadata for the session.
b8aa1682 1933 */
5312a3ed
JG
1934static int relay_recv_metadata(const struct lttcomm_relayd_hdr *recv_hdr,
1935 struct relay_connection *conn,
1936 const struct lttng_buffer_view *payload)
b8aa1682 1937{
32d1569c 1938 int ret = 0;
58eb9381 1939 struct relay_session *session = conn->session;
5312a3ed 1940 struct lttcomm_relayd_metadata_payload metadata_payload_header;
b8aa1682 1941 struct relay_stream *metadata_stream;
5312a3ed 1942 uint64_t metadata_payload_size;
c35f9726 1943 struct lttng_buffer_view packet_view;
b8aa1682
JD
1944
1945 if (!session) {
1946 ERR("Metadata sent before version check");
1947 ret = -1;
1948 goto end;
1949 }
1950
5312a3ed 1951 if (recv_hdr->data_size < sizeof(struct lttcomm_relayd_metadata_payload)) {
f6416125
MD
1952 ERR("Incorrect data size");
1953 ret = -1;
1954 goto end;
1955 }
5312a3ed
JG
1956 metadata_payload_size = recv_hdr->data_size -
1957 sizeof(struct lttcomm_relayd_metadata_payload);
f6416125 1958
5312a3ed
JG
1959 memcpy(&metadata_payload_header, payload->data,
1960 sizeof(metadata_payload_header));
1961 metadata_payload_header.stream_id = be64toh(
1962 metadata_payload_header.stream_id);
1963 metadata_payload_header.padding_size = be32toh(
1964 metadata_payload_header.padding_size);
9d1bbf21 1965
5312a3ed 1966 metadata_stream = stream_get_by_id(metadata_payload_header.stream_id);
b8aa1682
JD
1967 if (!metadata_stream) {
1968 ret = -1;
7591bab1 1969 goto end;
b8aa1682
JD
1970 }
1971
c35f9726
JG
1972 packet_view = lttng_buffer_view_from_view(payload,
1973 sizeof(metadata_payload_header), metadata_payload_size);
3e6e0df2 1974 if (!lttng_buffer_view_is_valid(&packet_view)) {
c35f9726 1975 ERR("Invalid metadata packet length announced by header");
b8aa1682 1976 ret = -1;
7591bab1 1977 goto end_put;
b8aa1682 1978 }
1d4dfdef 1979
c35f9726
JG
1980 pthread_mutex_lock(&metadata_stream->lock);
1981 ret = stream_write(metadata_stream, &packet_view,
5312a3ed 1982 metadata_payload_header.padding_size);
c35f9726
JG
1983 pthread_mutex_unlock(&metadata_stream->lock);
1984 if (ret){
5312a3ed 1985 ret = -1;
7591bab1 1986 goto end_put;
1d4dfdef 1987 }
7591bab1 1988end_put:
7591bab1 1989 stream_put(metadata_stream);
b8aa1682
JD
1990end:
1991 return ret;
1992}
1993
1994/*
1995 * relay_send_version: send relayd version number
1996 */
5312a3ed
JG
1997static int relay_send_version(const struct lttcomm_relayd_hdr *recv_hdr,
1998 struct relay_connection *conn,
1999 const struct lttng_buffer_view *payload)
b8aa1682 2000{
7f51dcba 2001 int ret;
5312a3ed 2002 ssize_t send_ret;
092b6259 2003 struct lttcomm_relayd_version reply, msg;
87cb6359 2004 bool compatible = true;
b8aa1682 2005
5312a3ed 2006 conn->version_check_done = true;
b8aa1682 2007
092b6259 2008 /* Get version from the other side. */
5312a3ed
JG
2009 if (payload->size < sizeof(msg)) {
2010 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
2011 sizeof(msg), payload->size);
092b6259 2012 ret = -1;
092b6259
DG
2013 goto end;
2014 }
2015
5312a3ed
JG
2016 memcpy(&msg, payload->data, sizeof(msg));
2017 msg.major = be32toh(msg.major);
2018 msg.minor = be32toh(msg.minor);
2019
53efb85a 2020 memset(&reply, 0, sizeof(reply));
d83a952c
MD
2021 reply.major = RELAYD_VERSION_COMM_MAJOR;
2022 reply.minor = RELAYD_VERSION_COMM_MINOR;
d4519fa3
JD
2023
2024 /* Major versions must be the same */
5312a3ed 2025 if (reply.major != msg.major) {
6151a90f 2026 DBG("Incompatible major versions (%u vs %u), deleting session",
5312a3ed 2027 reply.major, msg.major);
87cb6359 2028 compatible = false;
d4519fa3
JD
2029 }
2030
58eb9381 2031 conn->major = reply.major;
0f907de1 2032 /* We adapt to the lowest compatible version */
5312a3ed 2033 if (reply.minor <= msg.minor) {
58eb9381 2034 conn->minor = reply.minor;
0f907de1 2035 } else {
5312a3ed 2036 conn->minor = msg.minor;
0f907de1
JD
2037 }
2038
6151a90f
JD
2039 reply.major = htobe32(reply.major);
2040 reply.minor = htobe32(reply.minor);
5312a3ed
JG
2041 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
2042 sizeof(reply), 0);
2043 if (send_ret < (ssize_t) sizeof(reply)) {
2044 ERR("Failed to send \"send version\" command reply (ret = %zd)",
2045 send_ret);
2046 ret = -1;
2047 goto end;
2048 } else {
2049 ret = 0;
6151a90f
JD
2050 }
2051
87cb6359
JD
2052 if (!compatible) {
2053 ret = -1;
2054 goto end;
2055 }
2056
58eb9381
DG
2057 DBG("Version check done using protocol %u.%u", conn->major,
2058 conn->minor);
b8aa1682
JD
2059
2060end:
2061 return ret;
2062}
2063
c8f59ee5 2064/*
6d805429 2065 * Check for data pending for a given stream id from the session daemon.
c8f59ee5 2066 */
5312a3ed
JG
2067static int relay_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
2068 struct relay_connection *conn,
2069 const struct lttng_buffer_view *payload)
c8f59ee5 2070{
58eb9381 2071 struct relay_session *session = conn->session;
6d805429 2072 struct lttcomm_relayd_data_pending msg;
c8f59ee5
DG
2073 struct lttcomm_relayd_generic_reply reply;
2074 struct relay_stream *stream;
5312a3ed 2075 ssize_t send_ret;
c8f59ee5 2076 int ret;
298a25ca 2077 uint64_t stream_seq;
c8f59ee5 2078
6d805429 2079 DBG("Data pending command received");
c8f59ee5 2080
5312a3ed 2081 if (!session || !conn->version_check_done) {
c8f59ee5
DG
2082 ERR("Trying to check for data before version check");
2083 ret = -1;
2084 goto end_no_session;
2085 }
2086
5312a3ed
JG
2087 if (payload->size < sizeof(msg)) {
2088 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
2089 sizeof(msg), payload->size);
c8f59ee5
DG
2090 ret = -1;
2091 goto end_no_session;
2092 }
5312a3ed
JG
2093 memcpy(&msg, payload->data, sizeof(msg));
2094 msg.stream_id = be64toh(msg.stream_id);
2095 msg.last_net_seq_num = be64toh(msg.last_net_seq_num);
c8f59ee5 2096
5312a3ed 2097 stream = stream_get_by_id(msg.stream_id);
de91f48a 2098 if (stream == NULL) {
c8f59ee5 2099 ret = -1;
7591bab1 2100 goto end;
c8f59ee5
DG
2101 }
2102
7591bab1
MD
2103 pthread_mutex_lock(&stream->lock);
2104
298a25ca
JG
2105 if (session_streams_have_index(session)) {
2106 /*
2107 * Ensure that both the index and stream data have been
2108 * flushed up to the requested point.
2109 */
ac497a37 2110 stream_seq = std::min(stream->prev_data_seq, stream->prev_index_seq);
298a25ca 2111 } else {
a8f9f353 2112 stream_seq = stream->prev_data_seq;
298a25ca 2113 }
a8f9f353 2114 DBG("Data pending for stream id %" PRIu64 ": prev_data_seq %" PRIu64
298a25ca
JG
2115 ", prev_index_seq %" PRIu64
2116 ", and last_seq %" PRIu64, msg.stream_id,
a8f9f353 2117 stream->prev_data_seq, stream->prev_index_seq,
298a25ca 2118 msg.last_net_seq_num);
c8f59ee5 2119
33832e64 2120 /* Avoid wrapping issue */
298a25ca 2121 if (((int64_t) (stream_seq - msg.last_net_seq_num)) >= 0) {
6d805429 2122 /* Data has in fact been written and is NOT pending */
c8f59ee5 2123 ret = 0;
6d805429
DG
2124 } else {
2125 /* Data still being streamed thus pending */
2126 ret = 1;
c8f59ee5
DG
2127 }
2128
7591bab1
MD
2129 stream->data_pending_check_done = true;
2130 pthread_mutex_unlock(&stream->lock);
f7079f67 2131
7591bab1
MD
2132 stream_put(stream);
2133end:
c8f59ee5 2134
53efb85a 2135 memset(&reply, 0, sizeof(reply));
c8f59ee5 2136 reply.ret_code = htobe32(ret);
5312a3ed
JG
2137 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2138 if (send_ret < (ssize_t) sizeof(reply)) {
2139 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
2140 send_ret);
2141 ret = -1;
c8f59ee5
DG
2142 }
2143
2144end_no_session:
2145 return ret;
2146}
2147
2148/*
2149 * Wait for the control socket to reach a quiescent state.
2150 *
7591bab1
MD
2151 * Note that for now, when receiving this command from the session
2152 * daemon, this means that every subsequent commands or data received on
2153 * the control socket has been handled. So, this is why we simply return
2154 * OK here.
c8f59ee5 2155 */
5312a3ed
JG
2156static int relay_quiescent_control(const struct lttcomm_relayd_hdr *recv_hdr,
2157 struct relay_connection *conn,
2158 const struct lttng_buffer_view *payload)
c8f59ee5
DG
2159{
2160 int ret;
5312a3ed 2161 ssize_t send_ret;
ad7051c0 2162 struct relay_stream *stream;
ad7051c0 2163 struct lttcomm_relayd_quiescent_control msg;
c8f59ee5
DG
2164 struct lttcomm_relayd_generic_reply reply;
2165
2166 DBG("Checking quiescent state on control socket");
2167
5312a3ed 2168 if (!conn->session || !conn->version_check_done) {
ad7051c0
DG
2169 ERR("Trying to check for data before version check");
2170 ret = -1;
2171 goto end_no_session;
2172 }
2173
5312a3ed
JG
2174 if (payload->size < sizeof(msg)) {
2175 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2176 sizeof(msg), payload->size);
ad7051c0
DG
2177 ret = -1;
2178 goto end_no_session;
2179 }
5312a3ed
JG
2180 memcpy(&msg, payload->data, sizeof(msg));
2181 msg.stream_id = be64toh(msg.stream_id);
ad7051c0 2182
5312a3ed 2183 stream = stream_get_by_id(msg.stream_id);
7591bab1
MD
2184 if (!stream) {
2185 goto reply;
2186 }
2187 pthread_mutex_lock(&stream->lock);
2188 stream->data_pending_check_done = true;
2189 pthread_mutex_unlock(&stream->lock);
5312a3ed
JG
2190
2191 DBG("Relay quiescent control pending flag set to %" PRIu64, msg.stream_id);
7591bab1
MD
2192 stream_put(stream);
2193reply:
53efb85a 2194 memset(&reply, 0, sizeof(reply));
c8f59ee5 2195 reply.ret_code = htobe32(LTTNG_OK);
5312a3ed
JG
2196 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2197 if (send_ret < (ssize_t) sizeof(reply)) {
2198 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
2199 send_ret);
2200 ret = -1;
2201 } else {
2202 ret = 0;
c8f59ee5
DG
2203 }
2204
ad7051c0 2205end_no_session:
c8f59ee5
DG
2206 return ret;
2207}
2208
f7079f67 2209/*
7591bab1
MD
2210 * Initialize a data pending command. This means that a consumer is about
2211 * to ask for data pending for each stream it holds. Simply iterate over
2212 * all streams of a session and set the data_pending_check_done flag.
f7079f67
DG
2213 *
2214 * This command returns to the client a LTTNG_OK code.
2215 */
5312a3ed
JG
2216static int relay_begin_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
2217 struct relay_connection *conn,
2218 const struct lttng_buffer_view *payload)
f7079f67
DG
2219{
2220 int ret;
5312a3ed 2221 ssize_t send_ret;
f7079f67
DG
2222 struct lttng_ht_iter iter;
2223 struct lttcomm_relayd_begin_data_pending msg;
2224 struct lttcomm_relayd_generic_reply reply;
2225 struct relay_stream *stream;
f7079f67 2226
a0377dfe
FD
2227 LTTNG_ASSERT(recv_hdr);
2228 LTTNG_ASSERT(conn);
f7079f67
DG
2229
2230 DBG("Init streams for data pending");
2231
5312a3ed 2232 if (!conn->session || !conn->version_check_done) {
f7079f67
DG
2233 ERR("Trying to check for data before version check");
2234 ret = -1;
2235 goto end_no_session;
2236 }
2237
5312a3ed
JG
2238 if (payload->size < sizeof(msg)) {
2239 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2240 sizeof(msg), payload->size);
f7079f67
DG
2241 ret = -1;
2242 goto end_no_session;
2243 }
5312a3ed
JG
2244 memcpy(&msg, payload->data, sizeof(msg));
2245 msg.session_id = be64toh(msg.session_id);
f7079f67
DG
2246
2247 /*
7591bab1
MD
2248 * Iterate over all streams to set the begin data pending flag.
2249 * For now, the streams are indexed by stream handle so we have
2250 * to iterate over all streams to find the one associated with
2251 * the right session_id.
f7079f67
DG
2252 */
2253 rcu_read_lock();
d3e2ba59 2254 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2a174661 2255 node.node) {
7591bab1
MD
2256 if (!stream_get(stream)) {
2257 continue;
2258 }
5312a3ed 2259 if (stream->trace->session->id == msg.session_id) {
7591bab1
MD
2260 pthread_mutex_lock(&stream->lock);
2261 stream->data_pending_check_done = false;
2262 pthread_mutex_unlock(&stream->lock);
f7079f67
DG
2263 DBG("Set begin data pending flag to stream %" PRIu64,
2264 stream->stream_handle);
2265 }
7591bab1 2266 stream_put(stream);
f7079f67
DG
2267 }
2268 rcu_read_unlock();
2269
53efb85a 2270 memset(&reply, 0, sizeof(reply));
f7079f67
DG
2271 /* All good, send back reply. */
2272 reply.ret_code = htobe32(LTTNG_OK);
2273
5312a3ed
JG
2274 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2275 if (send_ret < (ssize_t) sizeof(reply)) {
2276 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2277 send_ret);
2278 ret = -1;
2279 } else {
2280 ret = 0;
f7079f67
DG
2281 }
2282
2283end_no_session:
2284 return ret;
2285}
2286
2287/*
7591bab1
MD
2288 * End data pending command. This will check, for a given session id, if
2289 * each stream associated with it has its data_pending_check_done flag
2290 * set. If not, this means that the client lost track of the stream but
2291 * the data is still being streamed on our side. In this case, we inform
2292 * the client that data is in flight.
f7079f67
DG
2293 *
2294 * Return to the client if there is data in flight or not with a ret_code.
2295 */
5312a3ed
JG
2296static int relay_end_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
2297 struct relay_connection *conn,
2298 const struct lttng_buffer_view *payload)
f7079f67
DG
2299{
2300 int ret;
5312a3ed 2301 ssize_t send_ret;
f7079f67
DG
2302 struct lttng_ht_iter iter;
2303 struct lttcomm_relayd_end_data_pending msg;
2304 struct lttcomm_relayd_generic_reply reply;
2305 struct relay_stream *stream;
f7079f67
DG
2306 uint32_t is_data_inflight = 0;
2307
f7079f67
DG
2308 DBG("End data pending command");
2309
5312a3ed 2310 if (!conn->session || !conn->version_check_done) {
f7079f67
DG
2311 ERR("Trying to check for data before version check");
2312 ret = -1;
2313 goto end_no_session;
2314 }
2315
5312a3ed
JG
2316 if (payload->size < sizeof(msg)) {
2317 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2318 sizeof(msg), payload->size);
f7079f67
DG
2319 ret = -1;
2320 goto end_no_session;
2321 }
5312a3ed
JG
2322 memcpy(&msg, payload->data, sizeof(msg));
2323 msg.session_id = be64toh(msg.session_id);
f7079f67 2324
7591bab1
MD
2325 /*
2326 * Iterate over all streams to see if the begin data pending
2327 * flag is set.
2328 */
f7079f67 2329 rcu_read_lock();
d3e2ba59 2330 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2a174661 2331 node.node) {
7591bab1
MD
2332 if (!stream_get(stream)) {
2333 continue;
2334 }
5312a3ed 2335 if (stream->trace->session->id != msg.session_id) {
7591bab1
MD
2336 stream_put(stream);
2337 continue;
2338 }
2339 pthread_mutex_lock(&stream->lock);
2340 if (!stream->data_pending_check_done) {
298a25ca
JG
2341 uint64_t stream_seq;
2342
2343 if (session_streams_have_index(conn->session)) {
2344 /*
2345 * Ensure that both the index and stream data have been
2346 * flushed up to the requested point.
2347 */
ac497a37 2348 stream_seq = std::min(stream->prev_data_seq, stream->prev_index_seq);
298a25ca 2349 } else {
a8f9f353 2350 stream_seq = stream->prev_data_seq;
298a25ca
JG
2351 }
2352 if (!stream->closed || !(((int64_t) (stream_seq - stream->last_net_seq_num)) >= 0)) {
7591bab1
MD
2353 is_data_inflight = 1;
2354 DBG("Data is still in flight for stream %" PRIu64,
2355 stream->stream_handle);
2356 pthread_mutex_unlock(&stream->lock);
2357 stream_put(stream);
2358 break;
2359 }
f7079f67 2360 }
7591bab1
MD
2361 pthread_mutex_unlock(&stream->lock);
2362 stream_put(stream);
f7079f67
DG
2363 }
2364 rcu_read_unlock();
2365
53efb85a 2366 memset(&reply, 0, sizeof(reply));
f7079f67
DG
2367 /* All good, send back reply. */
2368 reply.ret_code = htobe32(is_data_inflight);
2369
5312a3ed
JG
2370 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2371 if (send_ret < (ssize_t) sizeof(reply)) {
2372 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2373 send_ret);
2374 ret = -1;
2375 } else {
2376 ret = 0;
f7079f67
DG
2377 }
2378
2379end_no_session:
2380 return ret;
2381}
2382
1c20f0e2
JD
2383/*
2384 * Receive an index for a specific stream.
2385 *
2386 * Return 0 on success else a negative value.
2387 */
5312a3ed
JG
2388static int relay_recv_index(const struct lttcomm_relayd_hdr *recv_hdr,
2389 struct relay_connection *conn,
2390 const struct lttng_buffer_view *payload)
1c20f0e2 2391{
5312a3ed
JG
2392 int ret;
2393 ssize_t send_ret;
58eb9381 2394 struct relay_session *session = conn->session;
1c20f0e2 2395 struct lttcomm_relayd_index index_info;
1c20f0e2
JD
2396 struct lttcomm_relayd_generic_reply reply;
2397 struct relay_stream *stream;
f8f3885c 2398 size_t msg_len;
1c20f0e2 2399
a0377dfe 2400 LTTNG_ASSERT(conn);
1c20f0e2
JD
2401
2402 DBG("Relay receiving index");
2403
5312a3ed 2404 if (!session || !conn->version_check_done) {
1c20f0e2
JD
2405 ERR("Trying to close a stream before version check");
2406 ret = -1;
2407 goto end_no_session;
2408 }
2409
f8f3885c
MD
2410 msg_len = lttcomm_relayd_index_len(
2411 lttng_to_index_major(conn->major, conn->minor),
2412 lttng_to_index_minor(conn->major, conn->minor));
5312a3ed
JG
2413 if (payload->size < msg_len) {
2414 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2415 msg_len, payload->size);
1c20f0e2
JD
2416 ret = -1;
2417 goto end_no_session;
2418 }
5312a3ed
JG
2419 memcpy(&index_info, payload->data, msg_len);
2420 index_info.relay_stream_id = be64toh(index_info.relay_stream_id);
2421 index_info.net_seq_num = be64toh(index_info.net_seq_num);
2422 index_info.packet_size = be64toh(index_info.packet_size);
2423 index_info.content_size = be64toh(index_info.content_size);
2424 index_info.timestamp_begin = be64toh(index_info.timestamp_begin);
2425 index_info.timestamp_end = be64toh(index_info.timestamp_end);
2426 index_info.events_discarded = be64toh(index_info.events_discarded);
2427 index_info.stream_id = be64toh(index_info.stream_id);
81df238b
JR
2428
2429 if (conn->minor >= 8) {
2430 index_info.stream_instance_id =
2431 be64toh(index_info.stream_instance_id);
2432 index_info.packet_seq_num = be64toh(index_info.packet_seq_num);
0f83d1cc
MD
2433 } else {
2434 index_info.stream_instance_id = -1ULL;
2435 index_info.packet_seq_num = -1ULL;
81df238b 2436 }
5312a3ed
JG
2437
2438 stream = stream_get_by_id(index_info.relay_stream_id);
1c20f0e2 2439 if (!stream) {
7591bab1 2440 ERR("stream_get_by_id not found");
1c20f0e2 2441 ret = -1;
7591bab1 2442 goto end;
1c20f0e2 2443 }
d3e2ba59 2444
c35f9726
JG
2445 pthread_mutex_lock(&stream->lock);
2446 ret = stream_add_index(stream, &index_info);
2447 pthread_mutex_unlock(&stream->lock);
2448 if (ret) {
7591bab1
MD
2449 goto end_stream_put;
2450 }
1c20f0e2 2451
7591bab1 2452end_stream_put:
7591bab1 2453 stream_put(stream);
7591bab1 2454end:
53efb85a 2455 memset(&reply, 0, sizeof(reply));
1c20f0e2
JD
2456 if (ret < 0) {
2457 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2458 } else {
2459 reply.ret_code = htobe32(LTTNG_OK);
2460 }
58eb9381 2461 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
5312a3ed
JG
2462 if (send_ret < (ssize_t) sizeof(reply)) {
2463 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret);
2464 ret = -1;
1c20f0e2
JD
2465 }
2466
2467end_no_session:
2468 return ret;
2469}
2470
a4baae1b
JD
2471/*
2472 * Receive the streams_sent message.
2473 *
2474 * Return 0 on success else a negative value.
2475 */
5312a3ed
JG
2476static int relay_streams_sent(const struct lttcomm_relayd_hdr *recv_hdr,
2477 struct relay_connection *conn,
2478 const struct lttng_buffer_view *payload)
a4baae1b 2479{
5312a3ed
JG
2480 int ret;
2481 ssize_t send_ret;
a4baae1b
JD
2482 struct lttcomm_relayd_generic_reply reply;
2483
a0377dfe 2484 LTTNG_ASSERT(conn);
a4baae1b
JD
2485
2486 DBG("Relay receiving streams_sent");
2487
5312a3ed 2488 if (!conn->session || !conn->version_check_done) {
a4baae1b
JD
2489 ERR("Trying to close a stream before version check");
2490 ret = -1;
2491 goto end_no_session;
2492 }
2493
2494 /*
7591bab1
MD
2495 * Publish every pending stream in the connection recv list which are
2496 * now ready to be used by the viewer.
4a9daf17 2497 */
7591bab1 2498 publish_connection_local_streams(conn);
4a9daf17 2499
53efb85a 2500 memset(&reply, 0, sizeof(reply));
a4baae1b 2501 reply.ret_code = htobe32(LTTNG_OK);
58eb9381 2502 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
5312a3ed
JG
2503 if (send_ret < (ssize_t) sizeof(reply)) {
2504 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2505 send_ret);
2506 ret = -1;
a4baae1b
JD
2507 } else {
2508 /* Success. */
2509 ret = 0;
2510 }
2511
2512end_no_session:
2513 return ret;
2514}
2515
ce9dbd47
JG
2516static ssize_t relay_unpack_rotate_streams_header(
2517 const struct lttng_buffer_view *payload,
2518 struct lttcomm_relayd_rotate_streams *_rotate_streams)
2519{
2520 struct lttcomm_relayd_rotate_streams rotate_streams;
2521 /*
2522 * Set to the smallest version (packed) of `lttcomm_relayd_rotate_streams`.
2523 * This is the smallest version of this structure, but it can be larger;
2524 * this variable is updated once the proper size of the structure is known.
2525 *
2526 * See comment at the declaration of this structure for more information.
2527 */
2528 ssize_t header_len = sizeof(struct lttcomm_relayd_rotate_streams_packed);
2529 size_t expected_payload_size_no_padding,
2530 expected_payload_size_3_bytes_padding,
2531 expected_payload_size_7_bytes_padding;
2532
2533 if (payload->size < header_len) {
2534 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2535 header_len, payload->size);
2536 goto error;
2537 }
2538
2539 /*
2540 * Some versions incorrectly omitted the LTTNG_PACKED annotation on the
2541 * `new_chunk_id` optional field of struct lttcomm_relayd_rotate_streams.
2542 *
2543 * We start by "unpacking" `stream_count` to figure out the padding length
2544 * emited by our peer.
2545 */
2546 memcpy(&rotate_streams.stream_count, payload->data,
2547 sizeof(rotate_streams.stream_count));
2548 rotate_streams = (typeof(rotate_streams)) {
2549 .stream_count = be32toh(rotate_streams.stream_count),
2550 };
2551
2552 /*
2553 * Payload size expected given the possible padding lengths in
2554 * `struct lttcomm_relayd_rotate_streams`.
2555 */
2556 expected_payload_size_no_padding = (rotate_streams.stream_count *
2557 sizeof(*rotate_streams.rotation_positions)) +
2558 sizeof(lttcomm_relayd_rotate_streams_packed);
2559 expected_payload_size_3_bytes_padding = (rotate_streams.stream_count *
2560 sizeof(*rotate_streams.rotation_positions)) +
2561 sizeof(lttcomm_relayd_rotate_streams_3_bytes_padding);
2562 expected_payload_size_7_bytes_padding = (rotate_streams.stream_count *
2563 sizeof(*rotate_streams.rotation_positions)) +
2564 sizeof(lttcomm_relayd_rotate_streams_7_bytes_padding);
2565
2566 if (payload->size == expected_payload_size_no_padding) {
2567 struct lttcomm_relayd_rotate_streams_packed packed_rotate_streams;
2568
2569 /*
2570 * This handles cases where someone might build with
2571 * -fpack-struct or any other toolchain that wouldn't produce
2572 * padding to align `value`.
2573 */
2574 DBG("Received `struct lttcomm_relayd_rotate_streams` with no padding");
2575
2576 header_len = sizeof(packed_rotate_streams);
2577 memcpy(&packed_rotate_streams, payload->data, header_len);
2578
2579 /* Unpack the packed structure to the natively-packed version. */
2580 *_rotate_streams = (typeof(*_rotate_streams)) {
2581 .stream_count = be32toh(packed_rotate_streams.stream_count),
2582 .new_chunk_id = (typeof(_rotate_streams->new_chunk_id)) {
2583 .is_set = !!packed_rotate_streams.new_chunk_id.is_set,
2584 .value = be64toh(packed_rotate_streams.new_chunk_id.value),
2585 }
2586 };
2587 } else if (payload->size == expected_payload_size_3_bytes_padding) {
2588 struct lttcomm_relayd_rotate_streams_3_bytes_padding padded_rotate_streams;
2589
2590 DBG("Received `struct lttcomm_relayd_rotate_streams` with 3 bytes of padding (4-byte aligned peer)");
2591
2592 header_len = sizeof(padded_rotate_streams);
2593 memcpy(&padded_rotate_streams, payload->data, header_len);
2594
2595 /* Unpack the 3-byte padded structure to the natively-packed version. */
2596 *_rotate_streams = (typeof(*_rotate_streams)) {
2597 .stream_count = be32toh(padded_rotate_streams.stream_count),
2598 .new_chunk_id = (typeof(_rotate_streams->new_chunk_id)) {
2599 .is_set = !!padded_rotate_streams.new_chunk_id.is_set,
2600 .value = be64toh(padded_rotate_streams.new_chunk_id.value),
2601 }
2602 };
2603 } else if (payload->size == expected_payload_size_7_bytes_padding) {
2604 struct lttcomm_relayd_rotate_streams_7_bytes_padding padded_rotate_streams;
2605
2606 DBG("Received `struct lttcomm_relayd_rotate_streams` with 7 bytes of padding (8-byte aligned peer)");
2607
2608 header_len = sizeof(padded_rotate_streams);
2609 memcpy(&padded_rotate_streams, payload->data, header_len);
2610
2611 /* Unpack the 7-byte padded structure to the natively-packed version. */
2612 *_rotate_streams = (typeof(*_rotate_streams)) {
2613 .stream_count = be32toh(padded_rotate_streams.stream_count),
2614 .new_chunk_id = (typeof(_rotate_streams->new_chunk_id)) {
2615 .is_set = !!padded_rotate_streams.new_chunk_id.is_set,
2616 .value = be64toh(padded_rotate_streams.new_chunk_id.value),
2617 }
2618 };
2619
2620 header_len = sizeof(padded_rotate_streams);
2621 } else {
2622 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected %zu, %zu or %zu bytes, got %zu bytes",
2623 expected_payload_size_no_padding,
2624 expected_payload_size_3_bytes_padding,
2625 expected_payload_size_7_bytes_padding,
2626 payload->size);
2627 goto error;
2628 }
2629
2630 return header_len;
2631error:
2632 return -1;
2633}
2634
d3ecc550 2635/*
c35f9726
JG
2636 * relay_rotate_session_stream: rotate a stream to a new tracefile for the
2637 * session rotation feature (not the tracefile rotation feature).
d3ecc550 2638 */
c35f9726
JG
2639static int relay_rotate_session_streams(
2640 const struct lttcomm_relayd_hdr *recv_hdr,
5312a3ed
JG
2641 struct relay_connection *conn,
2642 const struct lttng_buffer_view *payload)
d3ecc550 2643{
30b9d5ab 2644 int ret = 0;
c35f9726 2645 uint32_t i;
5312a3ed 2646 ssize_t send_ret;
c35f9726 2647 enum lttng_error_code reply_code = LTTNG_ERR_UNK;
d3ecc550 2648 struct relay_session *session = conn->session;
c35f9726
JG
2649 struct lttcomm_relayd_rotate_streams rotate_streams;
2650 struct lttcomm_relayd_generic_reply reply = {};
2651 struct relay_stream *stream = NULL;
c35f9726
JG
2652 struct lttng_trace_chunk *next_trace_chunk = NULL;
2653 struct lttng_buffer_view stream_positions;
70626904
JG
2654 char chunk_id_buf[MAX_INT_DEC_LEN(uint64_t)];
2655 const char *chunk_id_str = "none";
ce9dbd47 2656 ssize_t header_len;
d3ecc550 2657
d3ecc550
JD
2658 if (!session || !conn->version_check_done) {
2659 ERR("Trying to rotate a stream before version check");
2660 ret = -1;
2661 goto end_no_reply;
2662 }
2663
2664 if (session->major == 2 && session->minor < 11) {
2665 ERR("Unsupported feature before 2.11");
2666 ret = -1;
2667 goto end_no_reply;
2668 }
2669
ce9dbd47
JG
2670 header_len = relay_unpack_rotate_streams_header(payload, &rotate_streams);
2671 if (header_len < 0) {
d3ecc550
JD
2672 ret = -1;
2673 goto end_no_reply;
2674 }
2675
c35f9726
JG
2676 if (rotate_streams.new_chunk_id.is_set) {
2677 /*
2678 * Retrieve the trace chunk the stream must transition to. As
2679 * per the protocol, this chunk should have been created
2680 * before this command is received.
2681 */
2682 next_trace_chunk = sessiond_trace_chunk_registry_get_chunk(
2683 sessiond_trace_chunk_registry,
2684 session->sessiond_uuid, session->id,
2685 rotate_streams.new_chunk_id.value);
2686 if (!next_trace_chunk) {
c70636a7 2687 char uuid_str[LTTNG_UUID_STR_LEN];
c35f9726
JG
2688
2689 lttng_uuid_to_str(session->sessiond_uuid, uuid_str);
2690 ERR("Unknown next trace chunk in ROTATE_STREAMS command: sessiond_uuid = {%s}, session_id = %" PRIu64
2691 ", trace_chunk_id = %" PRIu64,
2692 uuid_str, session->id,
2693 rotate_streams.new_chunk_id.value);
2694 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2695 ret = -1;
2696 goto end;
2697 }
70626904
JG
2698
2699 ret = snprintf(chunk_id_buf, sizeof(chunk_id_buf), "%" PRIu64,
2700 rotate_streams.new_chunk_id.value);
2701 if (ret < 0 || ret >= sizeof(chunk_id_buf)) {
2702 chunk_id_str = "formatting error";
2703 } else {
2704 chunk_id_str = chunk_id_buf;
2705 }
d3ecc550
JD
2706 }
2707
70626904
JG
2708 DBG("Rotate %" PRIu32 " streams of session \"%s\" to chunk \"%s\"",
2709 rotate_streams.stream_count, session->session_name,
2710 chunk_id_str);
2711
c35f9726 2712 stream_positions = lttng_buffer_view_from_view(payload,
ce9dbd47 2713 header_len, -1);
c35f9726
JG
2714 if (!stream_positions.data ||
2715 stream_positions.size <
2716 (rotate_streams.stream_count *
2717 sizeof(struct lttcomm_relayd_stream_rotation_position))) {
2718 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
d3ecc550 2719 ret = -1;
5312a3ed 2720 goto end;
d3ecc550
JD
2721 }
2722
c35f9726
JG
2723 for (i = 0; i < rotate_streams.stream_count; i++) {
2724 struct lttcomm_relayd_stream_rotation_position *position_comm =
2725 &((typeof(position_comm)) stream_positions.data)[i];
2726 const struct lttcomm_relayd_stream_rotation_position pos = {
2727 .stream_id = be64toh(position_comm->stream_id),
2728 .rotate_at_seq_num = be64toh(
2729 position_comm->rotate_at_seq_num),
2730 };
5312a3ed 2731
c35f9726
JG
2732 stream = stream_get_by_id(pos.stream_id);
2733 if (!stream) {
2734 reply_code = LTTNG_ERR_INVALID;
2735 ret = -1;
2736 goto end;
c6db3843
JG
2737 }
2738
c35f9726
JG
2739 pthread_mutex_lock(&stream->lock);
2740 ret = stream_set_pending_rotation(stream, next_trace_chunk,
2741 pos.rotate_at_seq_num);
2742 pthread_mutex_unlock(&stream->lock);
2743 if (ret) {
2744 reply_code = LTTNG_ERR_FILE_CREATION_ERROR;
2745 goto end;
c6db3843 2746 }
c35f9726
JG
2747
2748 stream_put(stream);
2749 stream = NULL;
d3ecc550
JD
2750 }
2751
c35f9726 2752 reply_code = LTTNG_OK;
eaeb64a9 2753 ret = 0;
d3ecc550 2754end:
c35f9726
JG
2755 if (stream) {
2756 stream_put(stream);
d3ecc550 2757 }
c35f9726
JG
2758
2759 reply.ret_code = htobe32((uint32_t) reply_code);
d3ecc550
JD
2760 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
2761 sizeof(struct lttcomm_relayd_generic_reply), 0);
5312a3ed
JG
2762 if (send_ret < (ssize_t) sizeof(reply)) {
2763 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2764 send_ret);
2765 ret = -1;
d3ecc550 2766 }
d3ecc550 2767end_no_reply:
c35f9726 2768 lttng_trace_chunk_put(next_trace_chunk);
d3ecc550
JD
2769 return ret;
2770}
2771
e5add6d0
JG
2772/*
2773 * relay_create_trace_chunk: create a new trace chunk
2774 */
2775static int relay_create_trace_chunk(const struct lttcomm_relayd_hdr *recv_hdr,
2776 struct relay_connection *conn,
2777 const struct lttng_buffer_view *payload)
2778{
2779 int ret = 0;
2780 ssize_t send_ret;
2781 struct relay_session *session = conn->session;
2782 struct lttcomm_relayd_create_trace_chunk *msg;
2783 struct lttcomm_relayd_generic_reply reply = {};
2784 struct lttng_buffer_view header_view;
e5add6d0
JG
2785 struct lttng_trace_chunk *chunk = NULL, *published_chunk = NULL;
2786 enum lttng_error_code reply_code = LTTNG_OK;
2787 enum lttng_trace_chunk_status chunk_status;
a7ceb342 2788 const char *new_path;
e5add6d0
JG
2789
2790 if (!session || !conn->version_check_done) {
2791 ERR("Trying to create a trace chunk before version check");
2792 ret = -1;
2793 goto end_no_reply;
2794 }
2795
2796 if (session->major == 2 && session->minor < 11) {
2797 ERR("Chunk creation command is unsupported before 2.11");
2798 ret = -1;
2799 goto end_no_reply;
2800 }
2801
2802 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
3e6e0df2 2803 if (!lttng_buffer_view_is_valid(&header_view)) {
e5add6d0
JG
2804 ERR("Failed to receive payload of chunk creation command");
2805 ret = -1;
2806 goto end_no_reply;
2807 }
2808
2809 /* Convert to host endianness. */
2810 msg = (typeof(msg)) header_view.data;
2811 msg->chunk_id = be64toh(msg->chunk_id);
2812 msg->creation_timestamp = be64toh(msg->creation_timestamp);
2813 msg->override_name_length = be32toh(msg->override_name_length);
2814
a7ceb342
MD
2815 if (session->current_trace_chunk &&
2816 !lttng_trace_chunk_get_name_overridden(session->current_trace_chunk)) {
2817 chunk_status = lttng_trace_chunk_rename_path(session->current_trace_chunk,
2818 DEFAULT_CHUNK_TMP_OLD_DIRECTORY);
2819 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2820 ERR("Failed to rename old chunk");
2821 ret = -1;
2822 reply_code = LTTNG_ERR_UNK;
2823 goto end;
2824 }
2825 }
2826 session->ongoing_rotation = true;
2827 if (!session->current_trace_chunk) {
2828 if (!session->has_rotated) {
2829 new_path = "";
2830 } else {
2831 new_path = NULL;
2832 }
2833 } else {
2834 new_path = DEFAULT_CHUNK_TMP_NEW_DIRECTORY;
2835 }
e5add6d0 2836 chunk = lttng_trace_chunk_create(
a7ceb342 2837 msg->chunk_id, msg->creation_timestamp, new_path);
e5add6d0
JG
2838 if (!chunk) {
2839 ERR("Failed to create trace chunk in trace chunk creation command");
2840 ret = -1;
2841 reply_code = LTTNG_ERR_NOMEM;
2842 goto end;
2843 }
7145f5e9 2844 lttng_trace_chunk_set_fd_tracker(chunk, the_fd_tracker);
e5add6d0
JG
2845
2846 if (msg->override_name_length) {
2847 const char *name;
3e6e0df2
JG
2848 const struct lttng_buffer_view chunk_name_view =
2849 lttng_buffer_view_from_view(payload,
2850 sizeof(*msg),
2851 msg->override_name_length);
2852
2853 if (!lttng_buffer_view_is_valid(&chunk_name_view)) {
2854 ERR("Invalid payload of chunk creation command (protocol error): buffer too short for expected name length");
2855 ret = -1;
2856 reply_code = LTTNG_ERR_INVALID;
2857 goto end;
2858 }
e5add6d0 2859
e5add6d0 2860 name = chunk_name_view.data;
3e6e0df2
JG
2861 if (name[msg->override_name_length - 1]) {
2862 ERR("Invalid payload of chunk creation command (protocol error): name is not null-terminated");
e5add6d0
JG
2863 ret = -1;
2864 reply_code = LTTNG_ERR_INVALID;
2865 goto end;
2866 }
2867
2868 chunk_status = lttng_trace_chunk_override_name(
2869 chunk, chunk_name_view.data);
2870 switch (chunk_status) {
2871 case LTTNG_TRACE_CHUNK_STATUS_OK:
2872 break;
2873 case LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT:
2874 ERR("Failed to set the name of new trace chunk in trace chunk creation command (invalid name)");
2875 reply_code = LTTNG_ERR_INVALID;
2876 ret = -1;
2877 goto end;
2878 default:
2879 ERR("Failed to set the name of new trace chunk in trace chunk creation command (unknown error)");
2880 reply_code = LTTNG_ERR_UNK;
2881 ret = -1;
2882 goto end;
2883 }
2884 }
2885
e5add6d0
JG
2886 chunk_status = lttng_trace_chunk_set_credentials_current_user(chunk);
2887 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2888 reply_code = LTTNG_ERR_UNK;
2889 ret = -1;
2890 goto end;
2891 }
2892
a0377dfe 2893 LTTNG_ASSERT(conn->session->output_directory);
7ceefac4
JG
2894 chunk_status = lttng_trace_chunk_set_as_owner(chunk,
2895 conn->session->output_directory);
e5add6d0
JG
2896 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2897 reply_code = LTTNG_ERR_UNK;
2898 ret = -1;
2899 goto end;
2900 }
2901
2902 published_chunk = sessiond_trace_chunk_registry_publish_chunk(
2903 sessiond_trace_chunk_registry,
2904 conn->session->sessiond_uuid,
2905 conn->session->id,
2906 chunk);
2907 if (!published_chunk) {
c70636a7 2908 char uuid_str[LTTNG_UUID_STR_LEN];
e5add6d0
JG
2909
2910 lttng_uuid_to_str(conn->session->sessiond_uuid, uuid_str);
2911 ERR("Failed to publish chunk: sessiond_uuid = %s, session_id = %" PRIu64 ", chunk_id = %" PRIu64,
2912 uuid_str,
2913 conn->session->id,
2914 msg->chunk_id);
2915 ret = -1;
2916 reply_code = LTTNG_ERR_NOMEM;
2917 goto end;
2918 }
2919
2920 pthread_mutex_lock(&conn->session->lock);
62bad3bf
JG
2921 if (conn->session->pending_closure_trace_chunk) {
2922 /*
2923 * Invalid; this means a second create_trace_chunk command was
2924 * received before a close_trace_chunk.
2925 */
2926 ERR("Invalid trace chunk close command received; a trace chunk is already waiting for a trace chunk close command");
2927 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2928 ret = -1;
2929 goto end_unlock_session;
2930 }
2931 conn->session->pending_closure_trace_chunk =
2932 conn->session->current_trace_chunk;
e5add6d0 2933 conn->session->current_trace_chunk = published_chunk;
e5add6d0 2934 published_chunk = NULL;
a7ceb342
MD
2935 if (!conn->session->pending_closure_trace_chunk) {
2936 session->ongoing_rotation = false;
2937 }
62bad3bf 2938end_unlock_session:
c35f9726 2939 pthread_mutex_unlock(&conn->session->lock);
e5add6d0
JG
2940end:
2941 reply.ret_code = htobe32((uint32_t) reply_code);
2942 send_ret = conn->sock->ops->sendmsg(conn->sock,
2943 &reply,
2944 sizeof(struct lttcomm_relayd_generic_reply),
2945 0);
2946 if (send_ret < (ssize_t) sizeof(reply)) {
2947 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
2948 send_ret);
2949 ret = -1;
2950 }
2951end_no_reply:
2952 lttng_trace_chunk_put(chunk);
2953 lttng_trace_chunk_put(published_chunk);
e5add6d0
JG
2954 return ret;
2955}
2956
bbc4768c
JG
2957/*
2958 * relay_close_trace_chunk: close a trace chunk
2959 */
2960static int relay_close_trace_chunk(const struct lttcomm_relayd_hdr *recv_hdr,
2961 struct relay_connection *conn,
2962 const struct lttng_buffer_view *payload)
2963{
9898f786 2964 int ret = 0, buf_ret;
bbc4768c
JG
2965 ssize_t send_ret;
2966 struct relay_session *session = conn->session;
2967 struct lttcomm_relayd_close_trace_chunk *msg;
ecd1a12f 2968 struct lttcomm_relayd_close_trace_chunk_reply reply = {};
bbc4768c
JG
2969 struct lttng_buffer_view header_view;
2970 struct lttng_trace_chunk *chunk = NULL;
2971 enum lttng_error_code reply_code = LTTNG_OK;
2972 enum lttng_trace_chunk_status chunk_status;
2973 uint64_t chunk_id;
c35f9726 2974 LTTNG_OPTIONAL(enum lttng_trace_chunk_command_type) close_command = {};
bbc4768c 2975 time_t close_timestamp;
ecd1a12f
MD
2976 char closed_trace_chunk_path[LTTNG_PATH_MAX];
2977 size_t path_length = 0;
2978 const char *chunk_name = NULL;
2979 struct lttng_dynamic_buffer reply_payload;
a7ceb342 2980 const char *new_path;
ecd1a12f
MD
2981
2982 lttng_dynamic_buffer_init(&reply_payload);
bbc4768c
JG
2983
2984 if (!session || !conn->version_check_done) {
2985 ERR("Trying to close a trace chunk before version check");
2986 ret = -1;
2987 goto end_no_reply;
2988 }
2989
2990 if (session->major == 2 && session->minor < 11) {
2991 ERR("Chunk close command is unsupported before 2.11");
2992 ret = -1;
2993 goto end_no_reply;
2994 }
2995
2996 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
3e6e0df2 2997 if (!lttng_buffer_view_is_valid(&header_view)) {
bbc4768c
JG
2998 ERR("Failed to receive payload of chunk close command");
2999 ret = -1;
3000 goto end_no_reply;
3001 }
3002
3003 /* Convert to host endianness. */
3004 msg = (typeof(msg)) header_view.data;
3005 chunk_id = be64toh(msg->chunk_id);
3006 close_timestamp = (time_t) be64toh(msg->close_timestamp);
ac497a37
SM
3007 close_command.value = (lttng_trace_chunk_command_type) be32toh(msg->close_command.value);
3008 close_command.is_set = msg->close_command.is_set;
bbc4768c
JG
3009
3010 chunk = sessiond_trace_chunk_registry_get_chunk(
3011 sessiond_trace_chunk_registry,
3012 conn->session->sessiond_uuid,
3013 conn->session->id,
3014 chunk_id);
3015 if (!chunk) {
c70636a7 3016 char uuid_str[LTTNG_UUID_STR_LEN];
bbc4768c
JG
3017
3018 lttng_uuid_to_str(conn->session->sessiond_uuid, uuid_str);
3019 ERR("Failed to find chunk to close: sessiond_uuid = %s, session_id = %" PRIu64 ", chunk_id = %" PRIu64,
3020 uuid_str,
3021 conn->session->id,
3022 msg->chunk_id);
3023 ret = -1;
3024 reply_code = LTTNG_ERR_NOMEM;
3025 goto end;
3026 }
3027
62bad3bf 3028 pthread_mutex_lock(&session->lock);
f77a6ec2
MD
3029 if (close_command.is_set &&
3030 close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE) {
3031 /*
3032 * Clear command. It is a protocol error to ask for a
3033 * clear on a relay which does not allow it. Querying
3034 * the configuration allows figuring out whether
3035 * clearing is allowed before doing the clear.
3036 */
3037 if (!opt_allow_clear) {
3038 ret = -1;
3039 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
3040 goto end_unlock_session;
3041 }
3042 }
62bad3bf
JG
3043 if (session->pending_closure_trace_chunk &&
3044 session->pending_closure_trace_chunk != chunk) {
3045 ERR("Trace chunk close command for session \"%s\" does not target the trace chunk pending closure",
3046 session->session_name);
3047 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
3048 ret = -1;
3049 goto end_unlock_session;
3050 }
3051
a7ceb342
MD
3052 if (session->current_trace_chunk && session->current_trace_chunk != chunk &&
3053 !lttng_trace_chunk_get_name_overridden(session->current_trace_chunk)) {
3054 if (close_command.is_set &&
3055 close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE &&
3056 !session->has_rotated) {
3057 /* New chunk stays in session output directory. */
3058 new_path = "";
3059 } else {
3060 /* Use chunk name for new chunk. */
3061 new_path = NULL;
3062 }
3063 /* Rename new chunk path. */
3064 chunk_status = lttng_trace_chunk_rename_path(session->current_trace_chunk,
3065 new_path);
3066 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
3067 ret = -1;
88188199 3068 goto end_unlock_session;
a7ceb342
MD
3069 }
3070 session->ongoing_rotation = false;
3071 }
3072 if ((!close_command.is_set ||
3073 close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION) &&
3074 !lttng_trace_chunk_get_name_overridden(chunk)) {
3075 const char *old_path;
3076
3077 if (!session->has_rotated) {
3078 old_path = "";
3079 } else {
3080 old_path = NULL;
3081 }
3082 /* We need to move back the .tmp_old_chunk to its rightful place. */
3083 chunk_status = lttng_trace_chunk_rename_path(chunk, old_path);
3084 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
3085 ret = -1;
88188199 3086 goto end_unlock_session;
a7ceb342
MD
3087 }
3088 }
bbc4768c
JG
3089 chunk_status = lttng_trace_chunk_set_close_timestamp(
3090 chunk, close_timestamp);
3091 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
3092 ERR("Failed to set trace chunk close timestamp");
3093 ret = -1;
3094 reply_code = LTTNG_ERR_UNK;
62bad3bf 3095 goto end_unlock_session;
bbc4768c
JG
3096 }
3097
3098 if (close_command.is_set) {
3099 chunk_status = lttng_trace_chunk_set_close_command(
3100 chunk, close_command.value);
3101 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
3102 ret = -1;
3103 reply_code = LTTNG_ERR_INVALID;
62bad3bf 3104 goto end_unlock_session;
bbc4768c
JG
3105 }
3106 }
ecd1a12f
MD
3107 chunk_status = lttng_trace_chunk_get_name(chunk, &chunk_name, NULL);
3108 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
3109 ERR("Failed to get chunk name");
3110 ret = -1;
3111 reply_code = LTTNG_ERR_UNK;
3112 goto end_unlock_session;
3113 }
3114 if (!session->has_rotated && !session->snapshot) {
3115 ret = lttng_strncpy(closed_trace_chunk_path,
3116 session->output_path,
3117 sizeof(closed_trace_chunk_path));
3118 if (ret) {
3119 ERR("Failed to send trace chunk path: path length of %zu bytes exceeds the maximal allowed length of %zu bytes",
3120 strlen(session->output_path),
3121 sizeof(closed_trace_chunk_path));
3122 reply_code = LTTNG_ERR_NOMEM;
3123 ret = -1;
3124 goto end_unlock_session;
3125 }
3126 } else {
3127 if (session->snapshot) {
3128 ret = snprintf(closed_trace_chunk_path,
3129 sizeof(closed_trace_chunk_path),
3130 "%s/%s", session->output_path,
3131 chunk_name);
3132 } else {
3133 ret = snprintf(closed_trace_chunk_path,
3134 sizeof(closed_trace_chunk_path),
3135 "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY
3136 "/%s",
3137 session->output_path, chunk_name);
3138 }
3139 if (ret < 0 || ret == sizeof(closed_trace_chunk_path)) {
3140 ERR("Failed to format closed trace chunk resulting path");
3141 reply_code = ret < 0 ? LTTNG_ERR_UNK : LTTNG_ERR_NOMEM;
3142 ret = -1;
3143 goto end_unlock_session;
3144 }
3145 }
489ea154
MD
3146 if (close_command.is_set &&
3147 close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED) {
3148 session->has_rotated = true;
3149 }
ecd1a12f
MD
3150 DBG("Reply chunk path on close: %s", closed_trace_chunk_path);
3151 path_length = strlen(closed_trace_chunk_path) + 1;
3152 if (path_length > UINT32_MAX) {
3153 ERR("Closed trace chunk path exceeds the maximal length allowed by the protocol");
3154 ret = -1;
3155 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
3156 goto end_unlock_session;
3157 }
bbc4768c 3158
c35f9726
JG
3159 if (session->current_trace_chunk == chunk) {
3160 /*
3161 * After a trace chunk close command, no new streams
3162 * referencing the chunk may be created. Hence, on the
3163 * event that no new trace chunk have been created for
3164 * the session, the reference to the current trace chunk
3165 * is released in order to allow it to be reclaimed when
3166 * the last stream releases its reference to it.
3167 */
3168 lttng_trace_chunk_put(session->current_trace_chunk);
3169 session->current_trace_chunk = NULL;
3170 }
62bad3bf
JG
3171 lttng_trace_chunk_put(session->pending_closure_trace_chunk);
3172 session->pending_closure_trace_chunk = NULL;
3173end_unlock_session:
c35f9726
JG
3174 pthread_mutex_unlock(&session->lock);
3175
bbc4768c 3176end:
ecd1a12f
MD
3177 reply.generic.ret_code = htobe32((uint32_t) reply_code);
3178 reply.path_length = htobe32((uint32_t) path_length);
9898f786 3179 buf_ret = lttng_dynamic_buffer_append(
ecd1a12f 3180 &reply_payload, &reply, sizeof(reply));
9898f786 3181 if (buf_ret) {
ecd1a12f
MD
3182 ERR("Failed to append \"close trace chunk\" command reply header to payload buffer");
3183 goto end_no_reply;
3184 }
3185
3186 if (reply_code == LTTNG_OK) {
9898f786 3187 buf_ret = lttng_dynamic_buffer_append(&reply_payload,
ecd1a12f 3188 closed_trace_chunk_path, path_length);
9898f786 3189 if (buf_ret) {
ecd1a12f
MD
3190 ERR("Failed to append \"close trace chunk\" command reply path to payload buffer");
3191 goto end_no_reply;
3192 }
3193 }
3194
bbc4768c 3195 send_ret = conn->sock->ops->sendmsg(conn->sock,
ecd1a12f
MD
3196 reply_payload.data,
3197 reply_payload.size,
bbc4768c 3198 0);
ecd1a12f
MD
3199 if (send_ret < reply_payload.size) {
3200 ERR("Failed to send \"close trace chunk\" command reply of %zu bytes (ret = %zd)",
3201 reply_payload.size, send_ret);
bbc4768c 3202 ret = -1;
ecd1a12f 3203 goto end_no_reply;
bbc4768c
JG
3204 }
3205end_no_reply:
3206 lttng_trace_chunk_put(chunk);
ecd1a12f 3207 lttng_dynamic_buffer_reset(&reply_payload);
bbc4768c
JG
3208 return ret;
3209}
3210
c35f9726
JG
3211/*
3212 * relay_trace_chunk_exists: check if a trace chunk exists
3213 */
3214static int relay_trace_chunk_exists(const struct lttcomm_relayd_hdr *recv_hdr,
3215 struct relay_connection *conn,
3216 const struct lttng_buffer_view *payload)
3217{
3218 int ret = 0;
3219 ssize_t send_ret;
3220 struct relay_session *session = conn->session;
3221 struct lttcomm_relayd_trace_chunk_exists *msg;
3222 struct lttcomm_relayd_trace_chunk_exists_reply reply = {};
3223 struct lttng_buffer_view header_view;
c35f9726 3224 uint64_t chunk_id;
6b584c2e 3225 bool chunk_exists;
c35f9726
JG
3226
3227 if (!session || !conn->version_check_done) {
0f1b1d25 3228 ERR("Trying to check for the presence of a trace chunk before version check");
c35f9726
JG
3229 ret = -1;
3230 goto end_no_reply;
3231 }
3232
3233 if (session->major == 2 && session->minor < 11) {
8a82be4c 3234 ERR("Chunk exists command is unsupported before 2.11");
c35f9726
JG
3235 ret = -1;
3236 goto end_no_reply;
3237 }
3238
3239 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
3e6e0df2 3240 if (!lttng_buffer_view_is_valid(&header_view)) {
8a82be4c 3241 ERR("Failed to receive payload of chunk exists command");
c35f9726
JG
3242 ret = -1;
3243 goto end_no_reply;
3244 }
3245
3246 /* Convert to host endianness. */
3247 msg = (typeof(msg)) header_view.data;
3248 chunk_id = be64toh(msg->chunk_id);
3249
6b584c2e 3250 ret = sessiond_trace_chunk_registry_chunk_exists(
c35f9726
JG
3251 sessiond_trace_chunk_registry,
3252 conn->session->sessiond_uuid,
3253 conn->session->id,
6b584c2e
JG
3254 chunk_id, &chunk_exists);
3255 /*
3256 * If ret is not 0, send the reply and report the error to the caller.
3257 * It is a protocol (or internal) error and the session/connection
3258 * should be torn down.
3259 */
ac497a37
SM
3260 reply.generic.ret_code = htobe32((uint32_t) (ret == 0 ? LTTNG_OK : LTTNG_ERR_INVALID_PROTOCOL));
3261 reply.trace_chunk_exists = ret == 0 ? chunk_exists : 0;
3262
6b584c2e
JG
3263 send_ret = conn->sock->ops->sendmsg(
3264 conn->sock, &reply, sizeof(reply), 0);
c35f9726
JG
3265 if (send_ret < (ssize_t) sizeof(reply)) {
3266 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
3267 send_ret);
3268 ret = -1;
3269 }
3270end_no_reply:
c35f9726
JG
3271 return ret;
3272}
3273
8614e600
MD
3274/*
3275 * relay_get_configuration: query whether feature is available
3276 */
3277static int relay_get_configuration(const struct lttcomm_relayd_hdr *recv_hdr,
3278 struct relay_connection *conn,
3279 const struct lttng_buffer_view *payload)
3280{
3281 int ret = 0;
3282 ssize_t send_ret;
3283 struct lttcomm_relayd_get_configuration *msg;
3284 struct lttcomm_relayd_get_configuration_reply reply = {};
3285 struct lttng_buffer_view header_view;
3286 uint64_t query_flags = 0;
3287 uint64_t result_flags = 0;
3288
3289 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
3e6e0df2 3290 if (!lttng_buffer_view_is_valid(&header_view)) {
8614e600
MD
3291 ERR("Failed to receive payload of chunk close command");
3292 ret = -1;
3293 goto end_no_reply;
3294 }
3295
3296 /* Convert to host endianness. */
3297 msg = (typeof(msg)) header_view.data;
3298 query_flags = be64toh(msg->query_flags);
3299
3300 if (query_flags) {
3301 ret = LTTNG_ERR_INVALID_PROTOCOL;
3302 goto reply;
3303 }
3304 if (opt_allow_clear) {
3305 result_flags |= LTTCOMM_RELAYD_CONFIGURATION_FLAG_CLEAR_ALLOWED;
3306 }
3307 ret = 0;
3308reply:
ac497a37
SM
3309 reply.generic.ret_code = htobe32((uint32_t) (ret == 0 ? LTTNG_OK : LTTNG_ERR_INVALID_PROTOCOL));
3310 reply.relayd_configuration_flags = htobe64(result_flags);
3311
8614e600
MD
3312 send_ret = conn->sock->ops->sendmsg(
3313 conn->sock, &reply, sizeof(reply), 0);
3314 if (send_ret < (ssize_t) sizeof(reply)) {
3315 ERR("Failed to send \"get configuration\" command reply (ret = %zd)",
3316 send_ret);
3317 ret = -1;
3318 }
3319end_no_reply:
3320 return ret;
3321}
3322
5312a3ed
JG
3323#define DBG_CMD(cmd_name, conn) \
3324 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
3325
3326static int relay_process_control_command(struct relay_connection *conn,
3327 const struct lttcomm_relayd_hdr *header,
3328 const struct lttng_buffer_view *payload)
b8aa1682
JD
3329{
3330 int ret = 0;
3331
5312a3ed 3332 switch (header->cmd) {
b8aa1682 3333 case RELAYD_CREATE_SESSION:
5312a3ed
JG
3334 DBG_CMD("RELAYD_CREATE_SESSION", conn);
3335 ret = relay_create_session(header, conn, payload);
b8aa1682 3336 break;
b8aa1682 3337 case RELAYD_ADD_STREAM:
5312a3ed
JG
3338 DBG_CMD("RELAYD_ADD_STREAM", conn);
3339 ret = relay_add_stream(header, conn, payload);
b8aa1682
JD
3340 break;
3341 case RELAYD_START_DATA:
5312a3ed
JG
3342 DBG_CMD("RELAYD_START_DATA", conn);
3343 ret = relay_start(header, conn, payload);
b8aa1682
JD
3344 break;
3345 case RELAYD_SEND_METADATA:
5312a3ed
JG
3346 DBG_CMD("RELAYD_SEND_METADATA", conn);
3347 ret = relay_recv_metadata(header, conn, payload);
b8aa1682
JD
3348 break;
3349 case RELAYD_VERSION:
5312a3ed
JG
3350 DBG_CMD("RELAYD_VERSION", conn);
3351 ret = relay_send_version(header, conn, payload);
b8aa1682 3352 break;
173af62f 3353 case RELAYD_CLOSE_STREAM:
5312a3ed
JG
3354 DBG_CMD("RELAYD_CLOSE_STREAM", conn);
3355 ret = relay_close_stream(header, conn, payload);
173af62f 3356 break;
6d805429 3357 case RELAYD_DATA_PENDING:
5312a3ed
JG
3358 DBG_CMD("RELAYD_DATA_PENDING", conn);
3359 ret = relay_data_pending(header, conn, payload);
c8f59ee5
DG
3360 break;
3361 case RELAYD_QUIESCENT_CONTROL:
5312a3ed
JG
3362 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn);
3363 ret = relay_quiescent_control(header, conn, payload);
c8f59ee5 3364 break;
f7079f67 3365 case RELAYD_BEGIN_DATA_PENDING:
5312a3ed
JG
3366 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn);
3367 ret = relay_begin_data_pending(header, conn, payload);
f7079f67
DG
3368 break;
3369 case RELAYD_END_DATA_PENDING:
5312a3ed
JG
3370 DBG_CMD("RELAYD_END_DATA_PENDING", conn);
3371 ret = relay_end_data_pending(header, conn, payload);
f7079f67 3372 break;
1c20f0e2 3373 case RELAYD_SEND_INDEX:
5312a3ed
JG
3374 DBG_CMD("RELAYD_SEND_INDEX", conn);
3375 ret = relay_recv_index(header, conn, payload);
1c20f0e2 3376 break;
a4baae1b 3377 case RELAYD_STREAMS_SENT:
5312a3ed
JG
3378 DBG_CMD("RELAYD_STREAMS_SENT", conn);
3379 ret = relay_streams_sent(header, conn, payload);
a4baae1b 3380 break;
93ec662e 3381 case RELAYD_RESET_METADATA:
5312a3ed
JG
3382 DBG_CMD("RELAYD_RESET_METADATA", conn);
3383 ret = relay_reset_metadata(header, conn, payload);
93ec662e 3384 break;
c35f9726
JG
3385 case RELAYD_ROTATE_STREAMS:
3386 DBG_CMD("RELAYD_ROTATE_STREAMS", conn);
3387 ret = relay_rotate_session_streams(header, conn, payload);
d3ecc550 3388 break;
e5add6d0
JG
3389 case RELAYD_CREATE_TRACE_CHUNK:
3390 DBG_CMD("RELAYD_CREATE_TRACE_CHUNK", conn);
3391 ret = relay_create_trace_chunk(header, conn, payload);
3392 break;
bbc4768c
JG
3393 case RELAYD_CLOSE_TRACE_CHUNK:
3394 DBG_CMD("RELAYD_CLOSE_TRACE_CHUNK", conn);
3395 ret = relay_close_trace_chunk(header, conn, payload);
3396 break;
c35f9726
JG
3397 case RELAYD_TRACE_CHUNK_EXISTS:
3398 DBG_CMD("RELAYD_TRACE_CHUNK_EXISTS", conn);
3399 ret = relay_trace_chunk_exists(header, conn, payload);
3400 break;
8614e600
MD
3401 case RELAYD_GET_CONFIGURATION:
3402 DBG_CMD("RELAYD_GET_CONFIGURATION", conn);
3403 ret = relay_get_configuration(header, conn, payload);
3404 break;
b8aa1682
JD
3405 case RELAYD_UPDATE_SYNC_INFO:
3406 default:
5312a3ed 3407 ERR("Received unknown command (%u)", header->cmd);
58eb9381 3408 relay_unknown_command(conn);
b8aa1682
JD
3409 ret = -1;
3410 goto end;
3411 }
3412
3413end:
3414 return ret;
3415}
3416
5569b118
JG
3417static enum relay_connection_status relay_process_control_receive_payload(
3418 struct relay_connection *conn)
5312a3ed
JG
3419{
3420 int ret = 0;
5569b118 3421 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
5312a3ed
JG
3422 struct lttng_dynamic_buffer *reception_buffer =
3423 &conn->protocol.ctrl.reception_buffer;
3424 struct ctrl_connection_state_receive_payload *state =
3425 &conn->protocol.ctrl.state.receive_payload;
3426 struct lttng_buffer_view payload_view;
3427
3428 if (state->left_to_receive == 0) {
3429 /* Short-circuit for payload-less commands. */
3430 goto reception_complete;
3431 }
3432
3433 ret = conn->sock->ops->recvmsg(conn->sock,
3434 reception_buffer->data + state->received,
3435 state->left_to_receive, MSG_DONTWAIT);
3436 if (ret < 0) {
5569b118
JG
3437 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3438 PERROR("Unable to receive command payload on sock %d",
3439 conn->sock->fd);
3440 status = RELAY_CONNECTION_STATUS_ERROR;
3441 }
5312a3ed
JG
3442 goto end;
3443 } else if (ret == 0) {
3444 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
5569b118 3445 status = RELAY_CONNECTION_STATUS_CLOSED;
5312a3ed
JG
3446 goto end;
3447 }
3448
a0377dfe
FD
3449 LTTNG_ASSERT(ret > 0);
3450 LTTNG_ASSERT(ret <= state->left_to_receive);
5312a3ed
JG
3451
3452 state->left_to_receive -= ret;
3453 state->received += ret;
3454
3455 if (state->left_to_receive > 0) {
3456 /*
3457 * Can't transition to the protocol's next state, wait to
3458 * receive the rest of the header.
3459 */
3460 DBG3("Partial reception of control connection protocol payload (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
3461 state->received, state->left_to_receive,
3462 conn->sock->fd);
5312a3ed
JG
3463 goto end;
3464 }
3465
3466reception_complete:
3467 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64 " bytes",
3468 conn->sock->fd, state->received);
3469 /*
3470 * The payload required to process the command has been received.
3471 * A view to the reception buffer is forwarded to the various
3472 * commands and the state of the control is reset on success.
3473 *
3474 * Commands are responsible for sending their reply to the peer.
3475 */
3476 payload_view = lttng_buffer_view_from_dynamic_buffer(reception_buffer,
3477 0, -1);
3478 ret = relay_process_control_command(conn,
3479 &state->header, &payload_view);
3480 if (ret < 0) {
5569b118 3481 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed
JG
3482 goto end;
3483 }
3484
3485 ret = connection_reset_protocol_state(conn);
5569b118
JG
3486 if (ret) {
3487 status = RELAY_CONNECTION_STATUS_ERROR;
3488 }
5312a3ed 3489end:
5569b118 3490 return status;
5312a3ed
JG
3491}
3492
5569b118
JG
3493static enum relay_connection_status relay_process_control_receive_header(
3494 struct relay_connection *conn)
5312a3ed
JG
3495{
3496 int ret = 0;
5569b118 3497 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
5312a3ed
JG
3498 struct lttcomm_relayd_hdr header;
3499 struct lttng_dynamic_buffer *reception_buffer =
3500 &conn->protocol.ctrl.reception_buffer;
3501 struct ctrl_connection_state_receive_header *state =
3502 &conn->protocol.ctrl.state.receive_header;
3503
a0377dfe 3504 LTTNG_ASSERT(state->left_to_receive != 0);
5312a3ed
JG
3505
3506 ret = conn->sock->ops->recvmsg(conn->sock,
3507 reception_buffer->data + state->received,
3508 state->left_to_receive, MSG_DONTWAIT);
3509 if (ret < 0) {
5569b118
JG
3510 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3511 PERROR("Unable to receive control command header on sock %d",
3512 conn->sock->fd);
3513 status = RELAY_CONNECTION_STATUS_ERROR;
3514 }
5312a3ed
JG
3515 goto end;
3516 } else if (ret == 0) {
3517 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
5569b118 3518 status = RELAY_CONNECTION_STATUS_CLOSED;
5312a3ed
JG
3519 goto end;
3520 }
3521
a0377dfe
FD
3522 LTTNG_ASSERT(ret > 0);
3523 LTTNG_ASSERT(ret <= state->left_to_receive);
5312a3ed
JG
3524
3525 state->left_to_receive -= ret;
3526 state->received += ret;
3527
3528 if (state->left_to_receive > 0) {
3529 /*
3530 * Can't transition to the protocol's next state, wait to
3531 * receive the rest of the header.
3532 */
3533 DBG3("Partial reception of control connection protocol header (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
3534 state->received, state->left_to_receive,
3535 conn->sock->fd);
5312a3ed
JG
3536 goto end;
3537 }
3538
3539 /* Transition to next state: receiving the command's payload. */
3540 conn->protocol.ctrl.state_id =
3541 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD;
3542 memcpy(&header, reception_buffer->data, sizeof(header));
3543 header.circuit_id = be64toh(header.circuit_id);
3544 header.data_size = be64toh(header.data_size);
3545 header.cmd = be32toh(header.cmd);
3546 header.cmd_version = be32toh(header.cmd_version);
3547 memcpy(&conn->protocol.ctrl.state.receive_payload.header,
3548 &header, sizeof(header));
3549
3550 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32 ", cmd_version = %" PRIu32 ", payload size = %" PRIu64 " bytes",
3551 conn->sock->fd, header.cmd, header.cmd_version,
3552 header.data_size);
3553
715e6fb1 3554 if (header.data_size > DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE) {
5312a3ed
JG
3555 ERR("Command header indicates a payload (%" PRIu64 " bytes) that exceeds the maximal payload size allowed on a control connection.",
3556 header.data_size);
5569b118 3557 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed
JG
3558 goto end;
3559 }
3560
3561 conn->protocol.ctrl.state.receive_payload.left_to_receive =
3562 header.data_size;
3563 conn->protocol.ctrl.state.receive_payload.received = 0;
3564 ret = lttng_dynamic_buffer_set_size(reception_buffer,
3565 header.data_size);
3566 if (ret) {
5569b118 3567 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed
JG
3568 goto end;
3569 }
3570
3571 if (header.data_size == 0) {
3572 /*
3573 * Manually invoke the next state as the poll loop
3574 * will not wake-up to allow us to proceed further.
3575 */
5569b118 3576 status = relay_process_control_receive_payload(conn);
5312a3ed
JG
3577 }
3578end:
5569b118 3579 return status;
5312a3ed
JG
3580}
3581
3582/*
3583 * Process the commands received on the control socket
3584 */
5569b118
JG
3585static enum relay_connection_status relay_process_control(
3586 struct relay_connection *conn)
5312a3ed 3587{
5569b118 3588 enum relay_connection_status status;
5312a3ed
JG
3589
3590 switch (conn->protocol.ctrl.state_id) {
3591 case CTRL_CONNECTION_STATE_RECEIVE_HEADER:
5569b118 3592 status = relay_process_control_receive_header(conn);
5312a3ed
JG
3593 break;
3594 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD:
5569b118 3595 status = relay_process_control_receive_payload(conn);
5312a3ed
JG
3596 break;
3597 default:
3598 ERR("Unknown control connection protocol state encountered.");
3599 abort();
3600 }
3601
5569b118 3602 return status;
5312a3ed
JG
3603}
3604
5569b118
JG
3605static enum relay_connection_status relay_process_data_receive_header(
3606 struct relay_connection *conn)
b8aa1682 3607{
5312a3ed 3608 int ret;
5569b118 3609 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
5312a3ed
JG
3610 struct data_connection_state_receive_header *state =
3611 &conn->protocol.data.state.receive_header;
3612 struct lttcomm_relayd_data_hdr header;
b8aa1682 3613 struct relay_stream *stream;
5312a3ed 3614
a0377dfe 3615 LTTNG_ASSERT(state->left_to_receive != 0);
5312a3ed
JG
3616
3617 ret = conn->sock->ops->recvmsg(conn->sock,
3618 state->header_reception_buffer + state->received,
3619 state->left_to_receive, MSG_DONTWAIT);
3620 if (ret < 0) {
5569b118
JG
3621 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3622 PERROR("Unable to receive data header on sock %d", conn->sock->fd);
3623 status = RELAY_CONNECTION_STATUS_ERROR;
3624 }
5312a3ed
JG
3625 goto end;
3626 } else if (ret == 0) {
3627 /* Orderly shutdown. Not necessary to print an error. */
3628 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
5569b118 3629 status = RELAY_CONNECTION_STATUS_CLOSED;
b8aa1682
JD
3630 goto end;
3631 }
3632
a0377dfe
FD
3633 LTTNG_ASSERT(ret > 0);
3634 LTTNG_ASSERT(ret <= state->left_to_receive);
5312a3ed
JG
3635
3636 state->left_to_receive -= ret;
3637 state->received += ret;
3638
3639 if (state->left_to_receive > 0) {
3640 /*
3641 * Can't transition to the protocol's next state, wait to
3642 * receive the rest of the header.
3643 */
3644 DBG3("Partial reception of data connection header (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
3645 state->received, state->left_to_receive,
3646 conn->sock->fd);
7591bab1 3647 goto end;
b8aa1682 3648 }
b8aa1682 3649
5312a3ed
JG
3650 /* Transition to next state: receiving the payload. */
3651 conn->protocol.data.state_id = DATA_CONNECTION_STATE_RECEIVE_PAYLOAD;
173af62f 3652
5312a3ed
JG
3653 memcpy(&header, state->header_reception_buffer, sizeof(header));
3654 header.circuit_id = be64toh(header.circuit_id);
3655 header.stream_id = be64toh(header.stream_id);
3656 header.data_size = be32toh(header.data_size);
3657 header.net_seq_num = be64toh(header.net_seq_num);
3658 header.padding_size = be32toh(header.padding_size);
3659 memcpy(&conn->protocol.data.state.receive_payload.header, &header, sizeof(header));
3660
3661 conn->protocol.data.state.receive_payload.left_to_receive =
3662 header.data_size;
3663 conn->protocol.data.state.receive_payload.received = 0;
3664 conn->protocol.data.state.receive_payload.rotate_index = false;
3665
3666 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64 ", stream_id = %" PRIu64 ", data_size = %" PRIu32 ", net_seq_num = %" PRIu64 ", padding_size = %" PRIu32,
3667 conn->sock->fd, header.circuit_id,
3668 header.stream_id, header.data_size,
3669 header.net_seq_num, header.padding_size);
3670
3671 stream = stream_get_by_id(header.stream_id);
3672 if (!stream) {
3673 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64,
3674 header.stream_id);
5569b118
JG
3675 /* Protocol error. */
3676 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed
JG
3677 goto end;
3678 }
b8aa1682 3679
7591bab1 3680 pthread_mutex_lock(&stream->lock);
c35f9726
JG
3681 /* Prepare stream for the reception of a new packet. */
3682 ret = stream_init_packet(stream, header.data_size,
3683 &conn->protocol.data.state.receive_payload.rotate_index);
3684 pthread_mutex_unlock(&stream->lock);
3685 if (ret) {
3686 ERR("Failed to rotate stream output file");
3687 status = RELAY_CONNECTION_STATUS_ERROR;
3688 goto end_stream_unlock;
1c20f0e2
JD
3689 }
3690
5312a3ed 3691end_stream_unlock:
5312a3ed
JG
3692 stream_put(stream);
3693end:
5569b118 3694 return status;
5312a3ed
JG
3695}
3696
5569b118
JG
3697static enum relay_connection_status relay_process_data_receive_payload(
3698 struct relay_connection *conn)
5312a3ed
JG
3699{
3700 int ret;
5569b118 3701 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
5312a3ed
JG
3702 struct relay_stream *stream;
3703 struct data_connection_state_receive_payload *state =
3704 &conn->protocol.data.state.receive_payload;
3705 const size_t chunk_size = RECV_DATA_BUFFER_SIZE;
3706 char data_buffer[chunk_size];
3707 bool partial_recv = false;
3708 bool new_stream = false, close_requested = false, index_flushed = false;
3709 uint64_t left_to_receive = state->left_to_receive;
3710 struct relay_session *session;
3711
fd0f1e3e
JR
3712 DBG3("Receiving data for stream id %" PRIu64 " seqnum %" PRIu64 ", %" PRIu64" bytes received, %" PRIu64 " bytes left to receive",
3713 state->header.stream_id, state->header.net_seq_num,
3714 state->received, left_to_receive);
3715
5312a3ed
JG
3716 stream = stream_get_by_id(state->header.stream_id);
3717 if (!stream) {
5569b118 3718 /* Protocol error. */
fd0f1e3e 3719 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64,
5312a3ed 3720 state->header.stream_id);
5569b118 3721 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed 3722 goto end;
1c20f0e2
JD
3723 }
3724
5312a3ed
JG
3725 pthread_mutex_lock(&stream->lock);
3726 session = stream->trace->session;
fd0f1e3e
JR
3727 if (!conn->session) {
3728 ret = connection_set_session(conn, session);
3729 if (ret) {
3730 status = RELAY_CONNECTION_STATUS_ERROR;
3731 goto end_stream_unlock;
3732 }
3733 }
5312a3ed
JG
3734
3735 /*
3736 * The size of the "chunk" received on any iteration is bounded by:
3737 * - the data left to receive,
3738 * - the data immediately available on the socket,
3739 * - the on-stack data buffer
3740 */
3741 while (left_to_receive > 0 && !partial_recv) {
ff2aa8f0 3742 size_t recv_size = std::min<uint64_t>(left_to_receive, chunk_size);
c35f9726 3743 struct lttng_buffer_view packet_chunk;
5312a3ed
JG
3744
3745 ret = conn->sock->ops->recvmsg(conn->sock, data_buffer,
3746 recv_size, MSG_DONTWAIT);
3747 if (ret < 0) {
5569b118
JG
3748 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3749 PERROR("Socket %d error", conn->sock->fd);
3750 status = RELAY_CONNECTION_STATUS_ERROR;
3751 }
0848dba7 3752 goto end_stream_unlock;
5312a3ed
JG
3753 } else if (ret == 0) {
3754 /* No more data ready to be consumed on socket. */
3755 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64,
3756 state->header.stream_id);
5569b118 3757 status = RELAY_CONNECTION_STATUS_CLOSED;
5312a3ed
JG
3758 break;
3759 } else if (ret < (int) recv_size) {
3760 /*
3761 * All the data available on the socket has been
3762 * consumed.
3763 */
3764 partial_recv = true;
c35f9726 3765 recv_size = ret;
0848dba7
MD
3766 }
3767
c35f9726
JG
3768 packet_chunk = lttng_buffer_view_init(data_buffer,
3769 0, recv_size);
a0377dfe 3770 LTTNG_ASSERT(packet_chunk.data);
5312a3ed 3771
c35f9726
JG
3772 ret = stream_write(stream, &packet_chunk, 0);
3773 if (ret) {
0848dba7 3774 ERR("Relay error writing data to file");
5569b118 3775 status = RELAY_CONNECTION_STATUS_ERROR;
0848dba7
MD
3776 goto end_stream_unlock;
3777 }
3778
5312a3ed
JG
3779 left_to_receive -= recv_size;
3780 state->received += recv_size;
3781 state->left_to_receive = left_to_receive;
5312a3ed
JG
3782 }
3783
3784 if (state->left_to_receive > 0) {
3785 /*
3786 * Did not receive all the data expected, wait for more data to
3787 * become available on the socket.
3788 */
3789 DBG3("Partial receive on data connection of stream id %" PRIu64 ", %" PRIu64 " bytes received, %" PRIu64 " bytes left to receive",
3790 state->header.stream_id, state->received,
3791 state->left_to_receive);
5312a3ed 3792 goto end_stream_unlock;
0848dba7 3793 }
5ab7344e 3794
c35f9726
JG
3795 ret = stream_write(stream, NULL, state->header.padding_size);
3796 if (ret) {
5569b118 3797 status = RELAY_CONNECTION_STATUS_ERROR;
7591bab1 3798 goto end_stream_unlock;
1d4dfdef 3799 }
5312a3ed 3800
298a25ca 3801 if (session_streams_have_index(session)) {
c35f9726
JG
3802 ret = stream_update_index(stream, state->header.net_seq_num,
3803 state->rotate_index, &index_flushed,
3804 state->header.data_size + state->header.padding_size);
5312a3ed 3805 if (ret < 0) {
c35f9726 3806 ERR("Failed to update index: stream %" PRIu64 " net_seq_num %" PRIu64 " ret %d",
5312a3ed
JG
3807 stream->stream_handle,
3808 state->header.net_seq_num, ret);
5569b118 3809 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed
JG
3810 goto end_stream_unlock;
3811 }
3812 }
3813
a8f9f353 3814 if (stream->prev_data_seq == -1ULL) {
c0bae11d
MD
3815 new_stream = true;
3816 }
3817
c35f9726
JG
3818 ret = stream_complete_packet(stream, state->header.data_size +
3819 state->header.padding_size, state->header.net_seq_num,
3820 index_flushed);
3821 if (ret) {
3822 status = RELAY_CONNECTION_STATUS_ERROR;
3823 goto end_stream_unlock;
3824 }
5312a3ed
JG
3825
3826 /*
3827 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3828 * contents of *state which are aliased (union) to the same location as
3829 * the new state. Don't use it beyond this point.
3830 */
3831 connection_reset_protocol_state(conn);
3832 state = NULL;
173af62f 3833
7591bab1 3834end_stream_unlock:
bda7c7b9 3835 close_requested = stream->close_requested;
7591bab1 3836 pthread_mutex_unlock(&stream->lock);
5312a3ed 3837 if (close_requested && left_to_receive == 0) {
bda7c7b9
JG
3838 try_stream_close(stream);
3839 }
3840
c0bae11d
MD
3841 if (new_stream) {
3842 pthread_mutex_lock(&session->lock);
3843 uatomic_set(&session->new_streams, 1);
3844 pthread_mutex_unlock(&session->lock);
3845 }
5312a3ed 3846
7591bab1 3847 stream_put(stream);
b8aa1682 3848end:
5569b118 3849 return status;
b8aa1682
JD
3850}
3851
5312a3ed
JG
3852/*
3853 * relay_process_data: Process the data received on the data socket
3854 */
5569b118
JG
3855static enum relay_connection_status relay_process_data(
3856 struct relay_connection *conn)
5312a3ed 3857{
5569b118 3858 enum relay_connection_status status;
5312a3ed
JG
3859
3860 switch (conn->protocol.data.state_id) {
3861 case DATA_CONNECTION_STATE_RECEIVE_HEADER:
5569b118 3862 status = relay_process_data_receive_header(conn);
5312a3ed
JG
3863 break;
3864 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD:
5569b118 3865 status = relay_process_data_receive_payload(conn);
5312a3ed
JG
3866 break;
3867 default:
3868 ERR("Unexpected data connection communication state.");
3869 abort();
3870 }
3871
5569b118 3872 return status;
5312a3ed
JG
3873}
3874
7591bab1 3875static void cleanup_connection_pollfd(struct lttng_poll_event *events, int pollfd)
b8aa1682
JD
3876{
3877 int ret;
3878
58eb9381 3879 (void) lttng_poll_del(events, pollfd);
b8aa1682 3880
f355467e
JG
3881 ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker, &pollfd, 1,
3882 fd_tracker_util_close_fd, NULL);
b8aa1682
JD
3883 if (ret < 0) {
3884 ERR("Closing pollfd %d", pollfd);
3885 }
3886}
3887
7591bab1
MD
3888static void relay_thread_close_connection(struct lttng_poll_event *events,
3889 int pollfd, struct relay_connection *conn)
9d1bbf21 3890{
7591bab1 3891 const char *type_str;
2a174661 3892
7591bab1
MD
3893 switch (conn->type) {
3894 case RELAY_DATA:
3895 type_str = "Data";
3896 break;
3897 case RELAY_CONTROL:
3898 type_str = "Control";
3899 break;
3900 case RELAY_VIEWER_COMMAND:
3901 type_str = "Viewer Command";
3902 break;
3903 case RELAY_VIEWER_NOTIFICATION:
3904 type_str = "Viewer Notification";
3905 break;
3906 default:
3907 type_str = "Unknown";
9d1bbf21 3908 }
7591bab1
MD
3909 cleanup_connection_pollfd(events, pollfd);
3910 connection_put(conn);
3911 DBG("%s connection closed with %d", type_str, pollfd);
b8aa1682
JD
3912}
3913
3914/*
3915 * This thread does the actual work
3916 */
7591bab1 3917static void *relay_thread_worker(void *data)
b8aa1682 3918{
beaad64c
DG
3919 int ret, err = -1, last_seen_data_fd = -1;
3920 uint32_t nb_fd;
b8aa1682
JD
3921 struct lttng_poll_event events;
3922 struct lttng_ht *relay_connections_ht;
b8aa1682 3923 struct lttng_ht_iter iter;
90e7d72f 3924 struct relay_connection *destroy_conn = NULL;
b8aa1682
JD
3925
3926 DBG("[thread] Relay worker started");
3927
9d1bbf21
MD
3928 rcu_register_thread();
3929
55706a7d
MD
3930 health_register(health_relayd, HEALTH_RELAYD_TYPE_WORKER);
3931
9b5e0863
MD
3932 if (testpoint(relayd_thread_worker)) {
3933 goto error_testpoint;
3934 }
3935
f385ae0a
MD
3936 health_code_update();
3937
b8aa1682
JD
3938 /* table of connections indexed on socket */
3939 relay_connections_ht = lttng_ht_new(0, LTTNG_HT_TYPE_ULONG);
095a4ae5
MD
3940 if (!relay_connections_ht) {
3941 goto relay_connections_ht_error;
3942 }
b8aa1682 3943
e32a0864 3944 ret = create_named_thread_poll_set(&events, 2, "Worker thread epoll");
b8aa1682
JD
3945 if (ret < 0) {
3946 goto error_poll_create;
3947 }
3948
58eb9381 3949 ret = lttng_poll_add(&events, relay_conn_pipe[0], LPOLLIN | LPOLLRDHUP);
b8aa1682
JD
3950 if (ret < 0) {
3951 goto error;
3952 }
3953
beaad64c 3954restart:
b8aa1682 3955 while (1) {
beaad64c
DG
3956 int idx = -1, i, seen_control = 0, last_notdel_data_fd = -1;
3957
f385ae0a
MD
3958 health_code_update();
3959
b8aa1682 3960 /* Infinite blocking call, waiting for transmission */
87c1611d 3961 DBG3("Relayd worker thread polling...");
f385ae0a 3962 health_poll_entry();
b8aa1682 3963 ret = lttng_poll_wait(&events, -1);
f385ae0a 3964 health_poll_exit();
b8aa1682
JD
3965 if (ret < 0) {
3966 /*
3967 * Restart interrupted system call.
3968 */
3969 if (errno == EINTR) {
3970 goto restart;
3971 }
3972 goto error;
3973 }
3974
0d9c5d77
DG
3975 nb_fd = ret;
3976
beaad64c 3977 /*
7591bab1
MD
3978 * Process control. The control connection is
3979 * prioritized so we don't starve it with high
3980 * throughput tracing data on the data connection.
beaad64c 3981 */
b8aa1682
JD
3982 for (i = 0; i < nb_fd; i++) {
3983 /* Fetch once the poll data */
beaad64c
DG
3984 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
3985 int pollfd = LTTNG_POLL_GETFD(&events, i);
b8aa1682 3986
f385ae0a
MD
3987 health_code_update();
3988
b8aa1682
JD
3989 /* Thread quit pipe has been closed. Killing thread. */
3990 ret = check_thread_quit_pipe(pollfd, revents);
3991 if (ret) {
095a4ae5
MD
3992 err = 0;
3993 goto exit;
b8aa1682
JD
3994 }
3995
58eb9381
DG
3996 /* Inspect the relay conn pipe for new connection */
3997 if (pollfd == relay_conn_pipe[0]) {
03e43155 3998 if (revents & LPOLLIN) {
90e7d72f
JG
3999 struct relay_connection *conn;
4000
58eb9381 4001 ret = lttng_read(relay_conn_pipe[0], &conn, sizeof(conn));
b8aa1682
JD
4002 if (ret < 0) {
4003 goto error;
4004 }
73039936
FD
4005 ret = lttng_poll_add(&events,
4006 conn->sock->fd,
58eb9381 4007 LPOLLIN | LPOLLRDHUP);
73039936
FD
4008 if (ret) {
4009 ERR("Failed to add new connection file descriptor to poll set");
4010 goto error;
4011 }
7591bab1 4012 connection_ht_add(relay_connections_ht, conn);
58eb9381 4013 DBG("Connection socket %d added", conn->sock->fd);
03e43155
MD
4014 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
4015 ERR("Relay connection pipe error");
4016 goto error;
4017 } else {
4018 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
4019 goto error;
b8aa1682 4020 }
58eb9381 4021 } else {
90e7d72f
JG
4022 struct relay_connection *ctrl_conn;
4023
7591bab1 4024 ctrl_conn = connection_get_by_sock(relay_connections_ht, pollfd);
58eb9381 4025 /* If not found, there is a synchronization issue. */
a0377dfe 4026 LTTNG_ASSERT(ctrl_conn);
58eb9381 4027
03e43155
MD
4028 if (ctrl_conn->type == RELAY_DATA) {
4029 if (revents & LPOLLIN) {
beaad64c
DG
4030 /*
4031 * Flag the last seen data fd not deleted. It will be
4032 * used as the last seen fd if any fd gets deleted in
4033 * this first loop.
4034 */
4035 last_notdel_data_fd = pollfd;
4036 }
03e43155
MD
4037 goto put_ctrl_connection;
4038 }
a0377dfe 4039 LTTNG_ASSERT(ctrl_conn->type == RELAY_CONTROL);
03e43155
MD
4040
4041 if (revents & LPOLLIN) {
5569b118
JG
4042 enum relay_connection_status status;
4043
4044 status = relay_process_control(ctrl_conn);
4045 if (status != RELAY_CONNECTION_STATUS_OK) {
fd0f1e3e
JR
4046 /*
4047 * On socket error flag the session as aborted to force
4048 * the cleanup of its stream otherwise it can leak
4049 * during the lifetime of the relayd.
4050 *
4051 * This prevents situations in which streams can be
4052 * left opened because an index was received, the
4053 * control connection is closed, and the data
4054 * connection is closed (uncleanly) before the packet's
4055 * data provided.
4056 *
4057 * Since the control connection encountered an error,
4058 * it is okay to be conservative and close the
4059 * session right now as we can't rely on the protocol
4060 * being respected anymore.
4061 */
4062 if (status == RELAY_CONNECTION_STATUS_ERROR) {
4063 session_abort(ctrl_conn->session);
4064 }
4065
5569b118 4066 /* Clear the connection on error or close. */
5312a3ed
JG
4067 relay_thread_close_connection(&events,
4068 pollfd,
03e43155 4069 ctrl_conn);
03e43155 4070 }
5312a3ed 4071 seen_control = 1;
03e43155
MD
4072 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
4073 relay_thread_close_connection(&events,
4074 pollfd, ctrl_conn);
4075 if (last_seen_data_fd == pollfd) {
4076 last_seen_data_fd = last_notdel_data_fd;
4077 }
58eb9381 4078 } else {
03e43155
MD
4079 ERR("Unexpected poll events %u for control sock %d",
4080 revents, pollfd);
4081 connection_put(ctrl_conn);
4082 goto error;
beaad64c 4083 }
03e43155 4084 put_ctrl_connection:
7591bab1 4085 connection_put(ctrl_conn);
beaad64c
DG
4086 }
4087 }
4088
4089 /*
4090 * The last loop handled a control request, go back to poll to make
4091 * sure we prioritise the control socket.
4092 */
4093 if (seen_control) {
4094 continue;
4095 }
4096
4097 if (last_seen_data_fd >= 0) {
4098 for (i = 0; i < nb_fd; i++) {
4099 int pollfd = LTTNG_POLL_GETFD(&events, i);
f385ae0a
MD
4100
4101 health_code_update();
4102
beaad64c
DG
4103 if (last_seen_data_fd == pollfd) {
4104 idx = i;
4105 break;
4106 }
4107 }
4108 }
4109
4110 /* Process data connection. */
4111 for (i = idx + 1; i < nb_fd; i++) {
4112 /* Fetch the poll data. */
4113 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
4114 int pollfd = LTTNG_POLL_GETFD(&events, i);
90e7d72f 4115 struct relay_connection *data_conn;
beaad64c 4116
f385ae0a
MD
4117 health_code_update();
4118
fd20dac9
MD
4119 if (!revents) {
4120 /* No activity for this FD (poll implementation). */
4121 continue;
4122 }
4123
beaad64c 4124 /* Skip the command pipe. It's handled in the first loop. */
58eb9381 4125 if (pollfd == relay_conn_pipe[0]) {
beaad64c
DG
4126 continue;
4127 }
4128
7591bab1 4129 data_conn = connection_get_by_sock(relay_connections_ht, pollfd);
90e7d72f 4130 if (!data_conn) {
fd20dac9 4131 /* Skip it. Might be removed before. */
fd20dac9
MD
4132 continue;
4133 }
03e43155
MD
4134 if (data_conn->type == RELAY_CONTROL) {
4135 goto put_data_connection;
4136 }
a0377dfe 4137 LTTNG_ASSERT(data_conn->type == RELAY_DATA);
fd20dac9
MD
4138
4139 if (revents & LPOLLIN) {
5569b118
JG
4140 enum relay_connection_status status;
4141
4142 status = relay_process_data(data_conn);
4143 /* Connection closed or error. */
4144 if (status != RELAY_CONNECTION_STATUS_OK) {
fd0f1e3e
JR
4145 /*
4146 * On socket error flag the session as aborted to force
4147 * the cleanup of its stream otherwise it can leak
4148 * during the lifetime of the relayd.
4149 *
4150 * This prevents situations in which streams can be
4151 * left opened because an index was received, the
4152 * control connection is closed, and the data
4153 * connection is closed (uncleanly) before the packet's
4154 * data provided.
4155 *
4156 * Since the data connection encountered an error,
4157 * it is okay to be conservative and close the
4158 * session right now as we can't rely on the protocol
4159 * being respected anymore.
4160 */
4161 if (status == RELAY_CONNECTION_STATUS_ERROR) {
4162 session_abort(data_conn->session);
4163 }
7591bab1 4164 relay_thread_close_connection(&events, pollfd,
03e43155 4165 data_conn);
fd20dac9
MD
4166 /*
4167 * Every goto restart call sets the last seen fd where
4168 * here we don't really care since we gracefully
4169 * continue the loop after the connection is deleted.
4170 */
4171 } else {
4172 /* Keep last seen port. */
4173 last_seen_data_fd = pollfd;
7591bab1 4174 connection_put(data_conn);
fd20dac9 4175 goto restart;
b8aa1682 4176 }
03e43155
MD
4177 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
4178 relay_thread_close_connection(&events, pollfd,
4179 data_conn);
4180 } else {
4181 ERR("Unknown poll events %u for data sock %d",
4182 revents, pollfd);
b8aa1682 4183 }
03e43155 4184 put_data_connection:
7591bab1 4185 connection_put(data_conn);
b8aa1682 4186 }
beaad64c 4187 last_seen_data_fd = -1;
b8aa1682
JD
4188 }
4189
f385ae0a
MD
4190 /* Normal exit, no error */
4191 ret = 0;
4192
095a4ae5 4193exit:
b8aa1682 4194error:
71efa8ef 4195 /* Cleanup remaining connection object. */
9d1bbf21 4196 rcu_read_lock();
90e7d72f
JG
4197 cds_lfht_for_each_entry(relay_connections_ht->ht, &iter.iter,
4198 destroy_conn,
58eb9381 4199 sock_n.node) {
f385ae0a 4200 health_code_update();
98ba050e 4201
fd0f1e3e 4202 session_abort(destroy_conn->session);
98ba050e 4203
7591bab1
MD
4204 /*
4205 * No need to grab another ref, because we own
4206 * destroy_conn.
4207 */
4208 relay_thread_close_connection(&events, destroy_conn->sock->fd,
4209 destroy_conn);
b8aa1682 4210 }
94d49140 4211 rcu_read_unlock();
7591bab1 4212
e32a0864 4213 (void) fd_tracker_util_poll_clean(the_fd_tracker, &events);
7d2f7452 4214error_poll_create:
b8aa1682 4215 lttng_ht_destroy(relay_connections_ht);
095a4ae5 4216relay_connections_ht_error:
58eb9381 4217 /* Close relay conn pipes */
726b2396
JG
4218 (void) fd_tracker_util_pipe_close(the_fd_tracker,
4219 relay_conn_pipe);
095a4ae5
MD
4220 if (err) {
4221 DBG("Thread exited with error");
4222 }
b8aa1682 4223 DBG("Worker thread cleanup complete");
9b5e0863 4224error_testpoint:
f385ae0a
MD
4225 if (err) {
4226 health_error();
4227 ERR("Health error occurred in %s", __func__);
4228 }
4229 health_unregister(health_relayd);
9d1bbf21 4230 rcu_unregister_thread();
b4aacfdc 4231 lttng_relay_stop_threads();
b8aa1682
JD
4232 return NULL;
4233}
4234
4235/*
4236 * Create the relay command pipe to wake thread_manage_apps.
4237 * Closed in cleanup().
4238 */
58eb9381 4239static int create_relay_conn_pipe(void)
b8aa1682 4240{
726b2396
JG
4241 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker,
4242 "Relayd connection pipe", relay_conn_pipe);
b8aa1682
JD
4243}
4244
9c256b01
JG
4245static int stdio_open(void *data, int *fds)
4246{
4247 fds[0] = fileno(stdout);
4248 fds[1] = fileno(stderr);
4249 return 0;
4250}
4251
9c256b01
JG
4252static int track_stdio(void)
4253{
4254 int fds[2];
4255 const char *names[] = { "stdout", "stderr" };
4256
4257 return fd_tracker_open_unsuspendable_fd(the_fd_tracker, fds,
4258 names, 2, stdio_open, NULL);
4259}
4260
b8aa1682
JD
4261/*
4262 * main
4263 */
4264int main(int argc, char **argv)
4265{
00e3b7f1 4266 bool thread_is_rcu_registered = false;
178a0557 4267 int ret = 0, retval = 0;
b8aa1682 4268 void *status;
f7c3ffd7 4269 char *unlinked_file_directory_path = NULL, *output_path = NULL;
b8aa1682 4270
2a10de3b
JR
4271 /* Parse environment variables */
4272 ret = parse_env_options();
4273 if (ret) {
4274 retval = -1;
4275 goto exit_options;
4276 }
4277
4278 /*
4279 * Parse arguments.
4280 * Command line arguments overwrite environment.
4281 */
b8aa1682 4282 progname = argv[0];
178a0557
MD
4283 if (set_options(argc, argv)) {
4284 retval = -1;
4285 goto exit_options;
b8aa1682
JD
4286 }
4287
178a0557
MD
4288 if (set_signal_handler()) {
4289 retval = -1;
4290 goto exit_options;
b8aa1682
JD
4291 }
4292
a3bc3918
JR
4293 relayd_config_log();
4294
4295 if (opt_print_version) {
4296 print_version();
4297 retval = 0;
4298 goto exit_options;
4299 }
4300
c0407718
JG
4301 ret = fclose(stdin);
4302 if (ret) {
4303 PERROR("Failed to close stdin");
4304 goto exit_options;
4305 }
4306
35ab25e5
MD
4307 DBG("Clear command %s", opt_allow_clear ? "allowed" : "disallowed");
4308
4d513a50
DG
4309 /* Try to create directory if -o, --output is specified. */
4310 if (opt_output_path) {
994fa64f
DG
4311 if (*opt_output_path != '/') {
4312 ERR("Please specify an absolute path for -o, --output PATH");
178a0557
MD
4313 retval = -1;
4314 goto exit_options;
994fa64f
DG
4315 }
4316
d77dded2
JG
4317 ret = utils_mkdir_recursive(opt_output_path, S_IRWXU | S_IRWXG,
4318 -1, -1);
4d513a50
DG
4319 if (ret < 0) {
4320 ERR("Unable to create %s", opt_output_path);
178a0557
MD
4321 retval = -1;
4322 goto exit_options;
4d513a50
DG
4323 }
4324 }
4325
b8aa1682 4326 /* Daemonize */
b5218ffb 4327 if (opt_daemon || opt_background) {
3fd27398
MD
4328 ret = lttng_daemonize(&child_ppid, &recv_child_signal,
4329 !opt_background);
b8aa1682 4330 if (ret < 0) {
178a0557
MD
4331 retval = -1;
4332 goto exit_options;
b8aa1682 4333 }
3fd27398
MD
4334 }
4335
ce9ee1fb
JR
4336 if (opt_working_directory) {
4337 ret = utils_change_working_directory(opt_working_directory);
4338 if (ret) {
4339 /* All errors are already logged. */
4340 goto exit_options;
4341 }
4342 }
4343
23c8ff50
JG
4344 sessiond_trace_chunk_registry = sessiond_trace_chunk_registry_create();
4345 if (!sessiond_trace_chunk_registry) {
4346 ERR("Failed to initialize session daemon trace chunk registry");
4347 retval = -1;
794e2e5f 4348 goto exit_options;
23c8ff50
JG
4349 }
4350
00e3b7f1
JG
4351 /*
4352 * The RCU thread registration (and use, through the fd-tracker's
4353 * creation) is done after the daemonization to allow us to not
4354 * deal with liburcu's fork() management as the call RCU needs to
4355 * be restored.
4356 */
4357 rcu_register_thread();
4358 thread_is_rcu_registered = true;
4359
f7c3ffd7
JG
4360 output_path = create_output_path("");
4361 if (!output_path) {
4362 ERR("Failed to get output path");
4363 retval = -1;
4364 goto exit_options;
4365 }
4366 ret = asprintf(&unlinked_file_directory_path, "%s/%s", output_path,
4367 DEFAULT_UNLINKED_FILES_DIRECTORY);
4368 free(output_path);
4369 if (ret < 0) {
4370 ERR("Failed to format unlinked file directory path");
4371 retval = -1;
4372 goto exit_options;
4373 }
4374 the_fd_tracker = fd_tracker_create(
4375 unlinked_file_directory_path, lttng_opt_fd_pool_size);
4376 free(unlinked_file_directory_path);
00e3b7f1
JG
4377 if (!the_fd_tracker) {
4378 retval = -1;
4379 goto exit_options;
4380 }
4381
9c256b01
JG
4382 ret = track_stdio();
4383 if (ret) {
4384 retval = -1;
4385 goto exit_options;
4386 }
4387
178a0557
MD
4388 /* Initialize thread health monitoring */
4389 health_relayd = health_app_create(NR_HEALTH_RELAYD_TYPES);
4390 if (!health_relayd) {
4391 PERROR("health_app_create error");
4392 retval = -1;
794e2e5f 4393 goto exit_options;
178a0557
MD
4394 }
4395
3fd27398 4396 /* Create thread quit pipe */
178a0557
MD
4397 if (init_thread_quit_pipe()) {
4398 retval = -1;
794e2e5f 4399 goto exit_options;
b8aa1682
JD
4400 }
4401
b8aa1682 4402 /* Setup the thread apps communication pipe. */
178a0557
MD
4403 if (create_relay_conn_pipe()) {
4404 retval = -1;
794e2e5f 4405 goto exit_options;
b8aa1682
JD
4406 }
4407
4408 /* Init relay command queue. */
8bdee6e2 4409 cds_wfcq_init(&relay_conn_queue.head, &relay_conn_queue.tail);
b8aa1682 4410
554831e7
MD
4411 /* Initialize communication library */
4412 lttcomm_init();
87e45c13 4413 lttcomm_inet_init();
554831e7 4414
d3e2ba59 4415 /* tables of sessions indexed by session ID */
7591bab1
MD
4416 sessions_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
4417 if (!sessions_ht) {
178a0557 4418 retval = -1;
794e2e5f 4419 goto exit_options;
d3e2ba59
JD
4420 }
4421
4422 /* tables of streams indexed by stream ID */
2a174661 4423 relay_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
d3e2ba59 4424 if (!relay_streams_ht) {
178a0557 4425 retval = -1;
794e2e5f 4426 goto exit_options;
d3e2ba59
JD
4427 }
4428
4429 /* tables of streams indexed by stream ID */
92c6ca54
DG
4430 viewer_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
4431 if (!viewer_streams_ht) {
178a0557 4432 retval = -1;
794e2e5f 4433 goto exit_options;
55706a7d
MD
4434 }
4435
bcee2b96 4436 ret = init_health_quit_pipe();
178a0557
MD
4437 if (ret) {
4438 retval = -1;
794e2e5f 4439 goto exit_options;
65931c8b
MD
4440 }
4441
4442 /* Create thread to manage the client socket */
1a1a34b4 4443 ret = pthread_create(&health_thread, default_pthread_attr(),
65931c8b 4444 thread_manage_health, (void *) NULL);
178a0557
MD
4445 if (ret) {
4446 errno = ret;
65931c8b 4447 PERROR("pthread_create health");
178a0557 4448 retval = -1;
794e2e5f 4449 goto exit_options;
65931c8b
MD
4450 }
4451
b8aa1682 4452 /* Setup the dispatcher thread */
1a1a34b4 4453 ret = pthread_create(&dispatcher_thread, default_pthread_attr(),
b8aa1682 4454 relay_thread_dispatcher, (void *) NULL);
178a0557
MD
4455 if (ret) {
4456 errno = ret;
b8aa1682 4457 PERROR("pthread_create dispatcher");
178a0557
MD
4458 retval = -1;
4459 goto exit_dispatcher_thread;
b8aa1682
JD
4460 }
4461
4462 /* Setup the worker thread */
1a1a34b4 4463 ret = pthread_create(&worker_thread, default_pthread_attr(),
7591bab1 4464 relay_thread_worker, NULL);
178a0557
MD
4465 if (ret) {
4466 errno = ret;
b8aa1682 4467 PERROR("pthread_create worker");
178a0557
MD
4468 retval = -1;
4469 goto exit_worker_thread;
b8aa1682
JD
4470 }
4471
4472 /* Setup the listener thread */
1a1a34b4 4473 ret = pthread_create(&listener_thread, default_pthread_attr(),
b8aa1682 4474 relay_thread_listener, (void *) NULL);
178a0557
MD
4475 if (ret) {
4476 errno = ret;
b8aa1682 4477 PERROR("pthread_create listener");
178a0557
MD
4478 retval = -1;
4479 goto exit_listener_thread;
b8aa1682
JD
4480 }
4481
7591bab1 4482 ret = relayd_live_create(live_uri);
178a0557 4483 if (ret) {
d3e2ba59 4484 ERR("Starting live viewer threads");
178a0557 4485 retval = -1;
50138f51 4486 goto exit_live;
d3e2ba59
JD
4487 }
4488
178a0557
MD
4489 /*
4490 * This is where we start awaiting program completion (e.g. through
4491 * signal that asks threads to teardown).
4492 */
4493
4494 ret = relayd_live_join();
4495 if (ret) {
4496 retval = -1;
4497 }
50138f51 4498exit_live:
178a0557 4499
b8aa1682 4500 ret = pthread_join(listener_thread, &status);
178a0557
MD
4501 if (ret) {
4502 errno = ret;
4503 PERROR("pthread_join listener_thread");
4504 retval = -1;
b8aa1682
JD
4505 }
4506
178a0557 4507exit_listener_thread:
b8aa1682 4508 ret = pthread_join(worker_thread, &status);
178a0557
MD
4509 if (ret) {
4510 errno = ret;
4511 PERROR("pthread_join worker_thread");
4512 retval = -1;
b8aa1682
JD
4513 }
4514
178a0557 4515exit_worker_thread:
b8aa1682 4516 ret = pthread_join(dispatcher_thread, &status);
178a0557
MD
4517 if (ret) {
4518 errno = ret;
4519 PERROR("pthread_join dispatcher_thread");
4520 retval = -1;
b8aa1682 4521 }
178a0557 4522exit_dispatcher_thread:
42415026 4523
65931c8b 4524 ret = pthread_join(health_thread, &status);
178a0557
MD
4525 if (ret) {
4526 errno = ret;
4527 PERROR("pthread_join health_thread");
4528 retval = -1;
65931c8b 4529 }
178a0557 4530exit_options:
4d62fbf8
MD
4531 /*
4532 * Wait for all pending call_rcu work to complete before tearing
4533 * down data structures. call_rcu worker may be trying to
4534 * perform lookups in those structures.
4535 */
4536 rcu_barrier();
7591bab1
MD
4537 relayd_cleanup();
4538
4539 /* Ensure all prior call_rcu are done. */
4540 rcu_barrier();
d3e2ba59 4541
00e3b7f1
JG
4542 if (thread_is_rcu_registered) {
4543 rcu_unregister_thread();
4544 }
4545
178a0557 4546 if (!retval) {
b8aa1682 4547 exit(EXIT_SUCCESS);
178a0557
MD
4548 } else {
4549 exit(EXIT_FAILURE);
b8aa1682 4550 }
b8aa1682 4551}
This page took 0.33883 seconds and 4 git commands to generate.