Fix: relayd: return from function without unlocking session lock
[lttng-tools.git] / src / bin / lttng-relayd / main.c
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>
b8aa1682
JD
36
37#include <lttng/lttng.h>
38#include <common/common.h>
39#include <common/compat/poll.h>
40#include <common/compat/socket.h>
f263b7fd 41#include <common/compat/endian.h>
e8fa9fb0 42#include <common/compat/getenv.h>
b8aa1682 43#include <common/defaults.h>
3fd27398 44#include <common/daemonize.h>
b8aa1682
JD
45#include <common/futex.h>
46#include <common/sessiond-comm/sessiond-comm.h>
47#include <common/sessiond-comm/inet.h>
b8aa1682
JD
48#include <common/sessiond-comm/relayd.h>
49#include <common/uri.h>
a02de639 50#include <common/utils.h>
d3ecc550 51#include <common/align.h>
f40ef1d5 52#include <common/config/session-config.h>
5312a3ed
JG
53#include <common/dynamic-buffer.h>
54#include <common/buffer-view.h>
70626904 55#include <common/string-utils/format.h>
00e3b7f1 56#include <common/fd-tracker/fd-tracker.h>
67609994 57#include <common/fd-tracker/utils.h>
b8aa1682 58
2a635488 59#include "backward-compatibility-group-by.h"
0f907de1 60#include "cmd.h"
2a635488 61#include "connection.h"
d3e2ba59 62#include "ctf-trace.h"
2a635488 63#include "health-relayd.h"
1c20f0e2 64#include "index.h"
d3e2ba59 65#include "live.h"
2a635488 66#include "lttng-relayd.h"
2a174661 67#include "session.h"
2a635488 68#include "sessiond-trace-chunks.h"
2a174661 69#include "stream.h"
f056029c 70#include "tcp_keep_alive.h"
2a635488
JR
71#include "testpoint.h"
72#include "tracefile-array.h"
73#include "utils.h"
74#include "version.h"
75#include "viewer-stream.h"
b8aa1682 76
4fc83d94
PP
77static const char *help_msg =
78#ifdef LTTNG_EMBED_HELP
79#include <lttng-relayd.8.h>
80#else
81NULL
82#endif
83;
84
5569b118
JG
85enum relay_connection_status {
86 RELAY_CONNECTION_STATUS_OK,
a9577b76 87 /* An error occurred while processing an event on the connection. */
5569b118
JG
88 RELAY_CONNECTION_STATUS_ERROR,
89 /* Connection closed/shutdown cleanly. */
90 RELAY_CONNECTION_STATUS_CLOSED,
91};
92
b8aa1682 93/* command line options */
ce9ee1fb 94char *opt_output_path, *opt_working_directory;
35ab25e5 95static int opt_daemon, opt_background, opt_print_version, opt_allow_clear = 1;
a8b66566 96enum relay_group_output_by opt_group_output_by = RELAYD_GROUP_OUTPUT_BY_UNKNOWN;
3fd27398
MD
97
98/*
99 * We need to wait for listener and live listener threads, as well as
100 * health check thread, before being ready to signal readiness.
101 */
102#define NR_LTTNG_RELAY_READY 3
103static int lttng_relay_ready = NR_LTTNG_RELAY_READY;
0848dba7
MD
104
105/* Size of receive buffer. */
106#define RECV_DATA_BUFFER_SIZE 65536
107
3fd27398
MD
108static int recv_child_signal; /* Set to 1 when a SIGUSR1 signal is received. */
109static pid_t child_ppid; /* Internal parent PID use with daemonize. */
110
095a4ae5
MD
111static struct lttng_uri *control_uri;
112static struct lttng_uri *data_uri;
d3e2ba59 113static struct lttng_uri *live_uri;
b8aa1682
JD
114
115const char *progname;
b8aa1682 116
65931c8b 117const char *tracing_group_name = DEFAULT_TRACING_GROUP;
cd60b05a
JG
118static int tracing_group_name_override;
119
120const char * const config_section_name = "relayd";
65931c8b 121
b8aa1682
JD
122/*
123 * Quit pipe for all threads. This permits a single cancellation point
124 * for all threads when receiving an event on the pipe.
125 */
0b242f62 126int thread_quit_pipe[2] = { -1, -1 };
b8aa1682
JD
127
128/*
129 * This pipe is used to inform the worker thread that a command is queued and
130 * ready to be processed.
131 */
58eb9381 132static int relay_conn_pipe[2] = { -1, -1 };
b8aa1682 133
26c9d55e 134/* Shared between threads */
b8aa1682
JD
135static int dispatch_thread_exit;
136
137static pthread_t listener_thread;
138static pthread_t dispatcher_thread;
139static pthread_t worker_thread;
65931c8b 140static pthread_t health_thread;
b8aa1682 141
7591bab1
MD
142/*
143 * last_relay_stream_id_lock protects last_relay_stream_id increment
144 * atomicity on 32-bit architectures.
145 */
146static pthread_mutex_t last_relay_stream_id_lock = PTHREAD_MUTEX_INITIALIZER;
095a4ae5 147static uint64_t last_relay_stream_id;
b8aa1682
JD
148
149/*
150 * Relay command queue.
151 *
152 * The relay_thread_listener and relay_thread_dispatcher communicate with this
153 * queue.
154 */
58eb9381 155static struct relay_conn_queue relay_conn_queue;
b8aa1682 156
896010e3 157/* Cap of file desriptors to be in simultaneous use by the relay daemon. */
5c0551f9 158static unsigned int lttng_opt_fd_pool_size = -1;
896010e3 159
d3e2ba59
JD
160/* Global relay stream hash table. */
161struct lttng_ht *relay_streams_ht;
162
92c6ca54
DG
163/* Global relay viewer stream hash table. */
164struct lttng_ht *viewer_streams_ht;
165
7591bab1
MD
166/* Global relay sessions hash table. */
167struct lttng_ht *sessions_ht;
0a6518b0 168
55706a7d 169/* Relayd health monitoring */
eea7556c 170struct health_app *health_relayd;
55706a7d 171
23c8ff50
JG
172struct sessiond_trace_chunk_registry *sessiond_trace_chunk_registry;
173
00e3b7f1
JG
174/* Global fd tracker. */
175struct fd_tracker *the_fd_tracker;
176
cd60b05a
JG
177static struct option long_options[] = {
178 { "control-port", 1, 0, 'C', },
179 { "data-port", 1, 0, 'D', },
8d5c808e 180 { "live-port", 1, 0, 'L', },
cd60b05a 181 { "daemonize", 0, 0, 'd', },
b5218ffb 182 { "background", 0, 0, 'b', },
cd60b05a 183 { "group", 1, 0, 'g', },
5c0551f9 184 { "fd-pool-size", 1, 0, '\0', },
cd60b05a
JG
185 { "help", 0, 0, 'h', },
186 { "output", 1, 0, 'o', },
187 { "verbose", 0, 0, 'v', },
188 { "config", 1, 0, 'f' },
3a904098 189 { "version", 0, 0, 'V' },
ce9ee1fb 190 { "working-directory", 1, 0, 'w', },
a8b66566
JR
191 { "group-output-by-session", 0, 0, 's', },
192 { "group-output-by-host", 0, 0, 'p', },
35ab25e5 193 { "disallow-clear", 0, 0, 'x' },
cd60b05a
JG
194 { NULL, 0, 0, 0, },
195};
196
3a904098 197static const char *config_ignore_options[] = { "help", "config", "version" };
cd60b05a 198
a3bc3918
JR
199static void print_version(void) {
200 fprintf(stdout, "%s\n", VERSION);
201}
202
203static void relayd_config_log(void)
204{
205 DBG("LTTng-relayd " VERSION " - " VERSION_NAME "%s%s",
206 GIT_VERSION[0] == '\0' ? "" : " - " GIT_VERSION,
207 EXTRA_VERSION_NAME[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME);
208 if (EXTRA_VERSION_DESCRIPTION[0] != '\0') {
209 DBG("LTTng-relayd extra version description:\n\t" EXTRA_VERSION_DESCRIPTION "\n");
210 }
7f5ed73a
JR
211 if (EXTRA_VERSION_PATCHES[0] != '\0') {
212 DBG("LTTng-relayd extra patches:\n\t" EXTRA_VERSION_PATCHES "\n");
213 }
a3bc3918
JR
214}
215
cd60b05a
JG
216/*
217 * Take an option from the getopt output and set it in the right variable to be
218 * used later.
219 *
220 * Return 0 on success else a negative value.
221 */
7591bab1 222static int set_option(int opt, const char *arg, const char *optname)
b8aa1682 223{
cd60b05a
JG
224 int ret;
225
226 switch (opt) {
227 case 0:
5c0551f9 228 if (!strcmp(optname, "fd-pool-size")) {
896010e3
JG
229 unsigned long v;
230
231 errno = 0;
232 v = strtoul(arg, NULL, 0);
233 if (errno != 0 || !isdigit(arg[0])) {
5c0551f9 234 ERR("Wrong value in --fd-pool-size parameter: %s", arg);
896010e3
JG
235 ret = -1;
236 goto end;
237 }
896010e3 238 if (v >= UINT_MAX) {
5c0551f9 239 ERR("File descriptor cap overflow in --fd-pool-size parameter: %s", arg);
896010e3
JG
240 ret = -1;
241 goto end;
242 }
5c0551f9 243 lttng_opt_fd_pool_size = (unsigned int) v;
896010e3
JG
244 } else {
245 fprintf(stderr, "unknown option %s", optname);
246 if (arg) {
247 fprintf(stderr, " with arg %s\n", arg);
248 }
cd60b05a
JG
249 }
250 break;
251 case 'C':
e8fa9fb0
MD
252 if (lttng_is_setuid_setgid()) {
253 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
254 "-C, --control-port");
255 } else {
256 ret = uri_parse(arg, &control_uri);
257 if (ret < 0) {
258 ERR("Invalid control URI specified");
259 goto end;
260 }
261 if (control_uri->port == 0) {
262 control_uri->port = DEFAULT_NETWORK_CONTROL_PORT;
263 }
cd60b05a
JG
264 }
265 break;
266 case 'D':
e8fa9fb0
MD
267 if (lttng_is_setuid_setgid()) {
268 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
269 "-D, -data-port");
270 } else {
271 ret = uri_parse(arg, &data_uri);
272 if (ret < 0) {
273 ERR("Invalid data URI specified");
274 goto end;
275 }
276 if (data_uri->port == 0) {
277 data_uri->port = DEFAULT_NETWORK_DATA_PORT;
278 }
cd60b05a
JG
279 }
280 break;
8d5c808e 281 case 'L':
e8fa9fb0
MD
282 if (lttng_is_setuid_setgid()) {
283 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
284 "-L, -live-port");
285 } else {
286 ret = uri_parse(arg, &live_uri);
287 if (ret < 0) {
288 ERR("Invalid live URI specified");
289 goto end;
290 }
291 if (live_uri->port == 0) {
292 live_uri->port = DEFAULT_NETWORK_VIEWER_PORT;
293 }
8d5c808e
AM
294 }
295 break;
cd60b05a
JG
296 case 'd':
297 opt_daemon = 1;
298 break;
b5218ffb
MD
299 case 'b':
300 opt_background = 1;
301 break;
cd60b05a 302 case 'g':
e8fa9fb0
MD
303 if (lttng_is_setuid_setgid()) {
304 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
305 "-g, --group");
306 } else {
307 tracing_group_name = strdup(arg);
308 if (tracing_group_name == NULL) {
309 ret = -errno;
310 PERROR("strdup");
311 goto end;
312 }
313 tracing_group_name_override = 1;
330a40bb 314 }
cd60b05a
JG
315 break;
316 case 'h':
4fc83d94 317 ret = utils_show_help(8, "lttng-relayd", help_msg);
655b5cc1 318 if (ret) {
4fc83d94 319 ERR("Cannot show --help for `lttng-relayd`");
655b5cc1
PP
320 perror("exec");
321 }
cd60b05a 322 exit(EXIT_FAILURE);
3a904098 323 case 'V':
a3bc3918
JR
324 opt_print_version = 1;
325 break;
cd60b05a 326 case 'o':
e8fa9fb0
MD
327 if (lttng_is_setuid_setgid()) {
328 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
329 "-o, --output");
330 } else {
331 ret = asprintf(&opt_output_path, "%s", arg);
332 if (ret < 0) {
333 ret = -errno;
334 PERROR("asprintf opt_output_path");
335 goto end;
336 }
cd60b05a
JG
337 }
338 break;
ce9ee1fb
JR
339 case 'w':
340 if (lttng_is_setuid_setgid()) {
341 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
342 "-w, --working-directory");
343 } else {
344 ret = asprintf(&opt_working_directory, "%s", arg);
345 if (ret < 0) {
346 ret = -errno;
347 PERROR("asprintf opt_working_directory");
348 goto end;
349 }
350 }
351 break;
352
cd60b05a
JG
353 case 'v':
354 /* Verbose level can increase using multiple -v */
355 if (arg) {
356 lttng_opt_verbose = config_parse_value(arg);
357 } else {
849e5b7b
DG
358 /* Only 3 level of verbosity (-vvv). */
359 if (lttng_opt_verbose < 3) {
360 lttng_opt_verbose += 1;
361 }
cd60b05a
JG
362 }
363 break;
a8b66566
JR
364 case 's':
365 if (opt_group_output_by != RELAYD_GROUP_OUTPUT_BY_UNKNOWN) {
366 ERR("Cannot set --group-output-by-session, another --group-output-by argument is present");
367 exit(EXIT_FAILURE);
368 }
369 opt_group_output_by = RELAYD_GROUP_OUTPUT_BY_SESSION;
370 break;
371 case 'p':
372 if (opt_group_output_by != RELAYD_GROUP_OUTPUT_BY_UNKNOWN) {
373 ERR("Cannot set --group-output-by-host, another --group-output-by argument is present");
374 exit(EXIT_FAILURE);
375 }
376 opt_group_output_by = RELAYD_GROUP_OUTPUT_BY_HOST;
377 break;
35ab25e5
MD
378 case 'x':
379 /* Disallow clear */
380 opt_allow_clear = 0;
381 break;
cd60b05a
JG
382 default:
383 /* Unknown option or other error.
384 * Error is printed by getopt, just return */
385 ret = -1;
386 goto end;
387 }
388
389 /* All good. */
390 ret = 0;
391
392end:
393 return ret;
394}
395
396/*
397 * config_entry_handler_cb used to handle options read from a config file.
f40ef1d5 398 * See config_entry_handler_cb comment in common/config/session-config.h for the
cd60b05a
JG
399 * return value conventions.
400 */
7591bab1 401static int config_entry_handler(const struct config_entry *entry, void *unused)
cd60b05a
JG
402{
403 int ret = 0, i;
404
405 if (!entry || !entry->name || !entry->value) {
406 ret = -EINVAL;
407 goto end;
408 }
409
410 /* Check if the option is to be ignored */
411 for (i = 0; i < sizeof(config_ignore_options) / sizeof(char *); i++) {
412 if (!strcmp(entry->name, config_ignore_options[i])) {
413 goto end;
414 }
415 }
416
417 for (i = 0; i < (sizeof(long_options) / sizeof(struct option)) - 1; i++) {
418 /* Ignore if entry name is not fully matched. */
419 if (strcmp(entry->name, long_options[i].name)) {
420 continue;
421 }
422
423 /*
7591bab1
MD
424 * If the option takes no argument on the command line,
425 * we have to check if the value is "true". We support
426 * non-zero numeric values, true, on and yes.
cd60b05a
JG
427 */
428 if (!long_options[i].has_arg) {
429 ret = config_parse_value(entry->value);
430 if (ret <= 0) {
431 if (ret) {
432 WARN("Invalid configuration value \"%s\" for option %s",
433 entry->value, entry->name);
434 }
435 /* False, skip boolean config option. */
436 goto end;
437 }
438 }
439
440 ret = set_option(long_options[i].val, entry->value, entry->name);
441 goto end;
442 }
443
444 WARN("Unrecognized option \"%s\" in daemon configuration file.",
445 entry->name);
446
447end:
448 return ret;
449}
450
2a10de3b
JR
451static int parse_env_options(void)
452{
453 int ret = 0;
454 char *value = NULL;
455
456 value = lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV);
457 if (value) {
458 opt_working_directory = strdup(value);
459 if (!opt_working_directory) {
460 ERR("Failed to allocate working directory string (\"%s\")",
461 value);
462 ret = -1;
463 }
464 }
465 return ret;
466}
467
5c0551f9
JG
468static int set_fd_pool_size(void)
469{
470 int ret = 0;
471 struct rlimit rlimit;
472
473 ret = getrlimit(RLIMIT_NOFILE, &rlimit);
474 if (ret) {
475 PERROR("Failed to get file descriptor limit");
476 ret = -1;
477 goto end;
478 }
479
480 DBG("File descriptor count limits are %" PRIu64 " (soft) and %" PRIu64 " (hard)",
481 (uint64_t) rlimit.rlim_cur,
482 (uint64_t) rlimit.rlim_max);
483 if (lttng_opt_fd_pool_size == -1) {
484 /* Use default value (soft limit - reserve). */
485 if (rlimit.rlim_cur < DEFAULT_RELAYD_MIN_FD_POOL_SIZE) {
486 ERR("The process' file number limit is too low (%" PRIu64 "). The process' file number limit must be set to at least %i.",
487 (uint64_t) rlimit.rlim_cur, DEFAULT_RELAYD_MIN_FD_POOL_SIZE);
488 ret = -1;
489 goto end;
490 }
491 lttng_opt_fd_pool_size = rlimit.rlim_cur -
492 DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE;
493 goto end;
494 }
495
496 if (lttng_opt_fd_pool_size < DEFAULT_RELAYD_MIN_FD_POOL_SIZE) {
497 ERR("File descriptor pool size must be set to at least %d",
498 DEFAULT_RELAYD_MIN_FD_POOL_SIZE);
499 ret = -1;
500 goto end;
501 }
502
503 if (lttng_opt_fd_pool_size > rlimit.rlim_cur) {
504 ERR("File descriptor pool size argument (%u) exceeds the process' soft limit (%" PRIu64 ").",
505 lttng_opt_fd_pool_size, (uint64_t) rlimit.rlim_cur);
506 ret = -1;
507 goto end;
508 }
509
510 DBG("File descriptor pool size argument (%u) adjusted to %u to accomodate transient fd uses",
511 lttng_opt_fd_pool_size,
512 lttng_opt_fd_pool_size - DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE);
513 lttng_opt_fd_pool_size -= DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE;
514end:
515 return ret;
516}
517
7591bab1 518static int set_options(int argc, char **argv)
cd60b05a 519{
178a0557 520 int c, ret = 0, option_index = 0, retval = 0;
cd60b05a
JG
521 int orig_optopt = optopt, orig_optind = optind;
522 char *default_address, *optstring;
523 const char *config_path = NULL;
524
525 optstring = utils_generate_optstring(long_options,
526 sizeof(long_options) / sizeof(struct option));
527 if (!optstring) {
178a0557 528 retval = -ENOMEM;
cd60b05a
JG
529 goto exit;
530 }
531
532 /* Check for the --config option */
533
534 while ((c = getopt_long(argc, argv, optstring, long_options,
535 &option_index)) != -1) {
536 if (c == '?') {
178a0557 537 retval = -EINVAL;
cd60b05a
JG
538 goto exit;
539 } else if (c != 'f') {
540 continue;
541 }
542
e8fa9fb0
MD
543 if (lttng_is_setuid_setgid()) {
544 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
545 "-f, --config");
546 } else {
547 config_path = utils_expand_path(optarg);
548 if (!config_path) {
549 ERR("Failed to resolve path: %s", optarg);
550 }
cd60b05a
JG
551 }
552 }
553
554 ret = config_get_section_entries(config_path, config_section_name,
555 config_entry_handler, NULL);
556 if (ret) {
557 if (ret > 0) {
558 ERR("Invalid configuration option at line %i", ret);
cd60b05a 559 }
178a0557 560 retval = -1;
cd60b05a
JG
561 goto exit;
562 }
b8aa1682 563
cd60b05a
JG
564 /* Reset getopt's global state */
565 optopt = orig_optopt;
566 optind = orig_optind;
b8aa1682 567 while (1) {
cd60b05a 568 c = getopt_long(argc, argv, optstring, long_options, &option_index);
b8aa1682
JD
569 if (c == -1) {
570 break;
571 }
572
cd60b05a
JG
573 ret = set_option(c, optarg, long_options[option_index].name);
574 if (ret < 0) {
178a0557 575 retval = -1;
b8aa1682
JD
576 goto exit;
577 }
578 }
579
580 /* assign default values */
581 if (control_uri == NULL) {
fa91dc52
MD
582 ret = asprintf(&default_address,
583 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS ":%d",
584 DEFAULT_NETWORK_CONTROL_PORT);
b8aa1682
JD
585 if (ret < 0) {
586 PERROR("asprintf default data address");
178a0557 587 retval = -1;
b8aa1682
JD
588 goto exit;
589 }
590
591 ret = uri_parse(default_address, &control_uri);
592 free(default_address);
593 if (ret < 0) {
594 ERR("Invalid control URI specified");
178a0557 595 retval = -1;
b8aa1682
JD
596 goto exit;
597 }
598 }
599 if (data_uri == NULL) {
fa91dc52
MD
600 ret = asprintf(&default_address,
601 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS ":%d",
602 DEFAULT_NETWORK_DATA_PORT);
b8aa1682
JD
603 if (ret < 0) {
604 PERROR("asprintf default data address");
178a0557 605 retval = -1;
b8aa1682
JD
606 goto exit;
607 }
608
609 ret = uri_parse(default_address, &data_uri);
610 free(default_address);
611 if (ret < 0) {
612 ERR("Invalid data URI specified");
178a0557 613 retval = -1;
b8aa1682
JD
614 goto exit;
615 }
616 }
d3e2ba59 617 if (live_uri == NULL) {
fa91dc52
MD
618 ret = asprintf(&default_address,
619 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS ":%d",
620 DEFAULT_NETWORK_VIEWER_PORT);
d3e2ba59
JD
621 if (ret < 0) {
622 PERROR("asprintf default viewer control address");
178a0557 623 retval = -1;
d3e2ba59
JD
624 goto exit;
625 }
626
627 ret = uri_parse(default_address, &live_uri);
628 free(default_address);
629 if (ret < 0) {
630 ERR("Invalid viewer control URI specified");
178a0557 631 retval = -1;
d3e2ba59
JD
632 goto exit;
633 }
634 }
5c0551f9
JG
635 ret = set_fd_pool_size();
636 if (ret) {
637 retval = -1;
638 goto exit;
896010e3 639 }
b8aa1682 640
a8b66566
JR
641 if (opt_group_output_by == RELAYD_GROUP_OUTPUT_BY_UNKNOWN) {
642 opt_group_output_by = RELAYD_GROUP_OUTPUT_BY_HOST;
643 }
35ab25e5
MD
644 if (opt_allow_clear) {
645 /* Check if env variable exists. */
646 const char *value = lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV);
647 if (value) {
648 ret = config_parse_value(value);
649 if (ret < 0) {
650 ERR("Invalid value for %s specified", DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV);
651 retval = -1;
652 goto exit;
653 }
654 opt_allow_clear = !ret;
655 }
656 }
a8b66566 657
b8aa1682 658exit:
cd60b05a 659 free(optstring);
178a0557 660 return retval;
b8aa1682
JD
661}
662
7591bab1
MD
663static void print_global_objects(void)
664{
7591bab1
MD
665 print_viewer_streams();
666 print_relay_streams();
667 print_sessions();
7591bab1
MD
668}
669
5c0551f9
JG
670static int noop_close(void *data, int *fds)
671{
672 return 0;
673}
674
675static void untrack_stdio(void)
676{
677 int fds[] = { fileno(stdout), fileno(stderr) };
678
679 /*
680 * noop_close is used since we don't really want to close
681 * the stdio output fds; we merely want to stop tracking them.
682 */
683 (void) fd_tracker_close_unsuspendable_fd(the_fd_tracker,
684 fds, 2, noop_close, NULL);
685}
686
b8aa1682
JD
687/*
688 * Cleanup the daemon
689 */
7591bab1 690static void relayd_cleanup(void)
b8aa1682 691{
7591bab1
MD
692 print_global_objects();
693
b8aa1682
JD
694 DBG("Cleaning up");
695
178a0557
MD
696 if (viewer_streams_ht)
697 lttng_ht_destroy(viewer_streams_ht);
698 if (relay_streams_ht)
699 lttng_ht_destroy(relay_streams_ht);
7591bab1
MD
700 if (sessions_ht)
701 lttng_ht_destroy(sessions_ht);
178a0557 702
095a4ae5 703 free(opt_output_path);
ce9ee1fb 704 free(opt_working_directory);
095a4ae5 705
794e2e5f
JG
706 if (health_relayd) {
707 health_app_destroy(health_relayd);
708 }
a02de639 709 /* Close thread quit pipes */
bcee2b96
JG
710 if (health_quit_pipe[0] != -1) {
711 (void) fd_tracker_util_pipe_close(
712 the_fd_tracker, health_quit_pipe);
713 }
67609994
JG
714 if (thread_quit_pipe[0] != -1) {
715 (void) fd_tracker_util_pipe_close(
716 the_fd_tracker, thread_quit_pipe);
717 }
794e2e5f
JG
718 if (sessiond_trace_chunk_registry) {
719 sessiond_trace_chunk_registry_destroy(
720 sessiond_trace_chunk_registry);
721 }
00e3b7f1 722 if (the_fd_tracker) {
9c256b01
JG
723 untrack_stdio();
724 /*
725 * fd_tracker_destroy() will log the contents of the fd-tracker
726 * if a leak is detected.
727 */
00e3b7f1
JG
728 fd_tracker_destroy(the_fd_tracker);
729 }
794e2e5f 730
710c1f73
DG
731 uri_free(control_uri);
732 uri_free(data_uri);
8d5c808e 733 /* Live URI is freed in the live thread. */
cd60b05a
JG
734
735 if (tracing_group_name_override) {
736 free((void *) tracing_group_name);
737 }
b8aa1682
JD
738}
739
740/*
741 * Write to writable pipe used to notify a thread.
742 */
7591bab1 743static int notify_thread_pipe(int wpipe)
b8aa1682 744{
6cd525e8 745 ssize_t ret;
b8aa1682 746
6cd525e8
MD
747 ret = lttng_write(wpipe, "!", 1);
748 if (ret < 1) {
b8aa1682 749 PERROR("write poll pipe");
b4aacfdc 750 goto end;
b8aa1682 751 }
b4aacfdc
MD
752 ret = 0;
753end:
b8aa1682
JD
754 return ret;
755}
756
7591bab1 757static int notify_health_quit_pipe(int *pipe)
65931c8b 758{
6cd525e8 759 ssize_t ret;
65931c8b 760
6cd525e8
MD
761 ret = lttng_write(pipe[1], "4", 1);
762 if (ret < 1) {
65931c8b 763 PERROR("write relay health quit");
b4aacfdc 764 goto end;
65931c8b 765 }
b4aacfdc
MD
766 ret = 0;
767end:
768 return ret;
65931c8b
MD
769}
770
b8aa1682 771/*
b4aacfdc 772 * Stop all relayd and relayd-live threads.
b8aa1682 773 */
b4aacfdc 774int lttng_relay_stop_threads(void)
b8aa1682 775{
b4aacfdc 776 int retval = 0;
b8aa1682
JD
777
778 /* Stopping all threads */
779 DBG("Terminating all threads");
b4aacfdc 780 if (notify_thread_pipe(thread_quit_pipe[1])) {
b8aa1682 781 ERR("write error on thread quit pipe");
b4aacfdc 782 retval = -1;
b8aa1682
JD
783 }
784
b4aacfdc
MD
785 if (notify_health_quit_pipe(health_quit_pipe)) {
786 ERR("write error on health quit pipe");
787 }
65931c8b 788
b8aa1682 789 /* Dispatch thread */
26c9d55e 790 CMM_STORE_SHARED(dispatch_thread_exit, 1);
58eb9381 791 futex_nto1_wake(&relay_conn_queue.futex);
178a0557 792
b4aacfdc 793 if (relayd_live_stop()) {
178a0557 794 ERR("Error stopping live threads");
b4aacfdc 795 retval = -1;
178a0557 796 }
b4aacfdc 797 return retval;
b8aa1682
JD
798}
799
800/*
801 * Signal handler for the daemon
802 *
803 * Simply stop all worker threads, leaving main() return gracefully after
804 * joining all threads and calling cleanup().
805 */
7591bab1 806static void sighandler(int sig)
b8aa1682
JD
807{
808 switch (sig) {
b8aa1682
JD
809 case SIGINT:
810 DBG("SIGINT caught");
b4aacfdc
MD
811 if (lttng_relay_stop_threads()) {
812 ERR("Error stopping threads");
813 }
b8aa1682
JD
814 break;
815 case SIGTERM:
816 DBG("SIGTERM caught");
b4aacfdc
MD
817 if (lttng_relay_stop_threads()) {
818 ERR("Error stopping threads");
819 }
b8aa1682 820 break;
3fd27398
MD
821 case SIGUSR1:
822 CMM_STORE_SHARED(recv_child_signal, 1);
823 break;
b8aa1682
JD
824 default:
825 break;
826 }
827}
828
829/*
830 * Setup signal handler for :
831 * SIGINT, SIGTERM, SIGPIPE
832 */
7591bab1 833static int set_signal_handler(void)
b8aa1682
JD
834{
835 int ret = 0;
836 struct sigaction sa;
837 sigset_t sigset;
838
839 if ((ret = sigemptyset(&sigset)) < 0) {
840 PERROR("sigemptyset");
841 return ret;
842 }
843
b8aa1682
JD
844 sa.sa_mask = sigset;
845 sa.sa_flags = 0;
0072e5e2
MD
846
847 sa.sa_handler = sighandler;
b8aa1682
JD
848 if ((ret = sigaction(SIGTERM, &sa, NULL)) < 0) {
849 PERROR("sigaction");
850 return ret;
851 }
852
853 if ((ret = sigaction(SIGINT, &sa, NULL)) < 0) {
854 PERROR("sigaction");
855 return ret;
856 }
857
0072e5e2 858 if ((ret = sigaction(SIGUSR1, &sa, NULL)) < 0) {
b8aa1682
JD
859 PERROR("sigaction");
860 return ret;
861 }
862
0072e5e2
MD
863 sa.sa_handler = SIG_IGN;
864 if ((ret = sigaction(SIGPIPE, &sa, NULL)) < 0) {
3fd27398
MD
865 PERROR("sigaction");
866 return ret;
867 }
868
869 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
b8aa1682
JD
870
871 return ret;
872}
873
3fd27398
MD
874void lttng_relay_notify_ready(void)
875{
876 /* Notify the parent of the fork() process that we are ready. */
877 if (opt_daemon || opt_background) {
878 if (uatomic_sub_return(&lttng_relay_ready, 1) == 0) {
879 kill(child_ppid, SIGUSR1);
880 }
881 }
882}
883
b8aa1682
JD
884/*
885 * Init thread quit pipe.
886 *
887 * Return -1 on error or 0 if all pipes are created.
888 */
7591bab1 889static int init_thread_quit_pipe(void)
b8aa1682 890{
67609994
JG
891 return fd_tracker_util_pipe_open_cloexec(
892 the_fd_tracker, "Quit pipe", thread_quit_pipe);
b8aa1682
JD
893}
894
bcee2b96
JG
895/*
896 * Init health quit pipe.
897 *
898 * Return -1 on error or 0 if all pipes are created.
899 */
900static int init_health_quit_pipe(void)
901{
902 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker,
903 "Health quit pipe", health_quit_pipe);
904}
905
b8aa1682
JD
906/*
907 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
908 */
e32a0864
JG
909static int create_named_thread_poll_set(struct lttng_poll_event *events,
910 int size, const char *name)
b8aa1682
JD
911{
912 int ret;
913
914 if (events == NULL || size == 0) {
915 ret = -1;
916 goto error;
917 }
918
e32a0864
JG
919 ret = fd_tracker_util_poll_create(the_fd_tracker,
920 name, events, 1, LTTNG_CLOEXEC);
b8aa1682
JD
921
922 /* Add quit pipe */
c7759e6a 923 ret = lttng_poll_add(events, thread_quit_pipe[0], LPOLLIN | LPOLLERR);
b8aa1682
JD
924 if (ret < 0) {
925 goto error;
926 }
927
928 return 0;
929
930error:
931 return ret;
932}
933
934/*
935 * Check if the thread quit pipe was triggered.
936 *
937 * Return 1 if it was triggered else 0;
938 */
7591bab1 939static int check_thread_quit_pipe(int fd, uint32_t events)
b8aa1682
JD
940{
941 if (fd == thread_quit_pipe[0] && (events & LPOLLIN)) {
942 return 1;
943 }
944
945 return 0;
946}
947
40212d87
JG
948static int create_sock(void *data, int *out_fd)
949{
950 int ret;
951 struct lttcomm_sock *sock = data;
952
953 ret = lttcomm_create_sock(sock);
954 if (ret < 0) {
955 goto end;
956 }
957
958 *out_fd = sock->fd;
959end:
960 return ret;
961}
962
963static int close_sock(void *data, int *in_fd)
964{
965 struct lttcomm_sock *sock = data;
966
967 return sock->ops->close(sock);
968}
969
f355467e
JG
970static int accept_sock(void *data, int *out_fd)
971{
972 int ret = 0;
973 /* Socks is an array of in_sock, out_sock. */
974 struct lttcomm_sock **socks = data;
975 struct lttcomm_sock *in_sock = socks[0];
976
977 socks[1] = in_sock->ops->accept(in_sock);
978 if (!socks[1]) {
979 ret = -1;
980 goto end;
981 }
982 *out_fd = socks[1]->fd;
983end:
984 return ret;
985}
986
b8aa1682
JD
987/*
988 * Create and init socket from uri.
989 */
40212d87
JG
990static struct lttcomm_sock *relay_socket_create(struct lttng_uri *uri,
991 const char *name)
b8aa1682 992{
40212d87 993 int ret, sock_fd;
b8aa1682 994 struct lttcomm_sock *sock = NULL;
40212d87
JG
995 char uri_str[PATH_MAX];
996 char *formated_name = NULL;
b8aa1682
JD
997
998 sock = lttcomm_alloc_sock_from_uri(uri);
999 if (sock == NULL) {
1000 ERR("Allocating socket");
1001 goto error;
1002 }
1003
40212d87
JG
1004 /*
1005 * Don't fail to create the socket if the name can't be built as it is
1006 * only used for debugging purposes.
1007 */
1008 ret = uri_to_str_url(uri, uri_str, sizeof(uri_str));
1009 uri_str[sizeof(uri_str) - 1] = '\0';
1010 if (ret >= 0) {
1011 ret = asprintf(&formated_name, "%s socket @ %s", name,
1012 uri_str);
1013 if (ret < 0) {
1014 formated_name = NULL;
1015 }
b8aa1682 1016 }
40212d87
JG
1017
1018 ret = fd_tracker_open_unsuspendable_fd(the_fd_tracker, &sock_fd,
1019 (const char **) (formated_name ? &formated_name : NULL),
1020 1, create_sock, sock);
1021 free(formated_name);
1022 DBG("Listening on %s socket %d", name, sock->fd);
b8aa1682
JD
1023
1024 ret = sock->ops->bind(sock);
1025 if (ret < 0) {
2288467f 1026 PERROR("Failed to bind socket");
b8aa1682
JD
1027 goto error;
1028 }
1029
1030 ret = sock->ops->listen(sock, -1);
1031 if (ret < 0) {
1032 goto error;
1033
1034 }
1035
1036 return sock;
1037
1038error:
1039 if (sock) {
1040 lttcomm_destroy_sock(sock);
1041 }
1042 return NULL;
1043}
1044
f355467e
JG
1045static
1046struct lttcomm_sock *accept_relayd_sock(struct lttcomm_sock *listening_sock,
1047 const char *name)
1048{
1049 int out_fd, ret;
1050 struct lttcomm_sock *socks[2] = { listening_sock, NULL };
1051 struct lttcomm_sock *new_sock = NULL;
1052
1053 ret = fd_tracker_open_unsuspendable_fd(
1054 the_fd_tracker, &out_fd,
1055 (const char **) &name,
1056 1, accept_sock, &socks);
1057 if (ret) {
1058 goto end;
1059 }
1060 new_sock = socks[1];
1061 DBG("%s accepted, socket %d", name, new_sock->fd);
1062end:
1063 return new_sock;
1064}
1065
b8aa1682
JD
1066/*
1067 * This thread manages the listening for new connections on the network
1068 */
7591bab1 1069static void *relay_thread_listener(void *data)
b8aa1682 1070{
095a4ae5 1071 int i, ret, pollfd, err = -1;
b8aa1682
JD
1072 uint32_t revents, nb_fd;
1073 struct lttng_poll_event events;
1074 struct lttcomm_sock *control_sock, *data_sock;
1075
b8aa1682
JD
1076 DBG("[thread] Relay listener started");
1077
8fba2b8d 1078 rcu_register_thread();
55706a7d
MD
1079 health_register(health_relayd, HEALTH_RELAYD_TYPE_LISTENER);
1080
f385ae0a
MD
1081 health_code_update();
1082
40212d87 1083 control_sock = relay_socket_create(control_uri, "Control listener");
b8aa1682 1084 if (!control_sock) {
095a4ae5 1085 goto error_sock_control;
b8aa1682
JD
1086 }
1087
40212d87 1088 data_sock = relay_socket_create(data_uri, "Data listener");
b8aa1682 1089 if (!data_sock) {
095a4ae5 1090 goto error_sock_relay;
b8aa1682
JD
1091 }
1092
1093 /*
7591bab1
MD
1094 * Pass 3 as size here for the thread quit pipe, control and
1095 * data socket.
b8aa1682 1096 */
ba9cf8e1 1097 ret = create_named_thread_poll_set(&events, 3, "Listener thread epoll");
b8aa1682
JD
1098 if (ret < 0) {
1099 goto error_create_poll;
1100 }
1101
1102 /* Add the control socket */
1103 ret = lttng_poll_add(&events, control_sock->fd, LPOLLIN | LPOLLRDHUP);
1104 if (ret < 0) {
1105 goto error_poll_add;
1106 }
1107
1108 /* Add the data socket */
1109 ret = lttng_poll_add(&events, data_sock->fd, LPOLLIN | LPOLLRDHUP);
1110 if (ret < 0) {
1111 goto error_poll_add;
1112 }
1113
3fd27398
MD
1114 lttng_relay_notify_ready();
1115
9b5e0863
MD
1116 if (testpoint(relayd_thread_listener)) {
1117 goto error_testpoint;
1118 }
1119
b8aa1682 1120 while (1) {
f385ae0a
MD
1121 health_code_update();
1122
b8aa1682
JD
1123 DBG("Listener accepting connections");
1124
b8aa1682 1125restart:
f385ae0a 1126 health_poll_entry();
b8aa1682 1127 ret = lttng_poll_wait(&events, -1);
f385ae0a 1128 health_poll_exit();
b8aa1682
JD
1129 if (ret < 0) {
1130 /*
1131 * Restart interrupted system call.
1132 */
1133 if (errno == EINTR) {
1134 goto restart;
1135 }
1136 goto error;
1137 }
1138
0d9c5d77
DG
1139 nb_fd = ret;
1140
b8aa1682
JD
1141 DBG("Relay new connection received");
1142 for (i = 0; i < nb_fd; i++) {
f385ae0a
MD
1143 health_code_update();
1144
b8aa1682
JD
1145 /* Fetch once the poll data */
1146 revents = LTTNG_POLL_GETEV(&events, i);
1147 pollfd = LTTNG_POLL_GETFD(&events, i);
1148
1149 /* Thread quit pipe has been closed. Killing thread. */
1150 ret = check_thread_quit_pipe(pollfd, revents);
1151 if (ret) {
095a4ae5
MD
1152 err = 0;
1153 goto exit;
b8aa1682
JD
1154 }
1155
03e43155 1156 if (revents & LPOLLIN) {
4b7f17b2 1157 /*
7591bab1
MD
1158 * A new connection is requested, therefore a
1159 * sessiond/consumerd connection is allocated in
1160 * this thread, enqueued to a global queue and
1161 * dequeued (and freed) in the worker thread.
4b7f17b2 1162 */
58eb9381
DG
1163 int val = 1;
1164 struct relay_connection *new_conn;
f355467e 1165 struct lttcomm_sock *newsock = NULL;
7591bab1 1166 enum connection_type type;
b8aa1682
JD
1167
1168 if (pollfd == data_sock->fd) {
7591bab1 1169 type = RELAY_DATA;
f355467e
JG
1170 newsock = accept_relayd_sock(data_sock,
1171 "Data socket to relayd");
4b7f17b2
MD
1172 } else {
1173 assert(pollfd == control_sock->fd);
7591bab1 1174 type = RELAY_CONTROL;
875e3164
JG
1175 newsock = accept_relayd_sock(control_sock,
1176 "Control socket to relayd");
b8aa1682 1177 }
58eb9381
DG
1178 if (!newsock) {
1179 PERROR("accepting sock");
58eb9381
DG
1180 goto error;
1181 }
1182
1183 ret = setsockopt(newsock->fd, SOL_SOCKET, SO_REUSEADDR, &val,
1184 sizeof(val));
b8aa1682
JD
1185 if (ret < 0) {
1186 PERROR("setsockopt inet");
4b7f17b2 1187 lttcomm_destroy_sock(newsock);
b8aa1682
JD
1188 goto error;
1189 }
f056029c
JR
1190
1191 ret = socket_apply_keep_alive_config(newsock->fd);
1192 if (ret < 0) {
1193 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
1194 newsock->fd);
1195 lttcomm_destroy_sock(newsock);
1196 goto error;
1197 }
1198
7591bab1
MD
1199 new_conn = connection_create(newsock, type);
1200 if (!new_conn) {
1201 lttcomm_destroy_sock(newsock);
1202 goto error;
1203 }
58eb9381
DG
1204
1205 /* Enqueue request for the dispatcher thread. */
8bdee6e2
SM
1206 cds_wfcq_enqueue(&relay_conn_queue.head, &relay_conn_queue.tail,
1207 &new_conn->qnode);
b8aa1682
JD
1208
1209 /*
7591bab1
MD
1210 * Wake the dispatch queue futex.
1211 * Implicit memory barrier with the
1212 * exchange in cds_wfcq_enqueue.
b8aa1682 1213 */
58eb9381 1214 futex_nto1_wake(&relay_conn_queue.futex);
03e43155
MD
1215 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
1216 ERR("socket poll error");
1217 goto error;
1218 } else {
1219 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
1220 goto error;
b8aa1682
JD
1221 }
1222 }
1223 }
1224
095a4ae5 1225exit:
b8aa1682
JD
1226error:
1227error_poll_add:
9b5e0863 1228error_testpoint:
ba9cf8e1 1229 (void) fd_tracker_util_poll_clean(the_fd_tracker, &events);
b8aa1682 1230error_create_poll:
095a4ae5 1231 if (data_sock->fd >= 0) {
40212d87
JG
1232 int data_sock_fd = data_sock->fd;
1233
1234 ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker,
1235 &data_sock_fd, 1, close_sock,
1236 data_sock);
b8aa1682 1237 if (ret) {
40212d87 1238 PERROR("Failed to close the data listener socket file descriptor");
b8aa1682 1239 }
40212d87 1240 data_sock->fd = -1;
b8aa1682 1241 }
095a4ae5
MD
1242 lttcomm_destroy_sock(data_sock);
1243error_sock_relay:
1244 if (control_sock->fd >= 0) {
40212d87
JG
1245 int control_sock_fd = control_sock->fd;
1246
1247 ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker,
1248 &control_sock_fd, 1, close_sock,
1249 control_sock);
b8aa1682 1250 if (ret) {
40212d87 1251 PERROR("Failed to close the control listener socket file descriptor");
b8aa1682 1252 }
40212d87 1253 control_sock->fd = -1;
b8aa1682 1254 }
095a4ae5
MD
1255 lttcomm_destroy_sock(control_sock);
1256error_sock_control:
1257 if (err) {
f385ae0a
MD
1258 health_error();
1259 ERR("Health error occurred in %s", __func__);
095a4ae5 1260 }
55706a7d 1261 health_unregister(health_relayd);
8fba2b8d 1262 rcu_unregister_thread();
b8aa1682 1263 DBG("Relay listener thread cleanup complete");
b4aacfdc 1264 lttng_relay_stop_threads();
b8aa1682
JD
1265 return NULL;
1266}
1267
1268/*
1269 * This thread manages the dispatching of the requests to worker threads
1270 */
7591bab1 1271static void *relay_thread_dispatcher(void *data)
b8aa1682 1272{
6cd525e8
MD
1273 int err = -1;
1274 ssize_t ret;
8bdee6e2 1275 struct cds_wfcq_node *node;
58eb9381 1276 struct relay_connection *new_conn = NULL;
b8aa1682
JD
1277
1278 DBG("[thread] Relay dispatcher started");
1279
55706a7d
MD
1280 health_register(health_relayd, HEALTH_RELAYD_TYPE_DISPATCHER);
1281
9b5e0863
MD
1282 if (testpoint(relayd_thread_dispatcher)) {
1283 goto error_testpoint;
1284 }
1285
f385ae0a
MD
1286 health_code_update();
1287
0ed3b1a8 1288 for (;;) {
f385ae0a
MD
1289 health_code_update();
1290
b8aa1682 1291 /* Atomically prepare the queue futex */
58eb9381 1292 futex_nto1_prepare(&relay_conn_queue.futex);
b8aa1682 1293
0ed3b1a8
MD
1294 if (CMM_LOAD_SHARED(dispatch_thread_exit)) {
1295 break;
1296 }
1297
b8aa1682 1298 do {
f385ae0a
MD
1299 health_code_update();
1300
b8aa1682 1301 /* Dequeue commands */
8bdee6e2
SM
1302 node = cds_wfcq_dequeue_blocking(&relay_conn_queue.head,
1303 &relay_conn_queue.tail);
b8aa1682
JD
1304 if (node == NULL) {
1305 DBG("Woken up but nothing in the relay command queue");
1306 /* Continue thread execution */
1307 break;
1308 }
58eb9381 1309 new_conn = caa_container_of(node, struct relay_connection, qnode);
b8aa1682 1310
58eb9381 1311 DBG("Dispatching request waiting on sock %d", new_conn->sock->fd);
b8aa1682
JD
1312
1313 /*
7591bab1
MD
1314 * Inform worker thread of the new request. This
1315 * call is blocking so we can be assured that
1316 * the data will be read at some point in time
1317 * or wait to the end of the world :)
b8aa1682 1318 */
58eb9381
DG
1319 ret = lttng_write(relay_conn_pipe[1], &new_conn, sizeof(new_conn));
1320 if (ret < 0) {
1321 PERROR("write connection pipe");
7591bab1 1322 connection_put(new_conn);
b8aa1682
JD
1323 goto error;
1324 }
1325 } while (node != NULL);
1326
1327 /* Futex wait on queue. Blocking call on futex() */
f385ae0a 1328 health_poll_entry();
58eb9381 1329 futex_nto1_wait(&relay_conn_queue.futex);
f385ae0a 1330 health_poll_exit();
b8aa1682
JD
1331 }
1332
f385ae0a
MD
1333 /* Normal exit, no error */
1334 err = 0;
1335
b8aa1682 1336error:
9b5e0863 1337error_testpoint:
f385ae0a
MD
1338 if (err) {
1339 health_error();
1340 ERR("Health error occurred in %s", __func__);
1341 }
55706a7d 1342 health_unregister(health_relayd);
b8aa1682 1343 DBG("Dispatch thread dying");
b4aacfdc 1344 lttng_relay_stop_threads();
b8aa1682
JD
1345 return NULL;
1346}
1347
298a25ca
JG
1348static bool session_streams_have_index(const struct relay_session *session)
1349{
1350 return session->minor >= 4 && !session->snapshot;
1351}
1352
c5b6f4f0
DG
1353/*
1354 * Handle the RELAYD_CREATE_SESSION command.
1355 *
1356 * On success, send back the session id or else return a negative value.
1357 */
5312a3ed
JG
1358static int relay_create_session(const struct lttcomm_relayd_hdr *recv_hdr,
1359 struct relay_connection *conn,
1360 const struct lttng_buffer_view *payload)
c5b6f4f0 1361{
5312a3ed
JG
1362 int ret = 0;
1363 ssize_t send_ret;
4c6885d2 1364 struct relay_session *session = NULL;
ecd1a12f 1365 struct lttcomm_relayd_create_session_reply_2_11 reply = {};
1e791a74
JG
1366 char session_name[LTTNG_NAME_MAX] = {};
1367 char hostname[LTTNG_HOST_NAME_MAX] = {};
7591bab1
MD
1368 uint32_t live_timer = 0;
1369 bool snapshot = false;
46ef2188 1370 bool session_name_contains_creation_timestamp = false;
23c8ff50 1371 /* Left nil for peers < 2.11. */
6fa5fe7c 1372 char base_path[LTTNG_PATH_MAX] = {};
23c8ff50 1373 lttng_uuid sessiond_uuid = {};
1e791a74
JG
1374 LTTNG_OPTIONAL(uint64_t) id_sessiond = {};
1375 LTTNG_OPTIONAL(uint64_t) current_chunk_id = {};
db1da059 1376 LTTNG_OPTIONAL(time_t) creation_time = {};
ecd1a12f
MD
1377 struct lttng_dynamic_buffer reply_payload;
1378
1379 lttng_dynamic_buffer_init(&reply_payload);
c5b6f4f0 1380
f86f6389
JR
1381 if (conn->minor < 4) {
1382 /* From 2.1 to 2.3 */
1383 ret = 0;
1384 } else if (conn->minor >= 4 && conn->minor < 11) {
1385 /* From 2.4 to 2.10 */
5312a3ed 1386 ret = cmd_create_session_2_4(payload, session_name,
7591bab1 1387 hostname, &live_timer, &snapshot);
f86f6389 1388 } else {
84fa4db5 1389 bool has_current_chunk;
db1da059
JG
1390 uint64_t current_chunk_id_value;
1391 time_t creation_time_value;
1392 uint64_t id_sessiond_value;
84fa4db5 1393
f86f6389 1394 /* From 2.11 to ... */
db1da059 1395 ret = cmd_create_session_2_11(payload, session_name, hostname,
6fa5fe7c 1396 base_path, &live_timer, &snapshot, &id_sessiond_value,
db1da059 1397 sessiond_uuid, &has_current_chunk,
46ef2188
MD
1398 &current_chunk_id_value, &creation_time_value,
1399 &session_name_contains_creation_timestamp);
23c8ff50
JG
1400 if (lttng_uuid_is_nil(sessiond_uuid)) {
1401 /* The nil UUID is reserved for pre-2.11 clients. */
1402 ERR("Illegal nil UUID announced by peer in create session command");
1403 ret = -1;
1404 goto send_reply;
1405 }
db1da059
JG
1406 LTTNG_OPTIONAL_SET(&id_sessiond, id_sessiond_value);
1407 LTTNG_OPTIONAL_SET(&creation_time, creation_time_value);
1408 if (has_current_chunk) {
1409 LTTNG_OPTIONAL_SET(&current_chunk_id,
1410 current_chunk_id_value);
1411 }
7591bab1 1412 }
f86f6389 1413
7591bab1
MD
1414 if (ret < 0) {
1415 goto send_reply;
d3e2ba59
JD
1416 }
1417
6fa5fe7c 1418 session = session_create(session_name, hostname, base_path, live_timer,
1e791a74
JG
1419 snapshot, sessiond_uuid,
1420 id_sessiond.is_set ? &id_sessiond.value : NULL,
1421 current_chunk_id.is_set ? &current_chunk_id.value : NULL,
db1da059 1422 creation_time.is_set ? &creation_time.value : NULL,
46ef2188
MD
1423 conn->major, conn->minor,
1424 session_name_contains_creation_timestamp);
7591bab1
MD
1425 if (!session) {
1426 ret = -1;
1427 goto send_reply;
1428 }
1429 assert(!conn->session);
1430 conn->session = session;
c5b6f4f0
DG
1431 DBG("Created session %" PRIu64, session->id);
1432
ecd1a12f 1433 reply.generic.session_id = htobe64(session->id);
7591bab1
MD
1434
1435send_reply:
c5b6f4f0 1436 if (ret < 0) {
ecd1a12f 1437 reply.generic.ret_code = htobe32(LTTNG_ERR_FATAL);
c5b6f4f0 1438 } else {
ecd1a12f 1439 reply.generic.ret_code = htobe32(LTTNG_OK);
c5b6f4f0
DG
1440 }
1441
ecd1a12f
MD
1442 if (conn->minor < 11) {
1443 /* From 2.1 to 2.10 */
1444 ret = lttng_dynamic_buffer_append(&reply_payload,
1445 &reply.generic, sizeof(reply.generic));
1446 if (ret) {
1447 ERR("Failed to append \"create session\" command reply header to payload buffer");
1448 ret = -1;
1449 goto end;
1450 }
1451 } else {
1452 const uint32_t output_path_length =
8d382dd4 1453 session ? strlen(session->output_path) + 1 : 0;
ecd1a12f
MD
1454
1455 reply.output_path_length = htobe32(output_path_length);
8d382dd4
JG
1456 ret = lttng_dynamic_buffer_append(
1457 &reply_payload, &reply, sizeof(reply));
ecd1a12f
MD
1458 if (ret) {
1459 ERR("Failed to append \"create session\" command reply header to payload buffer");
1460 goto end;
1461 }
1462
8d382dd4
JG
1463 if (output_path_length) {
1464 ret = lttng_dynamic_buffer_append(&reply_payload,
1465 session->output_path,
1466 output_path_length);
1467 if (ret) {
1468 ERR("Failed to append \"create session\" command reply path to payload buffer");
1469 goto end;
1470 }
ecd1a12f
MD
1471 }
1472 }
1473
1474 send_ret = conn->sock->ops->sendmsg(conn->sock, reply_payload.data,
1475 reply_payload.size, 0);
1476 if (send_ret < (ssize_t) reply_payload.size) {
1477 ERR("Failed to send \"create session\" command reply of %zu bytes (ret = %zd)",
1478 reply_payload.size, send_ret);
5312a3ed 1479 ret = -1;
c5b6f4f0 1480 }
ecd1a12f 1481end:
4c6885d2
JG
1482 if (ret < 0 && session) {
1483 session_put(session);
1484 }
ecd1a12f 1485 lttng_dynamic_buffer_reset(&reply_payload);
c5b6f4f0
DG
1486 return ret;
1487}
1488
a4baae1b
JD
1489/*
1490 * When we have received all the streams and the metadata for a channel,
1491 * we make them visible to the viewer threads.
1492 */
7591bab1 1493static void publish_connection_local_streams(struct relay_connection *conn)
a4baae1b 1494{
7591bab1
MD
1495 struct relay_stream *stream;
1496 struct relay_session *session = conn->session;
a4baae1b 1497
7591bab1
MD
1498 /*
1499 * We publish all streams belonging to a session atomically wrt
1500 * session lock.
1501 */
1502 pthread_mutex_lock(&session->lock);
1503 rcu_read_lock();
1504 cds_list_for_each_entry_rcu(stream, &session->recv_list,
1505 recv_node) {
1506 stream_publish(stream);
a4baae1b 1507 }
7591bab1 1508 rcu_read_unlock();
a4baae1b 1509
7591bab1
MD
1510 /*
1511 * Inform the viewer that there are new streams in the session.
1512 */
1513 if (session->viewer_attached) {
1514 uatomic_set(&session->new_streams, 1);
1515 }
1516 pthread_mutex_unlock(&session->lock);
a4baae1b
JD
1517}
1518
348a81dc
JG
1519static int conform_channel_path(char *channel_path)
1520{
1521 int ret = 0;
1522
1523 if (strstr("../", channel_path)) {
1524 ERR("Refusing channel path as it walks up the path hierarchy: \"%s\"",
1525 channel_path);
1526 ret = -1;
1527 goto end;
1528 }
1529
1530 if (*channel_path == '/') {
1531 const size_t len = strlen(channel_path);
1532
1533 /*
1534 * Channel paths from peers prior to 2.11 are expressed as an
1535 * absolute path that is, in reality, relative to the relay
1536 * daemon's output directory. Remove the leading slash so it
1537 * is correctly interpreted as a relative path later on.
1538 *
1539 * len (and not len - 1) is used to copy the trailing NULL.
1540 */
1541 bcopy(channel_path + 1, channel_path, len);
1542 }
1543end:
1544 return ret;
1545}
1546
b8aa1682
JD
1547/*
1548 * relay_add_stream: allocate a new stream for a session
1549 */
5312a3ed
JG
1550static int relay_add_stream(const struct lttcomm_relayd_hdr *recv_hdr,
1551 struct relay_connection *conn,
1552 const struct lttng_buffer_view *payload)
b8aa1682 1553{
7591bab1
MD
1554 int ret;
1555 ssize_t send_ret;
58eb9381 1556 struct relay_session *session = conn->session;
b8aa1682
JD
1557 struct relay_stream *stream = NULL;
1558 struct lttcomm_relayd_status_stream reply;
4030a636 1559 struct ctf_trace *trace = NULL;
7591bab1
MD
1560 uint64_t stream_handle = -1ULL;
1561 char *path_name = NULL, *channel_name = NULL;
1562 uint64_t tracefile_size = 0, tracefile_count = 0;
348a81dc 1563 LTTNG_OPTIONAL(uint64_t) stream_chunk_id = {};
b8aa1682 1564
5312a3ed 1565 if (!session || !conn->version_check_done) {
b8aa1682
JD
1566 ERR("Trying to add a stream before version check");
1567 ret = -1;
1568 goto end_no_session;
1569 }
1570
2f21a469
JR
1571 if (session->minor == 1) {
1572 /* For 2.1 */
5312a3ed 1573 ret = cmd_recv_stream_2_1(payload, &path_name,
7591bab1 1574 &channel_name);
2f21a469
JR
1575 } else if (session->minor > 1 && session->minor < 11) {
1576 /* From 2.2 to 2.10 */
5312a3ed 1577 ret = cmd_recv_stream_2_2(payload, &path_name,
7591bab1 1578 &channel_name, &tracefile_size, &tracefile_count);
2f21a469
JR
1579 } else {
1580 /* From 2.11 to ... */
1581 ret = cmd_recv_stream_2_11(payload, &path_name,
0b50e4b3
JG
1582 &channel_name, &tracefile_size, &tracefile_count,
1583 &stream_chunk_id.value);
1584 stream_chunk_id.is_set = true;
0f907de1 1585 }
2f21a469 1586
0f907de1 1587 if (ret < 0) {
7591bab1 1588 goto send_reply;
b8aa1682
JD
1589 }
1590
348a81dc
JG
1591 if (conform_channel_path(path_name)) {
1592 goto send_reply;
1593 }
1594
2a635488
JR
1595 /*
1596 * Backward compatibility for --group-output-by-session.
1597 * Prior to lttng 2.11, the complete path is passed by the stream.
1598 * Starting at 2.11, lttng-relayd uses chunk. When dealing with producer
1599 * >=2.11 the chunk is responsible for the output path. When dealing
1600 * with producer < 2.11 the chunk output_path is the root output path
1601 * and the stream carries the complete path (path_name).
1602 * To support --group-output-by-session with older producer (<2.11), we
1603 * need to craft the path based on the stream path.
1604 */
1605 if (opt_group_output_by == RELAYD_GROUP_OUTPUT_BY_SESSION) {
1606 if (conn->minor < 4) {
1607 /*
1608 * From 2.1 to 2.3, the session_name is not passed on
1609 * the RELAYD_CREATE_SESSION command. The session name
1610 * is necessary to detect the presence of a base_path
1611 * inside the stream path. Without it we cannot perform
1612 * a valid group-output-by-session transformation.
1613 */
1614 WARN("Unable to perform a --group-by-session transformation for session %" PRIu64
1615 " for stream with path \"%s\" as it is produced by a peer using a protocol older than v2.4",
1616 session->id, path_name);
1617 } else if (conn->minor >= 4 && conn->minor < 11) {
1618 char *group_by_session_path_name;
1619
1620 assert(session->session_name[0] != '\0');
1621
1622 group_by_session_path_name =
1623 backward_compat_group_by_session(
1624 path_name,
1625 session->session_name);
1626 if (!group_by_session_path_name) {
1627 ERR("Failed to apply group by session to stream of session %" PRIu64,
1628 session->id);
1629 goto send_reply;
1630 }
1631
1632 DBG("Transformed session path from \"%s\" to \"%s\" to honor per-session name grouping",
1633 path_name, group_by_session_path_name);
1634
1635 free(path_name);
1636 path_name = group_by_session_path_name;
1637 }
1638 }
1639
7591bab1 1640 trace = ctf_trace_get_by_path_or_create(session, path_name);
2a174661 1641 if (!trace) {
7591bab1 1642 goto send_reply;
2a174661 1643 }
2a174661 1644
2a635488 1645 /* This stream here has one reference on the trace. */
7591bab1
MD
1646 pthread_mutex_lock(&last_relay_stream_id_lock);
1647 stream_handle = ++last_relay_stream_id;
1648 pthread_mutex_unlock(&last_relay_stream_id_lock);
d3e2ba59 1649
7591bab1
MD
1650 /* We pass ownership of path_name and channel_name. */
1651 stream = stream_create(trace, stream_handle, path_name,
348a81dc 1652 channel_name, tracefile_size, tracefile_count);
7591bab1
MD
1653 path_name = NULL;
1654 channel_name = NULL;
a4baae1b 1655
2a174661 1656 /*
7591bab1
MD
1657 * Streams are the owners of their trace. Reference to trace is
1658 * kept within stream_create().
2a174661 1659 */
7591bab1 1660 ctf_trace_put(trace);
d3e2ba59 1661
7591bab1 1662send_reply:
53efb85a 1663 memset(&reply, 0, sizeof(reply));
7591bab1
MD
1664 reply.handle = htobe64(stream_handle);
1665 if (!stream) {
f73fabfd 1666 reply.ret_code = htobe32(LTTNG_ERR_UNK);
b8aa1682 1667 } else {
f73fabfd 1668 reply.ret_code = htobe32(LTTNG_OK);
b8aa1682 1669 }
5af40280 1670
58eb9381 1671 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
b8aa1682 1672 sizeof(struct lttcomm_relayd_status_stream), 0);
5312a3ed
JG
1673 if (send_ret < (ssize_t) sizeof(reply)) {
1674 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1675 send_ret);
1676 ret = -1;
b8aa1682
JD
1677 }
1678
1679end_no_session:
7591bab1
MD
1680 free(path_name);
1681 free(channel_name);
0f907de1 1682 return ret;
b8aa1682
JD
1683}
1684
173af62f
DG
1685/*
1686 * relay_close_stream: close a specific stream
1687 */
5312a3ed
JG
1688static int relay_close_stream(const struct lttcomm_relayd_hdr *recv_hdr,
1689 struct relay_connection *conn,
1690 const struct lttng_buffer_view *payload)
173af62f 1691{
5312a3ed
JG
1692 int ret;
1693 ssize_t send_ret;
58eb9381 1694 struct relay_session *session = conn->session;
173af62f
DG
1695 struct lttcomm_relayd_close_stream stream_info;
1696 struct lttcomm_relayd_generic_reply reply;
1697 struct relay_stream *stream;
173af62f
DG
1698
1699 DBG("Close stream received");
1700
5312a3ed 1701 if (!session || !conn->version_check_done) {
173af62f
DG
1702 ERR("Trying to close a stream before version check");
1703 ret = -1;
1704 goto end_no_session;
1705 }
1706
5312a3ed
JG
1707 if (payload->size < sizeof(stream_info)) {
1708 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1709 sizeof(stream_info), payload->size);
173af62f
DG
1710 ret = -1;
1711 goto end_no_session;
1712 }
5312a3ed
JG
1713 memcpy(&stream_info, payload->data, sizeof(stream_info));
1714 stream_info.stream_id = be64toh(stream_info.stream_id);
1715 stream_info.last_net_seq_num = be64toh(stream_info.last_net_seq_num);
173af62f 1716
5312a3ed 1717 stream = stream_get_by_id(stream_info.stream_id);
173af62f
DG
1718 if (!stream) {
1719 ret = -1;
7591bab1 1720 goto end;
173af62f 1721 }
77f7bd85
MD
1722
1723 /*
1724 * Set last_net_seq_num before the close flag. Required by data
1725 * pending check.
1726 */
7591bab1 1727 pthread_mutex_lock(&stream->lock);
5312a3ed 1728 stream->last_net_seq_num = stream_info.last_net_seq_num;
77f7bd85
MD
1729 pthread_mutex_unlock(&stream->lock);
1730
bda7c7b9
JG
1731 /*
1732 * This is one of the conditions which may trigger a stream close
1733 * with the others being:
1734 * 1) A close command is received for a stream
1735 * 2) The control connection owning the stream is closed
1736 * 3) We have received all of the stream's data _after_ a close
1737 * request.
1738 */
1739 try_stream_close(stream);
7591bab1
MD
1740 if (stream->is_metadata) {
1741 struct relay_viewer_stream *vstream;
173af62f 1742
7591bab1
MD
1743 vstream = viewer_stream_get_by_id(stream->stream_handle);
1744 if (vstream) {
94f73d08 1745 if (stream->no_new_metadata_notified) {
7591bab1
MD
1746 /*
1747 * Since all the metadata has been sent to the
1748 * viewer and that we have a request to close
1749 * its stream, we can safely teardown the
1750 * corresponding metadata viewer stream.
1751 */
1752 viewer_stream_put(vstream);
1753 }
1754 /* Put local reference. */
1755 viewer_stream_put(vstream);
1756 }
1757 }
7591bab1 1758 stream_put(stream);
5312a3ed 1759 ret = 0;
173af62f 1760
7591bab1 1761end:
53efb85a 1762 memset(&reply, 0, sizeof(reply));
173af62f 1763 if (ret < 0) {
f73fabfd 1764 reply.ret_code = htobe32(LTTNG_ERR_UNK);
173af62f 1765 } else {
f73fabfd 1766 reply.ret_code = htobe32(LTTNG_OK);
173af62f 1767 }
58eb9381 1768 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
173af62f 1769 sizeof(struct lttcomm_relayd_generic_reply), 0);
5312a3ed
JG
1770 if (send_ret < (ssize_t) sizeof(reply)) {
1771 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1772 send_ret);
1773 ret = -1;
173af62f
DG
1774 }
1775
1776end_no_session:
1777 return ret;
1778}
1779
93ec662e
JD
1780/*
1781 * relay_reset_metadata: reset a metadata stream
1782 */
1783static
5312a3ed
JG
1784int relay_reset_metadata(const struct lttcomm_relayd_hdr *recv_hdr,
1785 struct relay_connection *conn,
1786 const struct lttng_buffer_view *payload)
93ec662e 1787{
5312a3ed
JG
1788 int ret;
1789 ssize_t send_ret;
93ec662e
JD
1790 struct relay_session *session = conn->session;
1791 struct lttcomm_relayd_reset_metadata stream_info;
1792 struct lttcomm_relayd_generic_reply reply;
1793 struct relay_stream *stream;
1794
1795 DBG("Reset metadata received");
1796
5312a3ed 1797 if (!session || !conn->version_check_done) {
93ec662e
JD
1798 ERR("Trying to reset a metadata stream before version check");
1799 ret = -1;
1800 goto end_no_session;
1801 }
1802
5312a3ed
JG
1803 if (payload->size < sizeof(stream_info)) {
1804 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1805 sizeof(stream_info), payload->size);
93ec662e
JD
1806 ret = -1;
1807 goto end_no_session;
1808 }
5312a3ed
JG
1809 memcpy(&stream_info, payload->data, sizeof(stream_info));
1810 stream_info.stream_id = be64toh(stream_info.stream_id);
1811 stream_info.version = be64toh(stream_info.version);
1812
1813 DBG("Update metadata to version %" PRIu64, stream_info.version);
93ec662e
JD
1814
1815 /* Unsupported for live sessions for now. */
1816 if (session->live_timer != 0) {
1817 ret = -1;
1818 goto end;
1819 }
1820
5312a3ed 1821 stream = stream_get_by_id(stream_info.stream_id);
93ec662e
JD
1822 if (!stream) {
1823 ret = -1;
1824 goto end;
1825 }
1826 pthread_mutex_lock(&stream->lock);
1827 if (!stream->is_metadata) {
1828 ret = -1;
1829 goto end_unlock;
1830 }
1831
c35f9726 1832 ret = stream_reset_file(stream);
93ec662e 1833 if (ret < 0) {
c35f9726
JG
1834 ERR("Failed to reset metadata stream %" PRIu64
1835 ": stream_path = %s, channel = %s",
1836 stream->stream_handle, stream->path_name,
1837 stream->channel_name);
93ec662e
JD
1838 goto end_unlock;
1839 }
93ec662e
JD
1840end_unlock:
1841 pthread_mutex_unlock(&stream->lock);
1842 stream_put(stream);
1843
1844end:
1845 memset(&reply, 0, sizeof(reply));
1846 if (ret < 0) {
1847 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1848 } else {
1849 reply.ret_code = htobe32(LTTNG_OK);
1850 }
1851 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1852 sizeof(struct lttcomm_relayd_generic_reply), 0);
5312a3ed
JG
1853 if (send_ret < (ssize_t) sizeof(reply)) {
1854 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1855 send_ret);
1856 ret = -1;
93ec662e
JD
1857 }
1858
1859end_no_session:
1860 return ret;
1861}
1862
b8aa1682
JD
1863/*
1864 * relay_unknown_command: send -1 if received unknown command
1865 */
7591bab1 1866static void relay_unknown_command(struct relay_connection *conn)
b8aa1682
JD
1867{
1868 struct lttcomm_relayd_generic_reply reply;
5312a3ed 1869 ssize_t send_ret;
b8aa1682 1870
53efb85a 1871 memset(&reply, 0, sizeof(reply));
f73fabfd 1872 reply.ret_code = htobe32(LTTNG_ERR_UNK);
5312a3ed
JG
1873 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1874 if (send_ret < sizeof(reply)) {
1875 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret);
b8aa1682
JD
1876 }
1877}
1878
1879/*
1880 * relay_start: send an acknowledgment to the client to tell if we are
1881 * ready to receive data. We are ready if a session is established.
1882 */
5312a3ed
JG
1883static int relay_start(const struct lttcomm_relayd_hdr *recv_hdr,
1884 struct relay_connection *conn,
1885 const struct lttng_buffer_view *payload)
b8aa1682 1886{
5312a3ed
JG
1887 int ret = 0;
1888 ssize_t send_ret;
b8aa1682 1889 struct lttcomm_relayd_generic_reply reply;
58eb9381 1890 struct relay_session *session = conn->session;
b8aa1682
JD
1891
1892 if (!session) {
1893 DBG("Trying to start the streaming without a session established");
f73fabfd 1894 ret = htobe32(LTTNG_ERR_UNK);
b8aa1682
JD
1895 }
1896
53efb85a 1897 memset(&reply, 0, sizeof(reply));
5312a3ed
JG
1898 reply.ret_code = htobe32(LTTNG_OK);
1899 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1900 sizeof(reply), 0);
1901 if (send_ret < (ssize_t) sizeof(reply)) {
1902 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1903 send_ret);
1904 ret = -1;
b8aa1682
JD
1905 }
1906
1907 return ret;
1908}
1909
b8aa1682 1910/*
7591bab1 1911 * relay_recv_metadata: receive the metadata for the session.
b8aa1682 1912 */
5312a3ed
JG
1913static int relay_recv_metadata(const struct lttcomm_relayd_hdr *recv_hdr,
1914 struct relay_connection *conn,
1915 const struct lttng_buffer_view *payload)
b8aa1682 1916{
32d1569c 1917 int ret = 0;
58eb9381 1918 struct relay_session *session = conn->session;
5312a3ed 1919 struct lttcomm_relayd_metadata_payload metadata_payload_header;
b8aa1682 1920 struct relay_stream *metadata_stream;
5312a3ed 1921 uint64_t metadata_payload_size;
c35f9726 1922 struct lttng_buffer_view packet_view;
b8aa1682
JD
1923
1924 if (!session) {
1925 ERR("Metadata sent before version check");
1926 ret = -1;
1927 goto end;
1928 }
1929
5312a3ed 1930 if (recv_hdr->data_size < sizeof(struct lttcomm_relayd_metadata_payload)) {
f6416125
MD
1931 ERR("Incorrect data size");
1932 ret = -1;
1933 goto end;
1934 }
5312a3ed
JG
1935 metadata_payload_size = recv_hdr->data_size -
1936 sizeof(struct lttcomm_relayd_metadata_payload);
f6416125 1937
5312a3ed
JG
1938 memcpy(&metadata_payload_header, payload->data,
1939 sizeof(metadata_payload_header));
1940 metadata_payload_header.stream_id = be64toh(
1941 metadata_payload_header.stream_id);
1942 metadata_payload_header.padding_size = be32toh(
1943 metadata_payload_header.padding_size);
9d1bbf21 1944
5312a3ed 1945 metadata_stream = stream_get_by_id(metadata_payload_header.stream_id);
b8aa1682
JD
1946 if (!metadata_stream) {
1947 ret = -1;
7591bab1 1948 goto end;
b8aa1682
JD
1949 }
1950
c35f9726
JG
1951 packet_view = lttng_buffer_view_from_view(payload,
1952 sizeof(metadata_payload_header), metadata_payload_size);
1953 if (!packet_view.data) {
1954 ERR("Invalid metadata packet length announced by header");
b8aa1682 1955 ret = -1;
7591bab1 1956 goto end_put;
b8aa1682 1957 }
1d4dfdef 1958
c35f9726
JG
1959 pthread_mutex_lock(&metadata_stream->lock);
1960 ret = stream_write(metadata_stream, &packet_view,
5312a3ed 1961 metadata_payload_header.padding_size);
c35f9726
JG
1962 pthread_mutex_unlock(&metadata_stream->lock);
1963 if (ret){
5312a3ed 1964 ret = -1;
7591bab1 1965 goto end_put;
1d4dfdef 1966 }
7591bab1 1967end_put:
7591bab1 1968 stream_put(metadata_stream);
b8aa1682
JD
1969end:
1970 return ret;
1971}
1972
1973/*
1974 * relay_send_version: send relayd version number
1975 */
5312a3ed
JG
1976static int relay_send_version(const struct lttcomm_relayd_hdr *recv_hdr,
1977 struct relay_connection *conn,
1978 const struct lttng_buffer_view *payload)
b8aa1682 1979{
7f51dcba 1980 int ret;
5312a3ed 1981 ssize_t send_ret;
092b6259 1982 struct lttcomm_relayd_version reply, msg;
87cb6359 1983 bool compatible = true;
b8aa1682 1984
5312a3ed 1985 conn->version_check_done = true;
b8aa1682 1986
092b6259 1987 /* Get version from the other side. */
5312a3ed
JG
1988 if (payload->size < sizeof(msg)) {
1989 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1990 sizeof(msg), payload->size);
092b6259 1991 ret = -1;
092b6259
DG
1992 goto end;
1993 }
1994
5312a3ed
JG
1995 memcpy(&msg, payload->data, sizeof(msg));
1996 msg.major = be32toh(msg.major);
1997 msg.minor = be32toh(msg.minor);
1998
53efb85a 1999 memset(&reply, 0, sizeof(reply));
d83a952c
MD
2000 reply.major = RELAYD_VERSION_COMM_MAJOR;
2001 reply.minor = RELAYD_VERSION_COMM_MINOR;
d4519fa3
JD
2002
2003 /* Major versions must be the same */
5312a3ed 2004 if (reply.major != msg.major) {
6151a90f 2005 DBG("Incompatible major versions (%u vs %u), deleting session",
5312a3ed 2006 reply.major, msg.major);
87cb6359 2007 compatible = false;
d4519fa3
JD
2008 }
2009
58eb9381 2010 conn->major = reply.major;
0f907de1 2011 /* We adapt to the lowest compatible version */
5312a3ed 2012 if (reply.minor <= msg.minor) {
58eb9381 2013 conn->minor = reply.minor;
0f907de1 2014 } else {
5312a3ed 2015 conn->minor = msg.minor;
0f907de1
JD
2016 }
2017
6151a90f
JD
2018 reply.major = htobe32(reply.major);
2019 reply.minor = htobe32(reply.minor);
5312a3ed
JG
2020 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
2021 sizeof(reply), 0);
2022 if (send_ret < (ssize_t) sizeof(reply)) {
2023 ERR("Failed to send \"send version\" command reply (ret = %zd)",
2024 send_ret);
2025 ret = -1;
2026 goto end;
2027 } else {
2028 ret = 0;
6151a90f
JD
2029 }
2030
87cb6359
JD
2031 if (!compatible) {
2032 ret = -1;
2033 goto end;
2034 }
2035
58eb9381
DG
2036 DBG("Version check done using protocol %u.%u", conn->major,
2037 conn->minor);
b8aa1682
JD
2038
2039end:
2040 return ret;
2041}
2042
c8f59ee5 2043/*
6d805429 2044 * Check for data pending for a given stream id from the session daemon.
c8f59ee5 2045 */
5312a3ed
JG
2046static int relay_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
2047 struct relay_connection *conn,
2048 const struct lttng_buffer_view *payload)
c8f59ee5 2049{
58eb9381 2050 struct relay_session *session = conn->session;
6d805429 2051 struct lttcomm_relayd_data_pending msg;
c8f59ee5
DG
2052 struct lttcomm_relayd_generic_reply reply;
2053 struct relay_stream *stream;
5312a3ed 2054 ssize_t send_ret;
c8f59ee5 2055 int ret;
298a25ca 2056 uint64_t stream_seq;
c8f59ee5 2057
6d805429 2058 DBG("Data pending command received");
c8f59ee5 2059
5312a3ed 2060 if (!session || !conn->version_check_done) {
c8f59ee5
DG
2061 ERR("Trying to check for data before version check");
2062 ret = -1;
2063 goto end_no_session;
2064 }
2065
5312a3ed
JG
2066 if (payload->size < sizeof(msg)) {
2067 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
2068 sizeof(msg), payload->size);
c8f59ee5
DG
2069 ret = -1;
2070 goto end_no_session;
2071 }
5312a3ed
JG
2072 memcpy(&msg, payload->data, sizeof(msg));
2073 msg.stream_id = be64toh(msg.stream_id);
2074 msg.last_net_seq_num = be64toh(msg.last_net_seq_num);
c8f59ee5 2075
5312a3ed 2076 stream = stream_get_by_id(msg.stream_id);
de91f48a 2077 if (stream == NULL) {
c8f59ee5 2078 ret = -1;
7591bab1 2079 goto end;
c8f59ee5
DG
2080 }
2081
7591bab1
MD
2082 pthread_mutex_lock(&stream->lock);
2083
298a25ca
JG
2084 if (session_streams_have_index(session)) {
2085 /*
2086 * Ensure that both the index and stream data have been
2087 * flushed up to the requested point.
2088 */
a8f9f353 2089 stream_seq = min(stream->prev_data_seq, stream->prev_index_seq);
298a25ca 2090 } else {
a8f9f353 2091 stream_seq = stream->prev_data_seq;
298a25ca 2092 }
a8f9f353 2093 DBG("Data pending for stream id %" PRIu64 ": prev_data_seq %" PRIu64
298a25ca
JG
2094 ", prev_index_seq %" PRIu64
2095 ", and last_seq %" PRIu64, msg.stream_id,
a8f9f353 2096 stream->prev_data_seq, stream->prev_index_seq,
298a25ca 2097 msg.last_net_seq_num);
c8f59ee5 2098
33832e64 2099 /* Avoid wrapping issue */
298a25ca 2100 if (((int64_t) (stream_seq - msg.last_net_seq_num)) >= 0) {
6d805429 2101 /* Data has in fact been written and is NOT pending */
c8f59ee5 2102 ret = 0;
6d805429
DG
2103 } else {
2104 /* Data still being streamed thus pending */
2105 ret = 1;
c8f59ee5
DG
2106 }
2107
7591bab1
MD
2108 stream->data_pending_check_done = true;
2109 pthread_mutex_unlock(&stream->lock);
f7079f67 2110
7591bab1
MD
2111 stream_put(stream);
2112end:
c8f59ee5 2113
53efb85a 2114 memset(&reply, 0, sizeof(reply));
c8f59ee5 2115 reply.ret_code = htobe32(ret);
5312a3ed
JG
2116 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2117 if (send_ret < (ssize_t) sizeof(reply)) {
2118 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
2119 send_ret);
2120 ret = -1;
c8f59ee5
DG
2121 }
2122
2123end_no_session:
2124 return ret;
2125}
2126
2127/*
2128 * Wait for the control socket to reach a quiescent state.
2129 *
7591bab1
MD
2130 * Note that for now, when receiving this command from the session
2131 * daemon, this means that every subsequent commands or data received on
2132 * the control socket has been handled. So, this is why we simply return
2133 * OK here.
c8f59ee5 2134 */
5312a3ed
JG
2135static int relay_quiescent_control(const struct lttcomm_relayd_hdr *recv_hdr,
2136 struct relay_connection *conn,
2137 const struct lttng_buffer_view *payload)
c8f59ee5
DG
2138{
2139 int ret;
5312a3ed 2140 ssize_t send_ret;
ad7051c0 2141 struct relay_stream *stream;
ad7051c0 2142 struct lttcomm_relayd_quiescent_control msg;
c8f59ee5
DG
2143 struct lttcomm_relayd_generic_reply reply;
2144
2145 DBG("Checking quiescent state on control socket");
2146
5312a3ed 2147 if (!conn->session || !conn->version_check_done) {
ad7051c0
DG
2148 ERR("Trying to check for data before version check");
2149 ret = -1;
2150 goto end_no_session;
2151 }
2152
5312a3ed
JG
2153 if (payload->size < sizeof(msg)) {
2154 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2155 sizeof(msg), payload->size);
ad7051c0
DG
2156 ret = -1;
2157 goto end_no_session;
2158 }
5312a3ed
JG
2159 memcpy(&msg, payload->data, sizeof(msg));
2160 msg.stream_id = be64toh(msg.stream_id);
ad7051c0 2161
5312a3ed 2162 stream = stream_get_by_id(msg.stream_id);
7591bab1
MD
2163 if (!stream) {
2164 goto reply;
2165 }
2166 pthread_mutex_lock(&stream->lock);
2167 stream->data_pending_check_done = true;
2168 pthread_mutex_unlock(&stream->lock);
5312a3ed
JG
2169
2170 DBG("Relay quiescent control pending flag set to %" PRIu64, msg.stream_id);
7591bab1
MD
2171 stream_put(stream);
2172reply:
53efb85a 2173 memset(&reply, 0, sizeof(reply));
c8f59ee5 2174 reply.ret_code = htobe32(LTTNG_OK);
5312a3ed
JG
2175 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2176 if (send_ret < (ssize_t) sizeof(reply)) {
2177 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
2178 send_ret);
2179 ret = -1;
2180 } else {
2181 ret = 0;
c8f59ee5
DG
2182 }
2183
ad7051c0 2184end_no_session:
c8f59ee5
DG
2185 return ret;
2186}
2187
f7079f67 2188/*
7591bab1
MD
2189 * Initialize a data pending command. This means that a consumer is about
2190 * to ask for data pending for each stream it holds. Simply iterate over
2191 * all streams of a session and set the data_pending_check_done flag.
f7079f67
DG
2192 *
2193 * This command returns to the client a LTTNG_OK code.
2194 */
5312a3ed
JG
2195static int relay_begin_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
2196 struct relay_connection *conn,
2197 const struct lttng_buffer_view *payload)
f7079f67
DG
2198{
2199 int ret;
5312a3ed 2200 ssize_t send_ret;
f7079f67
DG
2201 struct lttng_ht_iter iter;
2202 struct lttcomm_relayd_begin_data_pending msg;
2203 struct lttcomm_relayd_generic_reply reply;
2204 struct relay_stream *stream;
f7079f67
DG
2205
2206 assert(recv_hdr);
58eb9381 2207 assert(conn);
f7079f67
DG
2208
2209 DBG("Init streams for data pending");
2210
5312a3ed 2211 if (!conn->session || !conn->version_check_done) {
f7079f67
DG
2212 ERR("Trying to check for data before version check");
2213 ret = -1;
2214 goto end_no_session;
2215 }
2216
5312a3ed
JG
2217 if (payload->size < sizeof(msg)) {
2218 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2219 sizeof(msg), payload->size);
f7079f67
DG
2220 ret = -1;
2221 goto end_no_session;
2222 }
5312a3ed
JG
2223 memcpy(&msg, payload->data, sizeof(msg));
2224 msg.session_id = be64toh(msg.session_id);
f7079f67
DG
2225
2226 /*
7591bab1
MD
2227 * Iterate over all streams to set the begin data pending flag.
2228 * For now, the streams are indexed by stream handle so we have
2229 * to iterate over all streams to find the one associated with
2230 * the right session_id.
f7079f67
DG
2231 */
2232 rcu_read_lock();
d3e2ba59 2233 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2a174661 2234 node.node) {
7591bab1
MD
2235 if (!stream_get(stream)) {
2236 continue;
2237 }
5312a3ed 2238 if (stream->trace->session->id == msg.session_id) {
7591bab1
MD
2239 pthread_mutex_lock(&stream->lock);
2240 stream->data_pending_check_done = false;
2241 pthread_mutex_unlock(&stream->lock);
f7079f67
DG
2242 DBG("Set begin data pending flag to stream %" PRIu64,
2243 stream->stream_handle);
2244 }
7591bab1 2245 stream_put(stream);
f7079f67
DG
2246 }
2247 rcu_read_unlock();
2248
53efb85a 2249 memset(&reply, 0, sizeof(reply));
f7079f67
DG
2250 /* All good, send back reply. */
2251 reply.ret_code = htobe32(LTTNG_OK);
2252
5312a3ed
JG
2253 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2254 if (send_ret < (ssize_t) sizeof(reply)) {
2255 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2256 send_ret);
2257 ret = -1;
2258 } else {
2259 ret = 0;
f7079f67
DG
2260 }
2261
2262end_no_session:
2263 return ret;
2264}
2265
2266/*
7591bab1
MD
2267 * End data pending command. This will check, for a given session id, if
2268 * each stream associated with it has its data_pending_check_done flag
2269 * set. If not, this means that the client lost track of the stream but
2270 * the data is still being streamed on our side. In this case, we inform
2271 * the client that data is in flight.
f7079f67
DG
2272 *
2273 * Return to the client if there is data in flight or not with a ret_code.
2274 */
5312a3ed
JG
2275static int relay_end_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
2276 struct relay_connection *conn,
2277 const struct lttng_buffer_view *payload)
f7079f67
DG
2278{
2279 int ret;
5312a3ed 2280 ssize_t send_ret;
f7079f67
DG
2281 struct lttng_ht_iter iter;
2282 struct lttcomm_relayd_end_data_pending msg;
2283 struct lttcomm_relayd_generic_reply reply;
2284 struct relay_stream *stream;
f7079f67
DG
2285 uint32_t is_data_inflight = 0;
2286
f7079f67
DG
2287 DBG("End data pending command");
2288
5312a3ed 2289 if (!conn->session || !conn->version_check_done) {
f7079f67
DG
2290 ERR("Trying to check for data before version check");
2291 ret = -1;
2292 goto end_no_session;
2293 }
2294
5312a3ed
JG
2295 if (payload->size < sizeof(msg)) {
2296 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2297 sizeof(msg), payload->size);
f7079f67
DG
2298 ret = -1;
2299 goto end_no_session;
2300 }
5312a3ed
JG
2301 memcpy(&msg, payload->data, sizeof(msg));
2302 msg.session_id = be64toh(msg.session_id);
f7079f67 2303
7591bab1
MD
2304 /*
2305 * Iterate over all streams to see if the begin data pending
2306 * flag is set.
2307 */
f7079f67 2308 rcu_read_lock();
d3e2ba59 2309 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2a174661 2310 node.node) {
7591bab1
MD
2311 if (!stream_get(stream)) {
2312 continue;
2313 }
5312a3ed 2314 if (stream->trace->session->id != msg.session_id) {
7591bab1
MD
2315 stream_put(stream);
2316 continue;
2317 }
2318 pthread_mutex_lock(&stream->lock);
2319 if (!stream->data_pending_check_done) {
298a25ca
JG
2320 uint64_t stream_seq;
2321
2322 if (session_streams_have_index(conn->session)) {
2323 /*
2324 * Ensure that both the index and stream data have been
2325 * flushed up to the requested point.
2326 */
a8f9f353 2327 stream_seq = min(stream->prev_data_seq, stream->prev_index_seq);
298a25ca 2328 } else {
a8f9f353 2329 stream_seq = stream->prev_data_seq;
298a25ca
JG
2330 }
2331 if (!stream->closed || !(((int64_t) (stream_seq - stream->last_net_seq_num)) >= 0)) {
7591bab1
MD
2332 is_data_inflight = 1;
2333 DBG("Data is still in flight for stream %" PRIu64,
2334 stream->stream_handle);
2335 pthread_mutex_unlock(&stream->lock);
2336 stream_put(stream);
2337 break;
2338 }
f7079f67 2339 }
7591bab1
MD
2340 pthread_mutex_unlock(&stream->lock);
2341 stream_put(stream);
f7079f67
DG
2342 }
2343 rcu_read_unlock();
2344
53efb85a 2345 memset(&reply, 0, sizeof(reply));
f7079f67
DG
2346 /* All good, send back reply. */
2347 reply.ret_code = htobe32(is_data_inflight);
2348
5312a3ed
JG
2349 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2350 if (send_ret < (ssize_t) sizeof(reply)) {
2351 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2352 send_ret);
2353 ret = -1;
2354 } else {
2355 ret = 0;
f7079f67
DG
2356 }
2357
2358end_no_session:
2359 return ret;
2360}
2361
1c20f0e2
JD
2362/*
2363 * Receive an index for a specific stream.
2364 *
2365 * Return 0 on success else a negative value.
2366 */
5312a3ed
JG
2367static int relay_recv_index(const struct lttcomm_relayd_hdr *recv_hdr,
2368 struct relay_connection *conn,
2369 const struct lttng_buffer_view *payload)
1c20f0e2 2370{
5312a3ed
JG
2371 int ret;
2372 ssize_t send_ret;
58eb9381 2373 struct relay_session *session = conn->session;
1c20f0e2 2374 struct lttcomm_relayd_index index_info;
1c20f0e2
JD
2375 struct lttcomm_relayd_generic_reply reply;
2376 struct relay_stream *stream;
f8f3885c 2377 size_t msg_len;
1c20f0e2 2378
58eb9381 2379 assert(conn);
1c20f0e2
JD
2380
2381 DBG("Relay receiving index");
2382
5312a3ed 2383 if (!session || !conn->version_check_done) {
1c20f0e2
JD
2384 ERR("Trying to close a stream before version check");
2385 ret = -1;
2386 goto end_no_session;
2387 }
2388
f8f3885c
MD
2389 msg_len = lttcomm_relayd_index_len(
2390 lttng_to_index_major(conn->major, conn->minor),
2391 lttng_to_index_minor(conn->major, conn->minor));
5312a3ed
JG
2392 if (payload->size < msg_len) {
2393 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2394 msg_len, payload->size);
1c20f0e2
JD
2395 ret = -1;
2396 goto end_no_session;
2397 }
5312a3ed
JG
2398 memcpy(&index_info, payload->data, msg_len);
2399 index_info.relay_stream_id = be64toh(index_info.relay_stream_id);
2400 index_info.net_seq_num = be64toh(index_info.net_seq_num);
2401 index_info.packet_size = be64toh(index_info.packet_size);
2402 index_info.content_size = be64toh(index_info.content_size);
2403 index_info.timestamp_begin = be64toh(index_info.timestamp_begin);
2404 index_info.timestamp_end = be64toh(index_info.timestamp_end);
2405 index_info.events_discarded = be64toh(index_info.events_discarded);
2406 index_info.stream_id = be64toh(index_info.stream_id);
81df238b
JR
2407
2408 if (conn->minor >= 8) {
2409 index_info.stream_instance_id =
2410 be64toh(index_info.stream_instance_id);
2411 index_info.packet_seq_num = be64toh(index_info.packet_seq_num);
0f83d1cc
MD
2412 } else {
2413 index_info.stream_instance_id = -1ULL;
2414 index_info.packet_seq_num = -1ULL;
81df238b 2415 }
5312a3ed
JG
2416
2417 stream = stream_get_by_id(index_info.relay_stream_id);
1c20f0e2 2418 if (!stream) {
7591bab1 2419 ERR("stream_get_by_id not found");
1c20f0e2 2420 ret = -1;
7591bab1 2421 goto end;
1c20f0e2 2422 }
d3e2ba59 2423
c35f9726
JG
2424 pthread_mutex_lock(&stream->lock);
2425 ret = stream_add_index(stream, &index_info);
2426 pthread_mutex_unlock(&stream->lock);
2427 if (ret) {
7591bab1
MD
2428 goto end_stream_put;
2429 }
1c20f0e2 2430
7591bab1 2431end_stream_put:
7591bab1 2432 stream_put(stream);
7591bab1 2433end:
53efb85a 2434 memset(&reply, 0, sizeof(reply));
1c20f0e2
JD
2435 if (ret < 0) {
2436 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2437 } else {
2438 reply.ret_code = htobe32(LTTNG_OK);
2439 }
58eb9381 2440 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
5312a3ed
JG
2441 if (send_ret < (ssize_t) sizeof(reply)) {
2442 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret);
2443 ret = -1;
1c20f0e2
JD
2444 }
2445
2446end_no_session:
2447 return ret;
2448}
2449
a4baae1b
JD
2450/*
2451 * Receive the streams_sent message.
2452 *
2453 * Return 0 on success else a negative value.
2454 */
5312a3ed
JG
2455static int relay_streams_sent(const struct lttcomm_relayd_hdr *recv_hdr,
2456 struct relay_connection *conn,
2457 const struct lttng_buffer_view *payload)
a4baae1b 2458{
5312a3ed
JG
2459 int ret;
2460 ssize_t send_ret;
a4baae1b
JD
2461 struct lttcomm_relayd_generic_reply reply;
2462
58eb9381 2463 assert(conn);
a4baae1b
JD
2464
2465 DBG("Relay receiving streams_sent");
2466
5312a3ed 2467 if (!conn->session || !conn->version_check_done) {
a4baae1b
JD
2468 ERR("Trying to close a stream before version check");
2469 ret = -1;
2470 goto end_no_session;
2471 }
2472
2473 /*
7591bab1
MD
2474 * Publish every pending stream in the connection recv list which are
2475 * now ready to be used by the viewer.
4a9daf17 2476 */
7591bab1 2477 publish_connection_local_streams(conn);
4a9daf17 2478
53efb85a 2479 memset(&reply, 0, sizeof(reply));
a4baae1b 2480 reply.ret_code = htobe32(LTTNG_OK);
58eb9381 2481 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
5312a3ed
JG
2482 if (send_ret < (ssize_t) sizeof(reply)) {
2483 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2484 send_ret);
2485 ret = -1;
a4baae1b
JD
2486 } else {
2487 /* Success. */
2488 ret = 0;
2489 }
2490
2491end_no_session:
2492 return ret;
2493}
2494
d3ecc550 2495/*
c35f9726
JG
2496 * relay_rotate_session_stream: rotate a stream to a new tracefile for the
2497 * session rotation feature (not the tracefile rotation feature).
d3ecc550 2498 */
c35f9726
JG
2499static int relay_rotate_session_streams(
2500 const struct lttcomm_relayd_hdr *recv_hdr,
5312a3ed
JG
2501 struct relay_connection *conn,
2502 const struct lttng_buffer_view *payload)
d3ecc550 2503{
30b9d5ab 2504 int ret = 0;
c35f9726 2505 uint32_t i;
5312a3ed 2506 ssize_t send_ret;
c35f9726 2507 enum lttng_error_code reply_code = LTTNG_ERR_UNK;
d3ecc550 2508 struct relay_session *session = conn->session;
c35f9726
JG
2509 struct lttcomm_relayd_rotate_streams rotate_streams;
2510 struct lttcomm_relayd_generic_reply reply = {};
2511 struct relay_stream *stream = NULL;
2512 const size_t header_len = sizeof(struct lttcomm_relayd_rotate_streams);
2513 struct lttng_trace_chunk *next_trace_chunk = NULL;
2514 struct lttng_buffer_view stream_positions;
70626904
JG
2515 char chunk_id_buf[MAX_INT_DEC_LEN(uint64_t)];
2516 const char *chunk_id_str = "none";
d3ecc550 2517
d3ecc550
JD
2518 if (!session || !conn->version_check_done) {
2519 ERR("Trying to rotate a stream before version check");
2520 ret = -1;
2521 goto end_no_reply;
2522 }
2523
2524 if (session->major == 2 && session->minor < 11) {
2525 ERR("Unsupported feature before 2.11");
2526 ret = -1;
2527 goto end_no_reply;
2528 }
2529
5312a3ed
JG
2530 if (payload->size < header_len) {
2531 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2532 header_len, payload->size);
d3ecc550
JD
2533 ret = -1;
2534 goto end_no_reply;
2535 }
2536
c35f9726 2537 memcpy(&rotate_streams, payload->data, header_len);
5312a3ed 2538
c35f9726
JG
2539 /* Convert header to host endianness. */
2540 rotate_streams = (typeof(rotate_streams)) {
2541 .stream_count = be32toh(rotate_streams.stream_count),
2542 .new_chunk_id = (typeof(rotate_streams.new_chunk_id)) {
2543 .is_set = !!rotate_streams.new_chunk_id.is_set,
2544 .value = be64toh(rotate_streams.new_chunk_id.value),
2545 }
2546 };
d3ecc550 2547
c35f9726
JG
2548 if (rotate_streams.new_chunk_id.is_set) {
2549 /*
2550 * Retrieve the trace chunk the stream must transition to. As
2551 * per the protocol, this chunk should have been created
2552 * before this command is received.
2553 */
2554 next_trace_chunk = sessiond_trace_chunk_registry_get_chunk(
2555 sessiond_trace_chunk_registry,
2556 session->sessiond_uuid, session->id,
2557 rotate_streams.new_chunk_id.value);
2558 if (!next_trace_chunk) {
c70636a7 2559 char uuid_str[LTTNG_UUID_STR_LEN];
c35f9726
JG
2560
2561 lttng_uuid_to_str(session->sessiond_uuid, uuid_str);
2562 ERR("Unknown next trace chunk in ROTATE_STREAMS command: sessiond_uuid = {%s}, session_id = %" PRIu64
2563 ", trace_chunk_id = %" PRIu64,
2564 uuid_str, session->id,
2565 rotate_streams.new_chunk_id.value);
2566 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2567 ret = -1;
2568 goto end;
2569 }
70626904
JG
2570
2571 ret = snprintf(chunk_id_buf, sizeof(chunk_id_buf), "%" PRIu64,
2572 rotate_streams.new_chunk_id.value);
2573 if (ret < 0 || ret >= sizeof(chunk_id_buf)) {
2574 chunk_id_str = "formatting error";
2575 } else {
2576 chunk_id_str = chunk_id_buf;
2577 }
d3ecc550
JD
2578 }
2579
70626904
JG
2580 DBG("Rotate %" PRIu32 " streams of session \"%s\" to chunk \"%s\"",
2581 rotate_streams.stream_count, session->session_name,
2582 chunk_id_str);
2583
c35f9726
JG
2584 stream_positions = lttng_buffer_view_from_view(payload,
2585 sizeof(rotate_streams), -1);
2586 if (!stream_positions.data ||
2587 stream_positions.size <
2588 (rotate_streams.stream_count *
2589 sizeof(struct lttcomm_relayd_stream_rotation_position))) {
2590 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
d3ecc550 2591 ret = -1;
5312a3ed 2592 goto end;
d3ecc550
JD
2593 }
2594
c35f9726
JG
2595 for (i = 0; i < rotate_streams.stream_count; i++) {
2596 struct lttcomm_relayd_stream_rotation_position *position_comm =
2597 &((typeof(position_comm)) stream_positions.data)[i];
2598 const struct lttcomm_relayd_stream_rotation_position pos = {
2599 .stream_id = be64toh(position_comm->stream_id),
2600 .rotate_at_seq_num = be64toh(
2601 position_comm->rotate_at_seq_num),
2602 };
5312a3ed 2603
c35f9726
JG
2604 stream = stream_get_by_id(pos.stream_id);
2605 if (!stream) {
2606 reply_code = LTTNG_ERR_INVALID;
2607 ret = -1;
2608 goto end;
c6db3843
JG
2609 }
2610
c35f9726
JG
2611 pthread_mutex_lock(&stream->lock);
2612 ret = stream_set_pending_rotation(stream, next_trace_chunk,
2613 pos.rotate_at_seq_num);
2614 pthread_mutex_unlock(&stream->lock);
2615 if (ret) {
2616 reply_code = LTTNG_ERR_FILE_CREATION_ERROR;
2617 goto end;
c6db3843 2618 }
c35f9726
JG
2619
2620 stream_put(stream);
2621 stream = NULL;
d3ecc550
JD
2622 }
2623
c35f9726 2624 reply_code = LTTNG_OK;
eaeb64a9 2625 ret = 0;
d3ecc550 2626end:
c35f9726
JG
2627 if (stream) {
2628 stream_put(stream);
d3ecc550 2629 }
c35f9726
JG
2630
2631 reply.ret_code = htobe32((uint32_t) reply_code);
d3ecc550
JD
2632 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
2633 sizeof(struct lttcomm_relayd_generic_reply), 0);
5312a3ed
JG
2634 if (send_ret < (ssize_t) sizeof(reply)) {
2635 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2636 send_ret);
2637 ret = -1;
d3ecc550 2638 }
d3ecc550 2639end_no_reply:
c35f9726 2640 lttng_trace_chunk_put(next_trace_chunk);
d3ecc550
JD
2641 return ret;
2642}
2643
e5add6d0 2644
e5add6d0
JG
2645
2646/*
2647 * relay_create_trace_chunk: create a new trace chunk
2648 */
2649static int relay_create_trace_chunk(const struct lttcomm_relayd_hdr *recv_hdr,
2650 struct relay_connection *conn,
2651 const struct lttng_buffer_view *payload)
2652{
2653 int ret = 0;
2654 ssize_t send_ret;
2655 struct relay_session *session = conn->session;
2656 struct lttcomm_relayd_create_trace_chunk *msg;
2657 struct lttcomm_relayd_generic_reply reply = {};
2658 struct lttng_buffer_view header_view;
2659 struct lttng_buffer_view chunk_name_view;
2660 struct lttng_trace_chunk *chunk = NULL, *published_chunk = NULL;
2661 enum lttng_error_code reply_code = LTTNG_OK;
2662 enum lttng_trace_chunk_status chunk_status;
a7ceb342 2663 const char *new_path;
e5add6d0
JG
2664
2665 if (!session || !conn->version_check_done) {
2666 ERR("Trying to create a trace chunk before version check");
2667 ret = -1;
2668 goto end_no_reply;
2669 }
2670
2671 if (session->major == 2 && session->minor < 11) {
2672 ERR("Chunk creation command is unsupported before 2.11");
2673 ret = -1;
2674 goto end_no_reply;
2675 }
2676
2677 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
2678 if (!header_view.data) {
2679 ERR("Failed to receive payload of chunk creation command");
2680 ret = -1;
2681 goto end_no_reply;
2682 }
2683
2684 /* Convert to host endianness. */
2685 msg = (typeof(msg)) header_view.data;
2686 msg->chunk_id = be64toh(msg->chunk_id);
2687 msg->creation_timestamp = be64toh(msg->creation_timestamp);
2688 msg->override_name_length = be32toh(msg->override_name_length);
2689
a7ceb342
MD
2690 if (session->current_trace_chunk &&
2691 !lttng_trace_chunk_get_name_overridden(session->current_trace_chunk)) {
2692 chunk_status = lttng_trace_chunk_rename_path(session->current_trace_chunk,
2693 DEFAULT_CHUNK_TMP_OLD_DIRECTORY);
2694 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2695 ERR("Failed to rename old chunk");
2696 ret = -1;
2697 reply_code = LTTNG_ERR_UNK;
2698 goto end;
2699 }
2700 }
2701 session->ongoing_rotation = true;
2702 if (!session->current_trace_chunk) {
2703 if (!session->has_rotated) {
2704 new_path = "";
2705 } else {
2706 new_path = NULL;
2707 }
2708 } else {
2709 new_path = DEFAULT_CHUNK_TMP_NEW_DIRECTORY;
2710 }
e5add6d0 2711 chunk = lttng_trace_chunk_create(
a7ceb342 2712 msg->chunk_id, msg->creation_timestamp, new_path);
e5add6d0
JG
2713 if (!chunk) {
2714 ERR("Failed to create trace chunk in trace chunk creation command");
2715 ret = -1;
2716 reply_code = LTTNG_ERR_NOMEM;
2717 goto end;
2718 }
7145f5e9 2719 lttng_trace_chunk_set_fd_tracker(chunk, the_fd_tracker);
e5add6d0
JG
2720
2721 if (msg->override_name_length) {
2722 const char *name;
2723
2724 chunk_name_view = lttng_buffer_view_from_view(payload,
2725 sizeof(*msg),
2726 msg->override_name_length);
2727 name = chunk_name_view.data;
2728 if (!name || name[msg->override_name_length - 1]) {
2729 ERR("Failed to receive payload of chunk creation command");
2730 ret = -1;
2731 reply_code = LTTNG_ERR_INVALID;
2732 goto end;
2733 }
2734
2735 chunk_status = lttng_trace_chunk_override_name(
2736 chunk, chunk_name_view.data);
2737 switch (chunk_status) {
2738 case LTTNG_TRACE_CHUNK_STATUS_OK:
2739 break;
2740 case LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT:
2741 ERR("Failed to set the name of new trace chunk in trace chunk creation command (invalid name)");
2742 reply_code = LTTNG_ERR_INVALID;
2743 ret = -1;
2744 goto end;
2745 default:
2746 ERR("Failed to set the name of new trace chunk in trace chunk creation command (unknown error)");
2747 reply_code = LTTNG_ERR_UNK;
2748 ret = -1;
2749 goto end;
2750 }
2751 }
2752
e5add6d0
JG
2753 chunk_status = lttng_trace_chunk_set_credentials_current_user(chunk);
2754 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2755 reply_code = LTTNG_ERR_UNK;
2756 ret = -1;
2757 goto end;
2758 }
2759
7ceefac4
JG
2760 assert(conn->session->output_directory);
2761 chunk_status = lttng_trace_chunk_set_as_owner(chunk,
2762 conn->session->output_directory);
e5add6d0
JG
2763 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2764 reply_code = LTTNG_ERR_UNK;
2765 ret = -1;
2766 goto end;
2767 }
2768
2769 published_chunk = sessiond_trace_chunk_registry_publish_chunk(
2770 sessiond_trace_chunk_registry,
2771 conn->session->sessiond_uuid,
2772 conn->session->id,
2773 chunk);
2774 if (!published_chunk) {
c70636a7 2775 char uuid_str[LTTNG_UUID_STR_LEN];
e5add6d0
JG
2776
2777 lttng_uuid_to_str(conn->session->sessiond_uuid, uuid_str);
2778 ERR("Failed to publish chunk: sessiond_uuid = %s, session_id = %" PRIu64 ", chunk_id = %" PRIu64,
2779 uuid_str,
2780 conn->session->id,
2781 msg->chunk_id);
2782 ret = -1;
2783 reply_code = LTTNG_ERR_NOMEM;
2784 goto end;
2785 }
2786
2787 pthread_mutex_lock(&conn->session->lock);
62bad3bf
JG
2788 if (conn->session->pending_closure_trace_chunk) {
2789 /*
2790 * Invalid; this means a second create_trace_chunk command was
2791 * received before a close_trace_chunk.
2792 */
2793 ERR("Invalid trace chunk close command received; a trace chunk is already waiting for a trace chunk close command");
2794 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2795 ret = -1;
2796 goto end_unlock_session;
2797 }
2798 conn->session->pending_closure_trace_chunk =
2799 conn->session->current_trace_chunk;
e5add6d0 2800 conn->session->current_trace_chunk = published_chunk;
e5add6d0 2801 published_chunk = NULL;
a7ceb342
MD
2802 if (!conn->session->pending_closure_trace_chunk) {
2803 session->ongoing_rotation = false;
2804 }
62bad3bf 2805end_unlock_session:
c35f9726 2806 pthread_mutex_unlock(&conn->session->lock);
e5add6d0
JG
2807end:
2808 reply.ret_code = htobe32((uint32_t) reply_code);
2809 send_ret = conn->sock->ops->sendmsg(conn->sock,
2810 &reply,
2811 sizeof(struct lttcomm_relayd_generic_reply),
2812 0);
2813 if (send_ret < (ssize_t) sizeof(reply)) {
2814 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
2815 send_ret);
2816 ret = -1;
2817 }
2818end_no_reply:
2819 lttng_trace_chunk_put(chunk);
2820 lttng_trace_chunk_put(published_chunk);
e5add6d0
JG
2821 return ret;
2822}
2823
bbc4768c
JG
2824/*
2825 * relay_close_trace_chunk: close a trace chunk
2826 */
2827static int relay_close_trace_chunk(const struct lttcomm_relayd_hdr *recv_hdr,
2828 struct relay_connection *conn,
2829 const struct lttng_buffer_view *payload)
2830{
9898f786 2831 int ret = 0, buf_ret;
bbc4768c
JG
2832 ssize_t send_ret;
2833 struct relay_session *session = conn->session;
2834 struct lttcomm_relayd_close_trace_chunk *msg;
ecd1a12f 2835 struct lttcomm_relayd_close_trace_chunk_reply reply = {};
bbc4768c
JG
2836 struct lttng_buffer_view header_view;
2837 struct lttng_trace_chunk *chunk = NULL;
2838 enum lttng_error_code reply_code = LTTNG_OK;
2839 enum lttng_trace_chunk_status chunk_status;
2840 uint64_t chunk_id;
c35f9726 2841 LTTNG_OPTIONAL(enum lttng_trace_chunk_command_type) close_command = {};
bbc4768c 2842 time_t close_timestamp;
ecd1a12f
MD
2843 char closed_trace_chunk_path[LTTNG_PATH_MAX];
2844 size_t path_length = 0;
2845 const char *chunk_name = NULL;
2846 struct lttng_dynamic_buffer reply_payload;
a7ceb342 2847 const char *new_path;
ecd1a12f
MD
2848
2849 lttng_dynamic_buffer_init(&reply_payload);
bbc4768c
JG
2850
2851 if (!session || !conn->version_check_done) {
2852 ERR("Trying to close a trace chunk before version check");
2853 ret = -1;
2854 goto end_no_reply;
2855 }
2856
2857 if (session->major == 2 && session->minor < 11) {
2858 ERR("Chunk close command is unsupported before 2.11");
2859 ret = -1;
2860 goto end_no_reply;
2861 }
2862
2863 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
2864 if (!header_view.data) {
2865 ERR("Failed to receive payload of chunk close command");
2866 ret = -1;
2867 goto end_no_reply;
2868 }
2869
2870 /* Convert to host endianness. */
2871 msg = (typeof(msg)) header_view.data;
2872 chunk_id = be64toh(msg->chunk_id);
2873 close_timestamp = (time_t) be64toh(msg->close_timestamp);
2874 close_command = (typeof(close_command)){
2875 .value = be32toh(msg->close_command.value),
2876 .is_set = msg->close_command.is_set,
2877 };
2878
2879 chunk = sessiond_trace_chunk_registry_get_chunk(
2880 sessiond_trace_chunk_registry,
2881 conn->session->sessiond_uuid,
2882 conn->session->id,
2883 chunk_id);
2884 if (!chunk) {
c70636a7 2885 char uuid_str[LTTNG_UUID_STR_LEN];
bbc4768c
JG
2886
2887 lttng_uuid_to_str(conn->session->sessiond_uuid, uuid_str);
2888 ERR("Failed to find chunk to close: sessiond_uuid = %s, session_id = %" PRIu64 ", chunk_id = %" PRIu64,
2889 uuid_str,
2890 conn->session->id,
2891 msg->chunk_id);
2892 ret = -1;
2893 reply_code = LTTNG_ERR_NOMEM;
2894 goto end;
2895 }
2896
62bad3bf 2897 pthread_mutex_lock(&session->lock);
f77a6ec2
MD
2898 if (close_command.is_set &&
2899 close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE) {
2900 /*
2901 * Clear command. It is a protocol error to ask for a
2902 * clear on a relay which does not allow it. Querying
2903 * the configuration allows figuring out whether
2904 * clearing is allowed before doing the clear.
2905 */
2906 if (!opt_allow_clear) {
2907 ret = -1;
2908 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2909 goto end_unlock_session;
2910 }
2911 }
62bad3bf
JG
2912 if (session->pending_closure_trace_chunk &&
2913 session->pending_closure_trace_chunk != chunk) {
2914 ERR("Trace chunk close command for session \"%s\" does not target the trace chunk pending closure",
2915 session->session_name);
2916 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2917 ret = -1;
2918 goto end_unlock_session;
2919 }
2920
a7ceb342
MD
2921 if (session->current_trace_chunk && session->current_trace_chunk != chunk &&
2922 !lttng_trace_chunk_get_name_overridden(session->current_trace_chunk)) {
2923 if (close_command.is_set &&
2924 close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE &&
2925 !session->has_rotated) {
2926 /* New chunk stays in session output directory. */
2927 new_path = "";
2928 } else {
2929 /* Use chunk name for new chunk. */
2930 new_path = NULL;
2931 }
2932 /* Rename new chunk path. */
2933 chunk_status = lttng_trace_chunk_rename_path(session->current_trace_chunk,
2934 new_path);
2935 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2936 ret = -1;
88188199 2937 goto end_unlock_session;
a7ceb342
MD
2938 }
2939 session->ongoing_rotation = false;
2940 }
2941 if ((!close_command.is_set ||
2942 close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION) &&
2943 !lttng_trace_chunk_get_name_overridden(chunk)) {
2944 const char *old_path;
2945
2946 if (!session->has_rotated) {
2947 old_path = "";
2948 } else {
2949 old_path = NULL;
2950 }
2951 /* We need to move back the .tmp_old_chunk to its rightful place. */
2952 chunk_status = lttng_trace_chunk_rename_path(chunk, old_path);
2953 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2954 ret = -1;
88188199 2955 goto end_unlock_session;
a7ceb342
MD
2956 }
2957 }
bbc4768c
JG
2958 chunk_status = lttng_trace_chunk_set_close_timestamp(
2959 chunk, close_timestamp);
2960 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2961 ERR("Failed to set trace chunk close timestamp");
2962 ret = -1;
2963 reply_code = LTTNG_ERR_UNK;
62bad3bf 2964 goto end_unlock_session;
bbc4768c
JG
2965 }
2966
2967 if (close_command.is_set) {
2968 chunk_status = lttng_trace_chunk_set_close_command(
2969 chunk, close_command.value);
2970 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2971 ret = -1;
2972 reply_code = LTTNG_ERR_INVALID;
62bad3bf 2973 goto end_unlock_session;
bbc4768c
JG
2974 }
2975 }
ecd1a12f
MD
2976 chunk_status = lttng_trace_chunk_get_name(chunk, &chunk_name, NULL);
2977 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2978 ERR("Failed to get chunk name");
2979 ret = -1;
2980 reply_code = LTTNG_ERR_UNK;
2981 goto end_unlock_session;
2982 }
2983 if (!session->has_rotated && !session->snapshot) {
2984 ret = lttng_strncpy(closed_trace_chunk_path,
2985 session->output_path,
2986 sizeof(closed_trace_chunk_path));
2987 if (ret) {
2988 ERR("Failed to send trace chunk path: path length of %zu bytes exceeds the maximal allowed length of %zu bytes",
2989 strlen(session->output_path),
2990 sizeof(closed_trace_chunk_path));
2991 reply_code = LTTNG_ERR_NOMEM;
2992 ret = -1;
2993 goto end_unlock_session;
2994 }
2995 } else {
2996 if (session->snapshot) {
2997 ret = snprintf(closed_trace_chunk_path,
2998 sizeof(closed_trace_chunk_path),
2999 "%s/%s", session->output_path,
3000 chunk_name);
3001 } else {
3002 ret = snprintf(closed_trace_chunk_path,
3003 sizeof(closed_trace_chunk_path),
3004 "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY
3005 "/%s",
3006 session->output_path, chunk_name);
3007 }
3008 if (ret < 0 || ret == sizeof(closed_trace_chunk_path)) {
3009 ERR("Failed to format closed trace chunk resulting path");
3010 reply_code = ret < 0 ? LTTNG_ERR_UNK : LTTNG_ERR_NOMEM;
3011 ret = -1;
3012 goto end_unlock_session;
3013 }
3014 }
489ea154
MD
3015 if (close_command.is_set &&
3016 close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED) {
3017 session->has_rotated = true;
3018 }
ecd1a12f
MD
3019 DBG("Reply chunk path on close: %s", closed_trace_chunk_path);
3020 path_length = strlen(closed_trace_chunk_path) + 1;
3021 if (path_length > UINT32_MAX) {
3022 ERR("Closed trace chunk path exceeds the maximal length allowed by the protocol");
3023 ret = -1;
3024 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
3025 goto end_unlock_session;
3026 }
bbc4768c 3027
c35f9726
JG
3028 if (session->current_trace_chunk == chunk) {
3029 /*
3030 * After a trace chunk close command, no new streams
3031 * referencing the chunk may be created. Hence, on the
3032 * event that no new trace chunk have been created for
3033 * the session, the reference to the current trace chunk
3034 * is released in order to allow it to be reclaimed when
3035 * the last stream releases its reference to it.
3036 */
3037 lttng_trace_chunk_put(session->current_trace_chunk);
3038 session->current_trace_chunk = NULL;
3039 }
62bad3bf
JG
3040 lttng_trace_chunk_put(session->pending_closure_trace_chunk);
3041 session->pending_closure_trace_chunk = NULL;
3042end_unlock_session:
c35f9726
JG
3043 pthread_mutex_unlock(&session->lock);
3044
bbc4768c 3045end:
ecd1a12f
MD
3046 reply.generic.ret_code = htobe32((uint32_t) reply_code);
3047 reply.path_length = htobe32((uint32_t) path_length);
9898f786 3048 buf_ret = lttng_dynamic_buffer_append(
ecd1a12f 3049 &reply_payload, &reply, sizeof(reply));
9898f786 3050 if (buf_ret) {
ecd1a12f
MD
3051 ERR("Failed to append \"close trace chunk\" command reply header to payload buffer");
3052 goto end_no_reply;
3053 }
3054
3055 if (reply_code == LTTNG_OK) {
9898f786 3056 buf_ret = lttng_dynamic_buffer_append(&reply_payload,
ecd1a12f 3057 closed_trace_chunk_path, path_length);
9898f786 3058 if (buf_ret) {
ecd1a12f
MD
3059 ERR("Failed to append \"close trace chunk\" command reply path to payload buffer");
3060 goto end_no_reply;
3061 }
3062 }
3063
bbc4768c 3064 send_ret = conn->sock->ops->sendmsg(conn->sock,
ecd1a12f
MD
3065 reply_payload.data,
3066 reply_payload.size,
bbc4768c 3067 0);
ecd1a12f
MD
3068 if (send_ret < reply_payload.size) {
3069 ERR("Failed to send \"close trace chunk\" command reply of %zu bytes (ret = %zd)",
3070 reply_payload.size, send_ret);
bbc4768c 3071 ret = -1;
ecd1a12f 3072 goto end_no_reply;
bbc4768c
JG
3073 }
3074end_no_reply:
3075 lttng_trace_chunk_put(chunk);
ecd1a12f 3076 lttng_dynamic_buffer_reset(&reply_payload);
bbc4768c
JG
3077 return ret;
3078}
3079
c35f9726
JG
3080/*
3081 * relay_trace_chunk_exists: check if a trace chunk exists
3082 */
3083static int relay_trace_chunk_exists(const struct lttcomm_relayd_hdr *recv_hdr,
3084 struct relay_connection *conn,
3085 const struct lttng_buffer_view *payload)
3086{
3087 int ret = 0;
3088 ssize_t send_ret;
3089 struct relay_session *session = conn->session;
3090 struct lttcomm_relayd_trace_chunk_exists *msg;
3091 struct lttcomm_relayd_trace_chunk_exists_reply reply = {};
3092 struct lttng_buffer_view header_view;
c35f9726 3093 uint64_t chunk_id;
6b584c2e 3094 bool chunk_exists;
c35f9726
JG
3095
3096 if (!session || !conn->version_check_done) {
3097 ERR("Trying to close a trace chunk before version check");
3098 ret = -1;
3099 goto end_no_reply;
3100 }
3101
3102 if (session->major == 2 && session->minor < 11) {
3103 ERR("Chunk close command is unsupported before 2.11");
3104 ret = -1;
3105 goto end_no_reply;
3106 }
3107
3108 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
3109 if (!header_view.data) {
3110 ERR("Failed to receive payload of chunk close command");
3111 ret = -1;
3112 goto end_no_reply;
3113 }
3114
3115 /* Convert to host endianness. */
3116 msg = (typeof(msg)) header_view.data;
3117 chunk_id = be64toh(msg->chunk_id);
3118
6b584c2e 3119 ret = sessiond_trace_chunk_registry_chunk_exists(
c35f9726
JG
3120 sessiond_trace_chunk_registry,
3121 conn->session->sessiond_uuid,
3122 conn->session->id,
6b584c2e
JG
3123 chunk_id, &chunk_exists);
3124 /*
3125 * If ret is not 0, send the reply and report the error to the caller.
3126 * It is a protocol (or internal) error and the session/connection
3127 * should be torn down.
3128 */
3129 reply = (typeof(reply)){
3130 .generic.ret_code = htobe32((uint32_t)
3131 (ret == 0 ? LTTNG_OK : LTTNG_ERR_INVALID_PROTOCOL)),
3132 .trace_chunk_exists = ret == 0 ? chunk_exists : 0,
c35f9726 3133 };
6b584c2e
JG
3134 send_ret = conn->sock->ops->sendmsg(
3135 conn->sock, &reply, sizeof(reply), 0);
c35f9726
JG
3136 if (send_ret < (ssize_t) sizeof(reply)) {
3137 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
3138 send_ret);
3139 ret = -1;
3140 }
3141end_no_reply:
c35f9726
JG
3142 return ret;
3143}
3144
8614e600
MD
3145/*
3146 * relay_get_configuration: query whether feature is available
3147 */
3148static int relay_get_configuration(const struct lttcomm_relayd_hdr *recv_hdr,
3149 struct relay_connection *conn,
3150 const struct lttng_buffer_view *payload)
3151{
3152 int ret = 0;
3153 ssize_t send_ret;
3154 struct lttcomm_relayd_get_configuration *msg;
3155 struct lttcomm_relayd_get_configuration_reply reply = {};
3156 struct lttng_buffer_view header_view;
3157 uint64_t query_flags = 0;
3158 uint64_t result_flags = 0;
3159
3160 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
3161 if (!header_view.data) {
3162 ERR("Failed to receive payload of chunk close command");
3163 ret = -1;
3164 goto end_no_reply;
3165 }
3166
3167 /* Convert to host endianness. */
3168 msg = (typeof(msg)) header_view.data;
3169 query_flags = be64toh(msg->query_flags);
3170
3171 if (query_flags) {
3172 ret = LTTNG_ERR_INVALID_PROTOCOL;
3173 goto reply;
3174 }
3175 if (opt_allow_clear) {
3176 result_flags |= LTTCOMM_RELAYD_CONFIGURATION_FLAG_CLEAR_ALLOWED;
3177 }
3178 ret = 0;
3179reply:
3180 reply = (typeof(reply)){
3181 .generic.ret_code = htobe32((uint32_t)
3182 (ret == 0 ? LTTNG_OK : LTTNG_ERR_INVALID_PROTOCOL)),
3183 .relayd_configuration_flags = htobe64(result_flags),
3184 };
3185 send_ret = conn->sock->ops->sendmsg(
3186 conn->sock, &reply, sizeof(reply), 0);
3187 if (send_ret < (ssize_t) sizeof(reply)) {
3188 ERR("Failed to send \"get configuration\" command reply (ret = %zd)",
3189 send_ret);
3190 ret = -1;
3191 }
3192end_no_reply:
3193 return ret;
3194}
3195
5312a3ed
JG
3196#define DBG_CMD(cmd_name, conn) \
3197 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
3198
3199static int relay_process_control_command(struct relay_connection *conn,
3200 const struct lttcomm_relayd_hdr *header,
3201 const struct lttng_buffer_view *payload)
b8aa1682
JD
3202{
3203 int ret = 0;
3204
5312a3ed 3205 switch (header->cmd) {
b8aa1682 3206 case RELAYD_CREATE_SESSION:
5312a3ed
JG
3207 DBG_CMD("RELAYD_CREATE_SESSION", conn);
3208 ret = relay_create_session(header, conn, payload);
b8aa1682 3209 break;
b8aa1682 3210 case RELAYD_ADD_STREAM:
5312a3ed
JG
3211 DBG_CMD("RELAYD_ADD_STREAM", conn);
3212 ret = relay_add_stream(header, conn, payload);
b8aa1682
JD
3213 break;
3214 case RELAYD_START_DATA:
5312a3ed
JG
3215 DBG_CMD("RELAYD_START_DATA", conn);
3216 ret = relay_start(header, conn, payload);
b8aa1682
JD
3217 break;
3218 case RELAYD_SEND_METADATA:
5312a3ed
JG
3219 DBG_CMD("RELAYD_SEND_METADATA", conn);
3220 ret = relay_recv_metadata(header, conn, payload);
b8aa1682
JD
3221 break;
3222 case RELAYD_VERSION:
5312a3ed
JG
3223 DBG_CMD("RELAYD_VERSION", conn);
3224 ret = relay_send_version(header, conn, payload);
b8aa1682 3225 break;
173af62f 3226 case RELAYD_CLOSE_STREAM:
5312a3ed
JG
3227 DBG_CMD("RELAYD_CLOSE_STREAM", conn);
3228 ret = relay_close_stream(header, conn, payload);
173af62f 3229 break;
6d805429 3230 case RELAYD_DATA_PENDING:
5312a3ed
JG
3231 DBG_CMD("RELAYD_DATA_PENDING", conn);
3232 ret = relay_data_pending(header, conn, payload);
c8f59ee5
DG
3233 break;
3234 case RELAYD_QUIESCENT_CONTROL:
5312a3ed
JG
3235 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn);
3236 ret = relay_quiescent_control(header, conn, payload);
c8f59ee5 3237 break;
f7079f67 3238 case RELAYD_BEGIN_DATA_PENDING:
5312a3ed
JG
3239 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn);
3240 ret = relay_begin_data_pending(header, conn, payload);
f7079f67
DG
3241 break;
3242 case RELAYD_END_DATA_PENDING:
5312a3ed
JG
3243 DBG_CMD("RELAYD_END_DATA_PENDING", conn);
3244 ret = relay_end_data_pending(header, conn, payload);
f7079f67 3245 break;
1c20f0e2 3246 case RELAYD_SEND_INDEX:
5312a3ed
JG
3247 DBG_CMD("RELAYD_SEND_INDEX", conn);
3248 ret = relay_recv_index(header, conn, payload);
1c20f0e2 3249 break;
a4baae1b 3250 case RELAYD_STREAMS_SENT:
5312a3ed
JG
3251 DBG_CMD("RELAYD_STREAMS_SENT", conn);
3252 ret = relay_streams_sent(header, conn, payload);
a4baae1b 3253 break;
93ec662e