Fix: lttng: uninitialized pointer free'd when no sessiond is present
[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 3254 case RELAYD_RESET_METADATA:
5312a3ed
JG
3255 DBG_CMD("RELAYD_RESET_METADATA", conn);
3256 ret = relay_reset_metadata(header, conn, payload);
93ec662e 3257 break;
c35f9726
JG
3258 case RELAYD_ROTATE_STREAMS:
3259 DBG_CMD("RELAYD_ROTATE_STREAMS", conn);
3260 ret = relay_rotate_session_streams(header, conn, payload);
d3ecc550 3261 break;
e5add6d0
JG
3262 case RELAYD_CREATE_TRACE_CHUNK:
3263 DBG_CMD("RELAYD_CREATE_TRACE_CHUNK", conn);
3264 ret = relay_create_trace_chunk(header, conn, payload);
3265 break;
bbc4768c
JG
3266 case RELAYD_CLOSE_TRACE_CHUNK:
3267 DBG_CMD("RELAYD_CLOSE_TRACE_CHUNK", conn);
3268 ret = relay_close_trace_chunk(header, conn, payload);
3269 break;
c35f9726
JG
3270 case RELAYD_TRACE_CHUNK_EXISTS:
3271 DBG_CMD("RELAYD_TRACE_CHUNK_EXISTS", conn);
3272 ret = relay_trace_chunk_exists(header, conn, payload);
3273 break;
8614e600
MD
3274 case RELAYD_GET_CONFIGURATION:
3275 DBG_CMD("RELAYD_GET_CONFIGURATION", conn);
3276 ret = relay_get_configuration(header, conn, payload);
3277 break;
b8aa1682
JD
3278 case RELAYD_UPDATE_SYNC_INFO:
3279 default:
5312a3ed 3280 ERR("Received unknown command (%u)", header->cmd);
58eb9381 3281 relay_unknown_command(conn);
b8aa1682
JD
3282 ret = -1;
3283 goto end;
3284 }
3285
3286end:
3287 return ret;
3288}
3289
5569b118
JG
3290static enum relay_connection_status relay_process_control_receive_payload(
3291 struct relay_connection *conn)
5312a3ed
JG
3292{
3293 int ret = 0;
5569b118 3294 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
5312a3ed
JG
3295 struct lttng_dynamic_buffer *reception_buffer =
3296 &conn->protocol.ctrl.reception_buffer;
3297 struct ctrl_connection_state_receive_payload *state =
3298 &conn->protocol.ctrl.state.receive_payload;
3299 struct lttng_buffer_view payload_view;
3300
3301 if (state->left_to_receive == 0) {
3302 /* Short-circuit for payload-less commands. */
3303 goto reception_complete;
3304 }
3305
3306 ret = conn->sock->ops->recvmsg(conn->sock,
3307 reception_buffer->data + state->received,
3308 state->left_to_receive, MSG_DONTWAIT);
3309 if (ret < 0) {
5569b118
JG
3310 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3311 PERROR("Unable to receive command payload on sock %d",
3312 conn->sock->fd);
3313 status = RELAY_CONNECTION_STATUS_ERROR;
3314 }
5312a3ed
JG
3315 goto end;
3316 } else if (ret == 0) {
3317 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
5569b118 3318 status = RELAY_CONNECTION_STATUS_CLOSED;
5312a3ed
JG
3319 goto end;
3320 }
3321
3322 assert(ret > 0);
3323 assert(ret <= state->left_to_receive);
3324
3325 state->left_to_receive -= ret;
3326 state->received += ret;
3327
3328 if (state->left_to_receive > 0) {
3329 /*
3330 * Can't transition to the protocol's next state, wait to
3331 * receive the rest of the header.
3332 */
3333 DBG3("Partial reception of control connection protocol payload (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
3334 state->received, state->left_to_receive,
3335 conn->sock->fd);
5312a3ed
JG
3336 goto end;
3337 }
3338
3339reception_complete:
3340 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64 " bytes",
3341 conn->sock->fd, state->received);
3342 /*
3343 * The payload required to process the command has been received.
3344 * A view to the reception buffer is forwarded to the various
3345 * commands and the state of the control is reset on success.
3346 *
3347 * Commands are responsible for sending their reply to the peer.
3348 */
3349 payload_view = lttng_buffer_view_from_dynamic_buffer(reception_buffer,
3350 0, -1);
3351 ret = relay_process_control_command(conn,
3352 &state->header, &payload_view);
3353 if (ret < 0) {
5569b118 3354 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed
JG
3355 goto end;
3356 }
3357
3358 ret = connection_reset_protocol_state(conn);
5569b118
JG
3359 if (ret) {
3360 status = RELAY_CONNECTION_STATUS_ERROR;
3361 }
5312a3ed 3362end:
5569b118 3363 return status;
5312a3ed
JG
3364}
3365
5569b118
JG
3366static enum relay_connection_status relay_process_control_receive_header(
3367 struct relay_connection *conn)
5312a3ed
JG
3368{
3369 int ret = 0;
5569b118 3370 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
5312a3ed
JG
3371 struct lttcomm_relayd_hdr header;
3372 struct lttng_dynamic_buffer *reception_buffer =
3373 &conn->protocol.ctrl.reception_buffer;
3374 struct ctrl_connection_state_receive_header *state =
3375 &conn->protocol.ctrl.state.receive_header;
3376
3377 assert(state->left_to_receive != 0);
3378
3379 ret = conn->sock->ops->recvmsg(conn->sock,
3380 reception_buffer->data + state->received,
3381 state->left_to_receive, MSG_DONTWAIT);
3382 if (ret < 0) {
5569b118
JG
3383 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3384 PERROR("Unable to receive control command header on sock %d",
3385 conn->sock->fd);
3386 status = RELAY_CONNECTION_STATUS_ERROR;
3387 }
5312a3ed
JG
3388 goto end;
3389 } else if (ret == 0) {
3390 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
5569b118 3391 status = RELAY_CONNECTION_STATUS_CLOSED;
5312a3ed
JG
3392 goto end;
3393 }
3394
3395 assert(ret > 0);
3396 assert(ret <= state->left_to_receive);
3397
3398 state->left_to_receive -= ret;
3399 state->received += ret;
3400
3401 if (state->left_to_receive > 0) {
3402 /*
3403 * Can't transition to the protocol's next state, wait to
3404 * receive the rest of the header.
3405 */
3406 DBG3("Partial reception of control connection protocol header (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
3407 state->received, state->left_to_receive,
3408 conn->sock->fd);
5312a3ed
JG
3409 goto end;
3410 }
3411
3412 /* Transition to next state: receiving the command's payload. */
3413 conn->protocol.ctrl.state_id =
3414 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD;
3415 memcpy(&header, reception_buffer->data, sizeof(header));
3416 header.circuit_id = be64toh(header.circuit_id);
3417 header.data_size = be64toh(header.data_size);
3418 header.cmd = be32toh(header.cmd);
3419 header.cmd_version = be32toh(header.cmd_version);
3420 memcpy(&conn->protocol.ctrl.state.receive_payload.header,
3421 &header, sizeof(header));
3422
3423 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32 ", cmd_version = %" PRIu32 ", payload size = %" PRIu64 " bytes",
3424 conn->sock->fd, header.cmd, header.cmd_version,
3425 header.data_size);
3426
715e6fb1 3427 if (header.data_size > DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE) {
5312a3ed
JG
3428 ERR("Command header indicates a payload (%" PRIu64 " bytes) that exceeds the maximal payload size allowed on a control connection.",
3429 header.data_size);
5569b118 3430 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed
JG
3431 goto end;
3432 }
3433
3434 conn->protocol.ctrl.state.receive_payload.left_to_receive =
3435 header.data_size;
3436 conn->protocol.ctrl.state.receive_payload.received = 0;
3437 ret = lttng_dynamic_buffer_set_size(reception_buffer,
3438 header.data_size);
3439 if (ret) {
5569b118 3440 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed
JG
3441 goto end;
3442 }
3443
3444 if (header.data_size == 0) {
3445 /*
3446 * Manually invoke the next state as the poll loop
3447 * will not wake-up to allow us to proceed further.
3448 */
5569b118 3449 status = relay_process_control_receive_payload(conn);
5312a3ed
JG
3450 }
3451end:
5569b118 3452 return status;
5312a3ed
JG
3453}
3454
3455/*
3456 * Process the commands received on the control socket
3457 */
5569b118
JG
3458static enum relay_connection_status relay_process_control(
3459 struct relay_connection *conn)
5312a3ed 3460{
5569b118 3461 enum relay_connection_status status;
5312a3ed
JG
3462
3463 switch (conn->protocol.ctrl.state_id) {
3464 case CTRL_CONNECTION_STATE_RECEIVE_HEADER:
5569b118 3465 status = relay_process_control_receive_header(conn);
5312a3ed
JG
3466 break;
3467 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD:
5569b118 3468 status = relay_process_control_receive_payload(conn);
5312a3ed
JG
3469 break;
3470 default:
3471 ERR("Unknown control connection protocol state encountered.");
3472 abort();
3473 }
3474
5569b118 3475 return status;
5312a3ed
JG
3476}
3477
5569b118
JG
3478static enum relay_connection_status relay_process_data_receive_header(
3479 struct relay_connection *conn)
b8aa1682 3480{
5312a3ed 3481 int ret;
5569b118 3482 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
5312a3ed
JG
3483 struct data_connection_state_receive_header *state =
3484 &conn->protocol.data.state.receive_header;
3485 struct lttcomm_relayd_data_hdr header;
b8aa1682 3486 struct relay_stream *stream;
5312a3ed
JG
3487
3488 assert(state->left_to_receive != 0);
3489
3490 ret = conn->sock->ops->recvmsg(conn->sock,
3491 state->header_reception_buffer + state->received,
3492 state->left_to_receive, MSG_DONTWAIT);
3493 if (ret < 0) {
5569b118
JG
3494 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3495 PERROR("Unable to receive data header on sock %d", conn->sock->fd);
3496 status = RELAY_CONNECTION_STATUS_ERROR;
3497 }
5312a3ed
JG
3498 goto end;
3499 } else if (ret == 0) {
3500 /* Orderly shutdown. Not necessary to print an error. */
3501 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
5569b118 3502 status = RELAY_CONNECTION_STATUS_CLOSED;
b8aa1682
JD
3503 goto end;
3504 }
3505
5312a3ed
JG
3506 assert(ret > 0);
3507 assert(ret <= state->left_to_receive);
3508
3509 state->left_to_receive -= ret;
3510 state->received += ret;
3511
3512 if (state->left_to_receive > 0) {
3513 /*
3514 * Can't transition to the protocol's next state, wait to
3515 * receive the rest of the header.
3516 */
3517 DBG3("Partial reception of data connection header (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
3518 state->received, state->left_to_receive,
3519 conn->sock->fd);
7591bab1 3520 goto end;
b8aa1682 3521 }
b8aa1682 3522
5312a3ed
JG
3523 /* Transition to next state: receiving the payload. */
3524 conn->protocol.data.state_id = DATA_CONNECTION_STATE_RECEIVE_PAYLOAD;
173af62f 3525
5312a3ed
JG
3526 memcpy(&header, state->header_reception_buffer, sizeof(header));
3527 header.circuit_id = be64toh(header.circuit_id);
3528 header.stream_id = be64toh(header.stream_id);
3529 header.data_size = be32toh(header.data_size);
3530 header.net_seq_num = be64toh(header.net_seq_num);
3531 header.padding_size = be32toh(header.padding_size);
3532 memcpy(&conn->protocol.data.state.receive_payload.header, &header, sizeof(header));
3533
3534 conn->protocol.data.state.receive_payload.left_to_receive =
3535 header.data_size;
3536 conn->protocol.data.state.receive_payload.received = 0;
3537 conn->protocol.data.state.receive_payload.rotate_index = false;
3538
3539 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64 ", stream_id = %" PRIu64 ", data_size = %" PRIu32 ", net_seq_num = %" PRIu64 ", padding_size = %" PRIu32,
3540 conn->sock->fd, header.circuit_id,
3541 header.stream_id, header.data_size,
3542 header.net_seq_num, header.padding_size);
3543
3544 stream = stream_get_by_id(header.stream_id);
3545 if (!stream) {
3546 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64,
3547 header.stream_id);
5569b118
JG
3548 /* Protocol error. */
3549 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed
JG
3550 goto end;
3551 }
b8aa1682 3552
7591bab1 3553 pthread_mutex_lock(&stream->lock);
c35f9726
JG
3554 /* Prepare stream for the reception of a new packet. */
3555 ret = stream_init_packet(stream, header.data_size,
3556 &conn->protocol.data.state.receive_payload.rotate_index);
3557 pthread_mutex_unlock(&stream->lock);
3558 if (ret) {
3559 ERR("Failed to rotate stream output file");
3560 status = RELAY_CONNECTION_STATUS_ERROR;
3561 goto end_stream_unlock;
1c20f0e2
JD
3562 }
3563
5312a3ed 3564end_stream_unlock:
5312a3ed
JG
3565 stream_put(stream);
3566end:
5569b118 3567 return status;
5312a3ed
JG
3568}
3569
5569b118
JG
3570static enum relay_connection_status relay_process_data_receive_payload(
3571 struct relay_connection *conn)
5312a3ed
JG
3572{
3573 int ret;
5569b118 3574 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
5312a3ed
JG
3575 struct relay_stream *stream;
3576 struct data_connection_state_receive_payload *state =
3577 &conn->protocol.data.state.receive_payload;
3578 const size_t chunk_size = RECV_DATA_BUFFER_SIZE;
3579 char data_buffer[chunk_size];
3580 bool partial_recv = false;
3581 bool new_stream = false, close_requested = false, index_flushed = false;
3582 uint64_t left_to_receive = state->left_to_receive;
3583 struct relay_session *session;
3584
fd0f1e3e
JR
3585 DBG3("Receiving data for stream id %" PRIu64 " seqnum %" PRIu64 ", %" PRIu64" bytes received, %" PRIu64 " bytes left to receive",
3586 state->header.stream_id, state->header.net_seq_num,
3587 state->received, left_to_receive);
3588
5312a3ed
JG
3589 stream = stream_get_by_id(state->header.stream_id);
3590 if (!stream) {
5569b118 3591 /* Protocol error. */
fd0f1e3e 3592 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64,
5312a3ed 3593 state->header.stream_id);
5569b118 3594 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed 3595 goto end;
1c20f0e2
JD
3596 }
3597
5312a3ed
JG
3598 pthread_mutex_lock(&stream->lock);
3599 session = stream->trace->session;
fd0f1e3e
JR
3600 if (!conn->session) {
3601 ret = connection_set_session(conn, session);
3602 if (ret) {
3603 status = RELAY_CONNECTION_STATUS_ERROR;
3604 goto end_stream_unlock;
3605 }
3606 }
5312a3ed
JG
3607
3608 /*
3609 * The size of the "chunk" received on any iteration is bounded by:
3610 * - the data left to receive,
3611 * - the data immediately available on the socket,
3612 * - the on-stack data buffer
3613 */
3614 while (left_to_receive > 0 && !partial_recv) {
5312a3ed 3615 size_t recv_size = min(left_to_receive, chunk_size);
c35f9726 3616 struct lttng_buffer_view packet_chunk;
5312a3ed
JG
3617
3618 ret = conn->sock->ops->recvmsg(conn->sock, data_buffer,
3619 recv_size, MSG_DONTWAIT);
3620 if (ret < 0) {
5569b118
JG
3621 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3622 PERROR("Socket %d error", conn->sock->fd);
3623 status = RELAY_CONNECTION_STATUS_ERROR;
3624 }
0848dba7 3625 goto end_stream_unlock;
5312a3ed
JG
3626 } else if (ret == 0) {
3627 /* No more data ready to be consumed on socket. */
3628 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64,
3629 state->header.stream_id);
5569b118 3630 status = RELAY_CONNECTION_STATUS_CLOSED;
5312a3ed
JG
3631 break;
3632 } else if (ret < (int) recv_size) {
3633 /*
3634 * All the data available on the socket has been
3635 * consumed.
3636 */
3637 partial_recv = true;
c35f9726 3638 recv_size = ret;
0848dba7
MD
3639 }
3640
c35f9726
JG
3641 packet_chunk = lttng_buffer_view_init(data_buffer,
3642 0, recv_size);
3643 assert(packet_chunk.data);
5312a3ed 3644
c35f9726
JG
3645 ret = stream_write(stream, &packet_chunk, 0);
3646 if (ret) {
0848dba7 3647 ERR("Relay error writing data to file");
5569b118 3648 status = RELAY_CONNECTION_STATUS_ERROR;
0848dba7
MD
3649 goto end_stream_unlock;
3650 }
3651
5312a3ed
JG
3652 left_to_receive -= recv_size;
3653 state->received += recv_size;
3654 state->left_to_receive = left_to_receive;
5312a3ed
JG
3655 }
3656
3657 if (state->left_to_receive > 0) {
3658 /*
3659 * Did not receive all the data expected, wait for more data to
3660 * become available on the socket.
3661 */
3662 DBG3("Partial receive on data connection of stream id %" PRIu64 ", %" PRIu64 " bytes received, %" PRIu64 " bytes left to receive",
3663 state->header.stream_id, state->received,
3664 state->left_to_receive);
5312a3ed 3665 goto end_stream_unlock;
0848dba7 3666 }
5ab7344e 3667
c35f9726
JG
3668 ret = stream_write(stream, NULL, state->header.padding_size);
3669 if (ret) {
5569b118 3670 status = RELAY_CONNECTION_STATUS_ERROR;
7591bab1 3671 goto end_stream_unlock;
1d4dfdef 3672 }
5312a3ed 3673
298a25ca 3674 if (session_streams_have_index(session)) {
c35f9726
JG
3675 ret = stream_update_index(stream, state->header.net_seq_num,
3676 state->rotate_index, &index_flushed,
3677 state->header.data_size + state->header.padding_size);
5312a3ed 3678 if (ret < 0) {
c35f9726 3679 ERR("Failed to update index: stream %" PRIu64 " net_seq_num %" PRIu64 " ret %d",
5312a3ed
JG
3680 stream->stream_handle,
3681 state->header.net_seq_num, ret);
5569b118 3682 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed
JG
3683 goto end_stream_unlock;
3684 }
3685 }
3686
a8f9f353 3687 if (stream->prev_data_seq == -1ULL) {
c0bae11d
MD
3688 new_stream = true;
3689 }
3690
c35f9726
JG
3691 ret = stream_complete_packet(stream, state->header.data_size +
3692 state->header.padding_size, state->header.net_seq_num,
3693 index_flushed);
3694 if (ret) {
3695 status = RELAY_CONNECTION_STATUS_ERROR;
3696 goto end_stream_unlock;
3697 }
5312a3ed
JG
3698
3699 /*
3700 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3701 * contents of *state which are aliased (union) to the same location as
3702 * the new state. Don't use it beyond this point.
3703 */
3704 connection_reset_protocol_state(conn);
3705 state = NULL;
173af62f 3706
7591bab1 3707end_stream_unlock:
bda7c7b9 3708 close_requested = stream->close_requested;
7591bab1 3709 pthread_mutex_unlock(&stream->lock);
5312a3ed 3710 if (close_requested && left_to_receive == 0) {
bda7c7b9
JG
3711 try_stream_close(stream);
3712 }
3713
c0bae11d
MD
3714 if (new_stream) {
3715 pthread_mutex_lock(&session->lock);
3716 uatomic_set(&session->new_streams, 1);
3717 pthread_mutex_unlock(&session->lock);
3718 }
5312a3ed 3719
7591bab1 3720 stream_put(stream);
b8aa1682 3721end:
5569b118 3722 return status;
b8aa1682
JD
3723}
3724
5312a3ed
JG
3725/*
3726 * relay_process_data: Process the data received on the data socket
3727 */
5569b118
JG
3728static enum relay_connection_status relay_process_data(
3729 struct relay_connection *conn)
5312a3ed 3730{
5569b118 3731 enum relay_connection_status status;
5312a3ed
JG
3732
3733 switch (conn->protocol.data.state_id) {
3734 case DATA_CONNECTION_STATE_RECEIVE_HEADER:
5569b118 3735 status = relay_process_data_receive_header(conn);
5312a3ed
JG
3736 break;
3737 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD:
5569b118 3738 status = relay_process_data_receive_payload(conn);
5312a3ed
JG
3739 break;
3740 default:
3741 ERR("Unexpected data connection communication state.");
3742 abort();
3743 }
3744
5569b118 3745 return status;
5312a3ed
JG
3746}
3747
7591bab1 3748static void cleanup_connection_pollfd(struct lttng_poll_event *events, int pollfd)
b8aa1682
JD
3749{
3750 int ret;
3751
58eb9381 3752 (void) lttng_poll_del(events, pollfd);
b8aa1682 3753
f355467e
JG
3754 ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker, &pollfd, 1,
3755 fd_tracker_util_close_fd, NULL);
b8aa1682
JD
3756 if (ret < 0) {
3757 ERR("Closing pollfd %d", pollfd);
3758 }
3759}
3760
7591bab1
MD
3761static void relay_thread_close_connection(struct lttng_poll_event *events,
3762 int pollfd, struct relay_connection *conn)
9d1bbf21 3763{
7591bab1 3764 const char *type_str;
2a174661 3765
7591bab1
MD
3766 switch (conn->type) {
3767 case RELAY_DATA:
3768 type_str = "Data";
3769 break;
3770 case RELAY_CONTROL:
3771 type_str = "Control";
3772 break;
3773 case RELAY_VIEWER_COMMAND:
3774 type_str = "Viewer Command";
3775 break;
3776 case RELAY_VIEWER_NOTIFICATION:
3777 type_str = "Viewer Notification";
3778 break;
3779 default:
3780 type_str = "Unknown";
9d1bbf21 3781 }
7591bab1
MD
3782 cleanup_connection_pollfd(events, pollfd);
3783 connection_put(conn);
3784 DBG("%s connection closed with %d", type_str, pollfd);
b8aa1682
JD
3785}
3786
3787/*
3788 * This thread does the actual work
3789 */
7591bab1 3790static void *relay_thread_worker(void *data)
b8aa1682 3791{
beaad64c
DG
3792 int ret, err = -1, last_seen_data_fd = -1;
3793 uint32_t nb_fd;
b8aa1682
JD
3794 struct lttng_poll_event events;
3795 struct lttng_ht *relay_connections_ht;
b8aa1682 3796 struct lttng_ht_iter iter;
90e7d72f 3797 struct relay_connection *destroy_conn = NULL;
b8aa1682
JD
3798
3799 DBG("[thread] Relay worker started");
3800
9d1bbf21
MD
3801 rcu_register_thread();
3802
55706a7d
MD
3803 health_register(health_relayd, HEALTH_RELAYD_TYPE_WORKER);
3804
9b5e0863
MD
3805 if (testpoint(relayd_thread_worker)) {
3806 goto error_testpoint;
3807 }
3808
f385ae0a
MD
3809 health_code_update();
3810
b8aa1682
JD
3811 /* table of connections indexed on socket */
3812 relay_connections_ht = lttng_ht_new(0, LTTNG_HT_TYPE_ULONG);
095a4ae5
MD
3813 if (!relay_connections_ht) {
3814 goto relay_connections_ht_error;
3815 }
b8aa1682 3816
e32a0864 3817 ret = create_named_thread_poll_set(&events, 2, "Worker thread epoll");
b8aa1682
JD
3818 if (ret < 0) {
3819 goto error_poll_create;
3820 }
3821
58eb9381 3822 ret = lttng_poll_add(&events, relay_conn_pipe[0], LPOLLIN | LPOLLRDHUP);
b8aa1682
JD
3823 if (ret < 0) {
3824 goto error;
3825 }
3826
beaad64c 3827restart:
b8aa1682 3828 while (1) {
beaad64c
DG
3829 int idx = -1, i, seen_control = 0, last_notdel_data_fd = -1;
3830
f385ae0a
MD
3831 health_code_update();
3832
b8aa1682 3833 /* Infinite blocking call, waiting for transmission */
87c1611d 3834 DBG3("Relayd worker thread polling...");
f385ae0a 3835 health_poll_entry();
b8aa1682 3836 ret = lttng_poll_wait(&events, -1);
f385ae0a 3837 health_poll_exit();
b8aa1682
JD
3838 if (ret < 0) {
3839 /*
3840 * Restart interrupted system call.
3841 */
3842 if (errno == EINTR) {
3843 goto restart;
3844 }
3845 goto error;
3846 }
3847
0d9c5d77
DG
3848 nb_fd = ret;
3849
beaad64c 3850 /*
7591bab1
MD
3851 * Process control. The control connection is
3852 * prioritized so we don't starve it with high
3853 * throughput tracing data on the data connection.
beaad64c 3854 */
b8aa1682
JD
3855 for (i = 0; i < nb_fd; i++) {
3856 /* Fetch once the poll data */
beaad64c
DG
3857 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
3858 int pollfd = LTTNG_POLL_GETFD(&events, i);
b8aa1682 3859
f385ae0a
MD
3860 health_code_update();
3861
b8aa1682
JD
3862 /* Thread quit pipe has been closed. Killing thread. */
3863 ret = check_thread_quit_pipe(pollfd, revents);
3864 if (ret) {
095a4ae5
MD
3865 err = 0;
3866 goto exit;
b8aa1682
JD
3867 }
3868
58eb9381
DG
3869 /* Inspect the relay conn pipe for new connection */
3870 if (pollfd == relay_conn_pipe[0]) {
03e43155 3871 if (revents & LPOLLIN) {
90e7d72f
JG
3872 struct relay_connection *conn;
3873
58eb9381 3874 ret = lttng_read(relay_conn_pipe[0], &conn, sizeof(conn));
b8aa1682
JD
3875 if (ret < 0) {
3876 goto error;
3877 }
73039936
FD
3878 ret = lttng_poll_add(&events,
3879 conn->sock->fd,
58eb9381 3880 LPOLLIN | LPOLLRDHUP);
73039936
FD
3881 if (ret) {
3882 ERR("Failed to add new connection file descriptor to poll set");
3883 goto error;
3884 }
7591bab1 3885 connection_ht_add(relay_connections_ht, conn);
58eb9381 3886 DBG("Connection socket %d added", conn->sock->fd);
03e43155
MD
3887 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
3888 ERR("Relay connection pipe error");
3889 goto error;
3890 } else {
3891 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
3892 goto error;
b8aa1682 3893 }
58eb9381 3894 } else {
90e7d72f
JG
3895 struct relay_connection *ctrl_conn;
3896
7591bab1 3897 ctrl_conn = connection_get_by_sock(relay_connections_ht, pollfd);
58eb9381 3898 /* If not found, there is a synchronization issue. */
90e7d72f 3899 assert(ctrl_conn);
58eb9381 3900
03e43155
MD
3901 if (ctrl_conn->type == RELAY_DATA) {
3902 if (revents & LPOLLIN) {
beaad64c
DG
3903 /*
3904 * Flag the last seen data fd not deleted. It will be
3905 * used as the last seen fd if any fd gets deleted in
3906 * this first loop.
3907 */
3908 last_notdel_data_fd = pollfd;
3909 }
03e43155
MD
3910 goto put_ctrl_connection;
3911 }
3912 assert(ctrl_conn->type == RELAY_CONTROL);
3913
3914 if (revents & LPOLLIN) {
5569b118
JG
3915 enum relay_connection_status status;
3916
3917 status = relay_process_control(ctrl_conn);
3918 if (status != RELAY_CONNECTION_STATUS_OK) {
fd0f1e3e
JR
3919 /*
3920 * On socket error flag the session as aborted to force
3921 * the cleanup of its stream otherwise it can leak
3922 * during the lifetime of the relayd.
3923 *
3924 * This prevents situations in which streams can be
3925 * left opened because an index was received, the
3926 * control connection is closed, and the data
3927 * connection is closed (uncleanly) before the packet's
3928 * data provided.
3929 *
3930 * Since the control connection encountered an error,
3931 * it is okay to be conservative and close the
3932 * session right now as we can't rely on the protocol
3933 * being respected anymore.
3934 */
3935 if (status == RELAY_CONNECTION_STATUS_ERROR) {
3936 session_abort(ctrl_conn->session);
3937 }
3938
5569b118 3939 /* Clear the connection on error or close. */
5312a3ed
JG
3940 relay_thread_close_connection(&events,
3941 pollfd,
03e43155 3942 ctrl_conn);
03e43155 3943 }
5312a3ed 3944 seen_control = 1;
03e43155
MD
3945 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
3946 relay_thread_close_connection(&events,
3947 pollfd, ctrl_conn);
3948 if (last_seen_data_fd == pollfd) {
3949 last_seen_data_fd = last_notdel_data_fd;
3950 }
58eb9381 3951 } else {
03e43155
MD
3952 ERR("Unexpected poll events %u for control sock %d",
3953 revents, pollfd);
3954 connection_put(ctrl_conn);
3955 goto error;
beaad64c 3956 }
03e43155 3957 put_ctrl_connection:
7591bab1 3958 connection_put(ctrl_conn);
beaad64c
DG
3959 }
3960 }
3961
3962 /*
3963 * The last loop handled a control request, go back to poll to make
3964 * sure we prioritise the control socket.
3965 */
3966 if (seen_control) {
3967 continue;
3968 }
3969
3970 if (last_seen_data_fd >= 0) {
3971 for (i = 0; i < nb_fd; i++) {
3972 int pollfd = LTTNG_POLL_GETFD(&events, i);
f385ae0a
MD
3973
3974 health_code_update();
3975
beaad64c
DG
3976 if (last_seen_data_fd == pollfd) {
3977 idx = i;
3978 break;
3979 }
3980 }
3981 }
3982
3983 /* Process data connection. */
3984 for (i = idx + 1; i < nb_fd; i++) {
3985 /* Fetch the poll data. */
3986 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
3987 int pollfd = LTTNG_POLL_GETFD(&events, i);
90e7d72f 3988 struct relay_connection *data_conn;
beaad64c 3989
f385ae0a
MD
3990 health_code_update();
3991
fd20dac9
MD
3992 if (!revents) {
3993 /* No activity for this FD (poll implementation). */
3994 continue;
3995 }
3996
beaad64c 3997 /* Skip the command pipe. It's handled in the first loop. */
58eb9381 3998 if (pollfd == relay_conn_pipe[0]) {
beaad64c
DG
3999 continue;
4000 }
4001
7591bab1 4002 data_conn = connection_get_by_sock(relay_connections_ht, pollfd);
90e7d72f 4003 if (!data_conn) {
fd20dac9 4004 /* Skip it. Might be removed before. */
fd20dac9
MD
4005 continue;
4006 }
03e43155
MD
4007 if (data_conn->type == RELAY_CONTROL) {
4008 goto put_data_connection;
4009 }
4010 assert(data_conn->type == RELAY_DATA);
fd20dac9
MD
4011
4012 if (revents & LPOLLIN) {
5569b118
JG
4013 enum relay_connection_status status;
4014
4015 status = relay_process_data(data_conn);
4016 /* Connection closed or error. */
4017 if (status != RELAY_CONNECTION_STATUS_OK) {
fd0f1e3e
JR
4018 /*
4019 * On socket error flag the session as aborted to force
4020 * the cleanup of its stream otherwise it can leak
4021 * during the lifetime of the relayd.
4022 *
4023 * This prevents situations in which streams can be
4024 * left opened because an index was received, the
4025 * control connection is closed, and the data
4026 * connection is closed (uncleanly) before the packet's
4027 * data provided.
4028 *
4029 * Since the data connection encountered an error,
4030 * it is okay to be conservative and close the
4031 * session right now as we can't rely on the protocol
4032 * being respected anymore.
4033 */
4034 if (status == RELAY_CONNECTION_STATUS_ERROR) {
4035 session_abort(data_conn->session);
4036 }
7591bab1 4037 relay_thread_close_connection(&events, pollfd,
03e43155 4038 data_conn);
fd20dac9
MD
4039 /*
4040 * Every goto restart call sets the last seen fd where
4041 * here we don't really care since we gracefully
4042 * continue the loop after the connection is deleted.
4043 */
4044 } else {
4045 /* Keep last seen port. */
4046 last_seen_data_fd = pollfd;
7591bab1 4047 connection_put(data_conn);
fd20dac9 4048 goto restart;
b8aa1682 4049 }
03e43155
MD
4050 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
4051 relay_thread_close_connection(&events, pollfd,
4052 data_conn);
4053 } else {
4054 ERR("Unknown poll events %u for data sock %d",
4055 revents, pollfd);
b8aa1682 4056 }
03e43155 4057 put_data_connection:
7591bab1 4058 connection_put(data_conn);
b8aa1682 4059 }
beaad64c 4060 last_seen_data_fd = -1;
b8aa1682
JD
4061 }
4062
f385ae0a
MD
4063 /* Normal exit, no error */
4064 ret = 0;
4065
095a4ae5 4066exit:
b8aa1682 4067error:
71efa8ef 4068 /* Cleanup remaining connection object. */
9d1bbf21 4069 rcu_read_lock();
90e7d72f
JG
4070 cds_lfht_for_each_entry(relay_connections_ht->ht, &iter.iter,
4071 destroy_conn,
58eb9381 4072 sock_n.node) {
f385ae0a 4073 health_code_update();
98ba050e 4074
fd0f1e3e 4075 session_abort(destroy_conn->session);
98ba050e 4076
7591bab1
MD
4077 /*
4078 * No need to grab another ref, because we own
4079 * destroy_conn.
4080 */
4081 relay_thread_close_connection(&events, destroy_conn->sock->fd,
4082 destroy_conn);
b8aa1682 4083 }
94d49140 4084 rcu_read_unlock();
7591bab1 4085
e32a0864 4086 (void) fd_tracker_util_poll_clean(the_fd_tracker, &events);
7d2f7452 4087error_poll_create:
b8aa1682 4088 lttng_ht_destroy(relay_connections_ht);
095a4ae5 4089relay_connections_ht_error:
58eb9381 4090 /* Close relay conn pipes */
726b2396
JG
4091 (void) fd_tracker_util_pipe_close(the_fd_tracker,
4092 relay_conn_pipe);
095a4ae5
MD
4093 if (err) {
4094 DBG("Thread exited with error");
4095 }
b8aa1682 4096 DBG("Worker thread cleanup complete");
9b5e0863 4097error_testpoint:
f385ae0a
MD
4098 if (err) {
4099 health_error();
4100 ERR("Health error occurred in %s", __func__);
4101 }
4102 health_unregister(health_relayd);
9d1bbf21 4103 rcu_unregister_thread();
b4aacfdc 4104 lttng_relay_stop_threads();
b8aa1682
JD
4105 return NULL;
4106}
4107
4108/*
4109 * Create the relay command pipe to wake thread_manage_apps.
4110 * Closed in cleanup().
4111 */
58eb9381 4112static int create_relay_conn_pipe(void)
b8aa1682 4113{
726b2396
JG
4114 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker,
4115 "Relayd connection pipe", relay_conn_pipe);
b8aa1682
JD
4116}
4117
9c256b01
JG
4118static int stdio_open(void *data, int *fds)
4119{
4120 fds[0] = fileno(stdout);
4121 fds[1] = fileno(stderr);
4122 return 0;
4123}
4124
9c256b01
JG
4125static int track_stdio(void)
4126{
4127 int fds[2];
4128 const char *names[] = { "stdout", "stderr" };
4129
4130 return fd_tracker_open_unsuspendable_fd(the_fd_tracker, fds,
4131 names, 2, stdio_open, NULL);
4132}
4133
b8aa1682
JD
4134/*
4135 * main
4136 */
4137int main(int argc, char **argv)
4138{
00e3b7f1 4139 bool thread_is_rcu_registered = false;
178a0557 4140 int ret = 0, retval = 0;
b8aa1682 4141 void *status;
f7c3ffd7 4142 char *unlinked_file_directory_path = NULL, *output_path = NULL;
b8aa1682 4143
2a10de3b
JR
4144 /* Parse environment variables */
4145 ret = parse_env_options();
4146 if (ret) {
4147 retval = -1;
4148 goto exit_options;
4149 }
4150
4151 /*
4152 * Parse arguments.
4153 * Command line arguments overwrite environment.
4154 */
b8aa1682 4155 progname = argv[0];
178a0557
MD
4156 if (set_options(argc, argv)) {
4157 retval = -1;
4158 goto exit_options;
b8aa1682
JD
4159 }
4160
178a0557
MD
4161 if (set_signal_handler()) {
4162 retval = -1;
4163 goto exit_options;
b8aa1682
JD
4164 }
4165
a3bc3918
JR
4166 relayd_config_log();
4167
4168 if (opt_print_version) {
4169 print_version();
4170 retval = 0;
4171 goto exit_options;
4172 }
4173
c0407718
JG
4174 ret = fclose(stdin);
4175 if (ret) {
4176 PERROR("Failed to close stdin");
4177 goto exit_options;
4178 }
4179
35ab25e5
MD
4180 DBG("Clear command %s", opt_allow_clear ? "allowed" : "disallowed");
4181
4d513a50
DG
4182 /* Try to create directory if -o, --output is specified. */
4183 if (opt_output_path) {
994fa64f
DG
4184 if (*opt_output_path != '/') {
4185 ERR("Please specify an absolute path for -o, --output PATH");
178a0557
MD
4186 retval = -1;
4187 goto exit_options;
994fa64f
DG
4188 }
4189
d77dded2
JG
4190 ret = utils_mkdir_recursive(opt_output_path, S_IRWXU | S_IRWXG,
4191 -1, -1);
4d513a50
DG
4192 if (ret < 0) {
4193 ERR("Unable to create %s", opt_output_path);
178a0557
MD
4194 retval = -1;
4195 goto exit_options;
4d513a50
DG
4196 }
4197 }
4198
b8aa1682 4199 /* Daemonize */
b5218ffb 4200 if (opt_daemon || opt_background) {
3fd27398
MD
4201 ret = lttng_daemonize(&child_ppid, &recv_child_signal,
4202 !opt_background);
b8aa1682 4203 if (ret < 0) {
178a0557
MD
4204 retval = -1;
4205 goto exit_options;
b8aa1682 4206 }
3fd27398
MD
4207 }
4208
ce9ee1fb
JR
4209 if (opt_working_directory) {
4210 ret = utils_change_working_directory(opt_working_directory);
4211 if (ret) {
4212 /* All errors are already logged. */
4213 goto exit_options;
4214 }
4215 }
4216
23c8ff50
JG
4217 sessiond_trace_chunk_registry = sessiond_trace_chunk_registry_create();
4218 if (!sessiond_trace_chunk_registry) {
4219 ERR("Failed to initialize session daemon trace chunk registry");
4220 retval = -1;
794e2e5f 4221 goto exit_options;
23c8ff50
JG
4222 }
4223
00e3b7f1
JG
4224 /*
4225 * The RCU thread registration (and use, through the fd-tracker's
4226 * creation) is done after the daemonization to allow us to not
4227 * deal with liburcu's fork() management as the call RCU needs to
4228 * be restored.
4229 */
4230 rcu_register_thread();
4231 thread_is_rcu_registered = true;
4232
f7c3ffd7
JG
4233 output_path = create_output_path("");
4234 if (!output_path) {
4235 ERR("Failed to get output path");
4236 retval = -1;
4237 goto exit_options;
4238 }
4239 ret = asprintf(&unlinked_file_directory_path, "%s/%s", output_path,
4240 DEFAULT_UNLINKED_FILES_DIRECTORY);
4241 free(output_path);
4242 if (ret < 0) {
4243 ERR("Failed to format unlinked file directory path");
4244 retval = -1;
4245 goto exit_options;
4246 }
4247 the_fd_tracker = fd_tracker_create(
4248 unlinked_file_directory_path, lttng_opt_fd_pool_size);
4249 free(unlinked_file_directory_path);
00e3b7f1
JG
4250 if (!the_fd_tracker) {
4251 retval = -1;
4252 goto exit_options;
4253 }
4254
9c256b01
JG
4255 ret = track_stdio();
4256 if (ret) {
4257 retval = -1;
4258 goto exit_options;
4259 }
4260
178a0557
MD
4261 /* Initialize thread health monitoring */
4262 health_relayd = health_app_create(NR_HEALTH_RELAYD_TYPES);
4263 if (!health_relayd) {
4264 PERROR("health_app_create error");
4265 retval = -1;
794e2e5f 4266 goto exit_options;
178a0557
MD
4267 }
4268
3fd27398 4269 /* Create thread quit pipe */
178a0557
MD
4270 if (init_thread_quit_pipe()) {
4271 retval = -1;
794e2e5f 4272 goto exit_options;
b8aa1682
JD
4273 }
4274
b8aa1682 4275 /* Setup the thread apps communication pipe. */
178a0557
MD
4276 if (create_relay_conn_pipe()) {
4277 retval = -1;
794e2e5f 4278 goto exit_options;
b8aa1682
JD
4279 }
4280
4281 /* Init relay command queue. */
8bdee6e2 4282 cds_wfcq_init(&relay_conn_queue.head, &relay_conn_queue.tail);
b8aa1682 4283
554831e7
MD
4284 /* Initialize communication library */
4285 lttcomm_init();
87e45c13 4286 lttcomm_inet_init();
554831e7 4287
d3e2ba59 4288 /* tables of sessions indexed by session ID */
7591bab1
MD
4289 sessions_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
4290 if (!sessions_ht) {
178a0557 4291 retval = -1;
794e2e5f 4292 goto exit_options;
d3e2ba59
JD
4293 }
4294
4295 /* tables of streams indexed by stream ID */
2a174661 4296 relay_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
d3e2ba59 4297 if (!relay_streams_ht) {
178a0557 4298 retval = -1;
794e2e5f 4299 goto exit_options;
d3e2ba59
JD
4300 }
4301
4302 /* tables of streams indexed by stream ID */
92c6ca54
DG
4303 viewer_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
4304 if (!viewer_streams_ht) {
178a0557 4305 retval = -1;
794e2e5f 4306 goto exit_options;
55706a7d
MD
4307 }
4308
bcee2b96 4309 ret = init_health_quit_pipe();
178a0557
MD
4310 if (ret) {
4311 retval = -1;
794e2e5f 4312 goto exit_options;
65931c8b
MD
4313 }
4314
4315 /* Create thread to manage the client socket */
1a1a34b4 4316 ret = pthread_create(&health_thread, default_pthread_attr(),
65931c8b 4317 thread_manage_health, (void *) NULL);
178a0557
MD
4318 if (ret) {
4319 errno = ret;
65931c8b 4320 PERROR("pthread_create health");
178a0557 4321 retval = -1;
794e2e5f 4322 goto exit_options;
65931c8b
MD
4323 }
4324
b8aa1682 4325 /* Setup the dispatcher thread */
1a1a34b4 4326 ret = pthread_create(&dispatcher_thread, default_pthread_attr(),
b8aa1682 4327 relay_thread_dispatcher, (void *) NULL);
178a0557
MD
4328 if (ret) {
4329 errno = ret;
b8aa1682 4330 PERROR("pthread_create dispatcher");
178a0557
MD
4331 retval = -1;
4332 goto exit_dispatcher_thread;
b8aa1682
JD
4333 }
4334
4335 /* Setup the worker thread */
1a1a34b4 4336 ret = pthread_create(&worker_thread, default_pthread_attr(),
7591bab1 4337 relay_thread_worker, NULL);
178a0557
MD
4338 if (ret) {
4339 errno = ret;
b8aa1682 4340 PERROR("pthread_create worker");
178a0557
MD
4341 retval = -1;
4342 goto exit_worker_thread;
b8aa1682
JD
4343 }
4344
4345 /* Setup the listener thread */
1a1a34b4 4346 ret = pthread_create(&listener_thread, default_pthread_attr(),
b8aa1682 4347 relay_thread_listener, (void *) NULL);
178a0557
MD
4348 if (ret) {
4349 errno = ret;
b8aa1682 4350 PERROR("pthread_create listener");
178a0557
MD
4351 retval = -1;
4352 goto exit_listener_thread;
b8aa1682
JD
4353 }
4354
7591bab1 4355 ret = relayd_live_create(live_uri);
178a0557 4356 if (ret) {
d3e2ba59 4357 ERR("Starting live viewer threads");
178a0557 4358 retval = -1;
50138f51 4359 goto exit_live;
d3e2ba59
JD
4360 }
4361
178a0557
MD
4362 /*
4363 * This is where we start awaiting program completion (e.g. through
4364 * signal that asks threads to teardown).
4365 */
4366
4367 ret = relayd_live_join();
4368 if (ret) {
4369 retval = -1;
4370 }
50138f51 4371exit_live:
178a0557 4372
b8aa1682 4373 ret = pthread_join(listener_thread, &status);
178a0557
MD
4374 if (ret) {
4375 errno = ret;
4376 PERROR("pthread_join listener_thread");
4377 retval = -1;
b8aa1682
JD
4378 }
4379
178a0557 4380exit_listener_thread:
b8aa1682 4381 ret = pthread_join(worker_thread, &status);
178a0557
MD
4382 if (ret) {
4383 errno = ret;
4384 PERROR("pthread_join worker_thread");
4385 retval = -1;
b8aa1682
JD
4386 }
4387
178a0557 4388exit_worker_thread:
b8aa1682 4389 ret = pthread_join(dispatcher_thread, &status);
178a0557
MD
4390 if (ret) {
4391 errno = ret;
4392 PERROR("pthread_join dispatcher_thread");
4393 retval = -1;
b8aa1682 4394 }
178a0557 4395exit_dispatcher_thread:
42415026 4396
65931c8b 4397 ret = pthread_join(health_thread, &status);
178a0557
MD
4398 if (ret) {
4399 errno = ret;
4400 PERROR("pthread_join health_thread");
4401 retval = -1;
65931c8b 4402 }
178a0557 4403exit_options:
4d62fbf8
MD
4404 /*
4405 * Wait for all pending call_rcu work to complete before tearing
4406 * down data structures. call_rcu worker may be trying to
4407 * perform lookups in those structures.
4408 */
4409 rcu_barrier();
7591bab1
MD
4410 relayd_cleanup();
4411
4412 /* Ensure all prior call_rcu are done. */
4413 rcu_barrier();
d3e2ba59 4414
00e3b7f1
JG
4415 if (thread_is_rcu_registered) {
4416 rcu_unregister_thread();
4417 }
4418
178a0557 4419 if (!retval) {
b8aa1682 4420 exit(EXIT_SUCCESS);
178a0557
MD
4421 } else {
4422 exit(EXIT_FAILURE);
b8aa1682 4423 }
b8aa1682 4424}
This page took 0.31582 seconds and 4 git commands to generate.