configure: add --enable-Werror
[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);
64e2c0ed
JG
921 if (ret) {
922 PERROR("Failed to create \"%s\" poll file descriptor", name);
923 goto error;
924 }
b8aa1682
JD
925
926 /* Add quit pipe */
c7759e6a 927 ret = lttng_poll_add(events, thread_quit_pipe[0], LPOLLIN | LPOLLERR);
b8aa1682
JD
928 if (ret < 0) {
929 goto error;
930 }
931
932 return 0;
933
934error:
935 return ret;
936}
937
938/*
939 * Check if the thread quit pipe was triggered.
940 *
941 * Return 1 if it was triggered else 0;
942 */
7591bab1 943static int check_thread_quit_pipe(int fd, uint32_t events)
b8aa1682
JD
944{
945 if (fd == thread_quit_pipe[0] && (events & LPOLLIN)) {
946 return 1;
947 }
948
949 return 0;
950}
951
40212d87
JG
952static int create_sock(void *data, int *out_fd)
953{
954 int ret;
955 struct lttcomm_sock *sock = data;
956
957 ret = lttcomm_create_sock(sock);
958 if (ret < 0) {
959 goto end;
960 }
961
962 *out_fd = sock->fd;
963end:
964 return ret;
965}
966
967static int close_sock(void *data, int *in_fd)
968{
969 struct lttcomm_sock *sock = data;
970
971 return sock->ops->close(sock);
972}
973
f355467e
JG
974static int accept_sock(void *data, int *out_fd)
975{
976 int ret = 0;
977 /* Socks is an array of in_sock, out_sock. */
978 struct lttcomm_sock **socks = data;
979 struct lttcomm_sock *in_sock = socks[0];
980
981 socks[1] = in_sock->ops->accept(in_sock);
982 if (!socks[1]) {
983 ret = -1;
984 goto end;
985 }
986 *out_fd = socks[1]->fd;
987end:
988 return ret;
989}
990
b8aa1682
JD
991/*
992 * Create and init socket from uri.
993 */
40212d87
JG
994static struct lttcomm_sock *relay_socket_create(struct lttng_uri *uri,
995 const char *name)
b8aa1682 996{
40212d87 997 int ret, sock_fd;
b8aa1682 998 struct lttcomm_sock *sock = NULL;
40212d87
JG
999 char uri_str[PATH_MAX];
1000 char *formated_name = NULL;
b8aa1682
JD
1001
1002 sock = lttcomm_alloc_sock_from_uri(uri);
1003 if (sock == NULL) {
1004 ERR("Allocating socket");
1005 goto error;
1006 }
1007
40212d87
JG
1008 /*
1009 * Don't fail to create the socket if the name can't be built as it is
1010 * only used for debugging purposes.
1011 */
1012 ret = uri_to_str_url(uri, uri_str, sizeof(uri_str));
1013 uri_str[sizeof(uri_str) - 1] = '\0';
1014 if (ret >= 0) {
1015 ret = asprintf(&formated_name, "%s socket @ %s", name,
1016 uri_str);
1017 if (ret < 0) {
1018 formated_name = NULL;
1019 }
b8aa1682 1020 }
40212d87
JG
1021
1022 ret = fd_tracker_open_unsuspendable_fd(the_fd_tracker, &sock_fd,
1023 (const char **) (formated_name ? &formated_name : NULL),
1024 1, create_sock, sock);
1025 free(formated_name);
1026 DBG("Listening on %s socket %d", name, sock->fd);
b8aa1682
JD
1027
1028 ret = sock->ops->bind(sock);
1029 if (ret < 0) {
2288467f 1030 PERROR("Failed to bind socket");
b8aa1682
JD
1031 goto error;
1032 }
1033
1034 ret = sock->ops->listen(sock, -1);
1035 if (ret < 0) {
1036 goto error;
1037
1038 }
1039
1040 return sock;
1041
1042error:
1043 if (sock) {
1044 lttcomm_destroy_sock(sock);
1045 }
1046 return NULL;
1047}
1048
f355467e
JG
1049static
1050struct lttcomm_sock *accept_relayd_sock(struct lttcomm_sock *listening_sock,
1051 const char *name)
1052{
1053 int out_fd, ret;
1054 struct lttcomm_sock *socks[2] = { listening_sock, NULL };
1055 struct lttcomm_sock *new_sock = NULL;
1056
1057 ret = fd_tracker_open_unsuspendable_fd(
1058 the_fd_tracker, &out_fd,
1059 (const char **) &name,
1060 1, accept_sock, &socks);
1061 if (ret) {
1062 goto end;
1063 }
1064 new_sock = socks[1];
1065 DBG("%s accepted, socket %d", name, new_sock->fd);
1066end:
1067 return new_sock;
1068}
1069
b8aa1682
JD
1070/*
1071 * This thread manages the listening for new connections on the network
1072 */
7591bab1 1073static void *relay_thread_listener(void *data)
b8aa1682 1074{
095a4ae5 1075 int i, ret, pollfd, err = -1;
b8aa1682
JD
1076 uint32_t revents, nb_fd;
1077 struct lttng_poll_event events;
1078 struct lttcomm_sock *control_sock, *data_sock;
1079
b8aa1682
JD
1080 DBG("[thread] Relay listener started");
1081
8fba2b8d 1082 rcu_register_thread();
55706a7d
MD
1083 health_register(health_relayd, HEALTH_RELAYD_TYPE_LISTENER);
1084
f385ae0a
MD
1085 health_code_update();
1086
40212d87 1087 control_sock = relay_socket_create(control_uri, "Control listener");
b8aa1682 1088 if (!control_sock) {
095a4ae5 1089 goto error_sock_control;
b8aa1682
JD
1090 }
1091
40212d87 1092 data_sock = relay_socket_create(data_uri, "Data listener");
b8aa1682 1093 if (!data_sock) {
095a4ae5 1094 goto error_sock_relay;
b8aa1682
JD
1095 }
1096
1097 /*
7591bab1
MD
1098 * Pass 3 as size here for the thread quit pipe, control and
1099 * data socket.
b8aa1682 1100 */
ba9cf8e1 1101 ret = create_named_thread_poll_set(&events, 3, "Listener thread epoll");
b8aa1682
JD
1102 if (ret < 0) {
1103 goto error_create_poll;
1104 }
1105
1106 /* Add the control socket */
1107 ret = lttng_poll_add(&events, control_sock->fd, LPOLLIN | LPOLLRDHUP);
1108 if (ret < 0) {
1109 goto error_poll_add;
1110 }
1111
1112 /* Add the data socket */
1113 ret = lttng_poll_add(&events, data_sock->fd, LPOLLIN | LPOLLRDHUP);
1114 if (ret < 0) {
1115 goto error_poll_add;
1116 }
1117
3fd27398
MD
1118 lttng_relay_notify_ready();
1119
9b5e0863
MD
1120 if (testpoint(relayd_thread_listener)) {
1121 goto error_testpoint;
1122 }
1123
b8aa1682 1124 while (1) {
f385ae0a
MD
1125 health_code_update();
1126
b8aa1682
JD
1127 DBG("Listener accepting connections");
1128
b8aa1682 1129restart:
f385ae0a 1130 health_poll_entry();
b8aa1682 1131 ret = lttng_poll_wait(&events, -1);
f385ae0a 1132 health_poll_exit();
b8aa1682
JD
1133 if (ret < 0) {
1134 /*
1135 * Restart interrupted system call.
1136 */
1137 if (errno == EINTR) {
1138 goto restart;
1139 }
1140 goto error;
1141 }
1142
0d9c5d77
DG
1143 nb_fd = ret;
1144
b8aa1682
JD
1145 DBG("Relay new connection received");
1146 for (i = 0; i < nb_fd; i++) {
f385ae0a
MD
1147 health_code_update();
1148
b8aa1682
JD
1149 /* Fetch once the poll data */
1150 revents = LTTNG_POLL_GETEV(&events, i);
1151 pollfd = LTTNG_POLL_GETFD(&events, i);
1152
1153 /* Thread quit pipe has been closed. Killing thread. */
1154 ret = check_thread_quit_pipe(pollfd, revents);
1155 if (ret) {
095a4ae5
MD
1156 err = 0;
1157 goto exit;
b8aa1682
JD
1158 }
1159
03e43155 1160 if (revents & LPOLLIN) {
4b7f17b2 1161 /*
7591bab1
MD
1162 * A new connection is requested, therefore a
1163 * sessiond/consumerd connection is allocated in
1164 * this thread, enqueued to a global queue and
1165 * dequeued (and freed) in the worker thread.
4b7f17b2 1166 */
58eb9381
DG
1167 int val = 1;
1168 struct relay_connection *new_conn;
f355467e 1169 struct lttcomm_sock *newsock = NULL;
7591bab1 1170 enum connection_type type;
b8aa1682
JD
1171
1172 if (pollfd == data_sock->fd) {
7591bab1 1173 type = RELAY_DATA;
f355467e
JG
1174 newsock = accept_relayd_sock(data_sock,
1175 "Data socket to relayd");
4b7f17b2
MD
1176 } else {
1177 assert(pollfd == control_sock->fd);
7591bab1 1178 type = RELAY_CONTROL;
875e3164
JG
1179 newsock = accept_relayd_sock(control_sock,
1180 "Control socket to relayd");
b8aa1682 1181 }
58eb9381
DG
1182 if (!newsock) {
1183 PERROR("accepting sock");
58eb9381
DG
1184 goto error;
1185 }
1186
1187 ret = setsockopt(newsock->fd, SOL_SOCKET, SO_REUSEADDR, &val,
1188 sizeof(val));
b8aa1682
JD
1189 if (ret < 0) {
1190 PERROR("setsockopt inet");
4b7f17b2 1191 lttcomm_destroy_sock(newsock);
b8aa1682
JD
1192 goto error;
1193 }
f056029c
JR
1194
1195 ret = socket_apply_keep_alive_config(newsock->fd);
1196 if (ret < 0) {
1197 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
1198 newsock->fd);
1199 lttcomm_destroy_sock(newsock);
1200 goto error;
1201 }
1202
7591bab1
MD
1203 new_conn = connection_create(newsock, type);
1204 if (!new_conn) {
1205 lttcomm_destroy_sock(newsock);
1206 goto error;
1207 }
58eb9381
DG
1208
1209 /* Enqueue request for the dispatcher thread. */
8bdee6e2
SM
1210 cds_wfcq_enqueue(&relay_conn_queue.head, &relay_conn_queue.tail,
1211 &new_conn->qnode);
b8aa1682
JD
1212
1213 /*
7591bab1
MD
1214 * Wake the dispatch queue futex.
1215 * Implicit memory barrier with the
1216 * exchange in cds_wfcq_enqueue.
b8aa1682 1217 */
58eb9381 1218 futex_nto1_wake(&relay_conn_queue.futex);
03e43155
MD
1219 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
1220 ERR("socket poll error");
1221 goto error;
1222 } else {
1223 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
1224 goto error;
b8aa1682
JD
1225 }
1226 }
1227 }
1228
095a4ae5 1229exit:
b8aa1682
JD
1230error:
1231error_poll_add:
9b5e0863 1232error_testpoint:
ba9cf8e1 1233 (void) fd_tracker_util_poll_clean(the_fd_tracker, &events);
b8aa1682 1234error_create_poll:
095a4ae5 1235 if (data_sock->fd >= 0) {
40212d87
JG
1236 int data_sock_fd = data_sock->fd;
1237
1238 ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker,
1239 &data_sock_fd, 1, close_sock,
1240 data_sock);
b8aa1682 1241 if (ret) {
40212d87 1242 PERROR("Failed to close the data listener socket file descriptor");
b8aa1682 1243 }
40212d87 1244 data_sock->fd = -1;
b8aa1682 1245 }
095a4ae5
MD
1246 lttcomm_destroy_sock(data_sock);
1247error_sock_relay:
1248 if (control_sock->fd >= 0) {
40212d87
JG
1249 int control_sock_fd = control_sock->fd;
1250
1251 ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker,
1252 &control_sock_fd, 1, close_sock,
1253 control_sock);
b8aa1682 1254 if (ret) {
40212d87 1255 PERROR("Failed to close the control listener socket file descriptor");
b8aa1682 1256 }
40212d87 1257 control_sock->fd = -1;
b8aa1682 1258 }
095a4ae5
MD
1259 lttcomm_destroy_sock(control_sock);
1260error_sock_control:
1261 if (err) {
f385ae0a
MD
1262 health_error();
1263 ERR("Health error occurred in %s", __func__);
095a4ae5 1264 }
55706a7d 1265 health_unregister(health_relayd);
8fba2b8d 1266 rcu_unregister_thread();
b8aa1682 1267 DBG("Relay listener thread cleanup complete");
b4aacfdc 1268 lttng_relay_stop_threads();
b8aa1682
JD
1269 return NULL;
1270}
1271
1272/*
1273 * This thread manages the dispatching of the requests to worker threads
1274 */
7591bab1 1275static void *relay_thread_dispatcher(void *data)
b8aa1682 1276{
6cd525e8
MD
1277 int err = -1;
1278 ssize_t ret;
8bdee6e2 1279 struct cds_wfcq_node *node;
58eb9381 1280 struct relay_connection *new_conn = NULL;
b8aa1682
JD
1281
1282 DBG("[thread] Relay dispatcher started");
1283
55706a7d
MD
1284 health_register(health_relayd, HEALTH_RELAYD_TYPE_DISPATCHER);
1285
9b5e0863
MD
1286 if (testpoint(relayd_thread_dispatcher)) {
1287 goto error_testpoint;
1288 }
1289
f385ae0a
MD
1290 health_code_update();
1291
0ed3b1a8 1292 for (;;) {
f385ae0a
MD
1293 health_code_update();
1294
b8aa1682 1295 /* Atomically prepare the queue futex */
58eb9381 1296 futex_nto1_prepare(&relay_conn_queue.futex);
b8aa1682 1297
0ed3b1a8
MD
1298 if (CMM_LOAD_SHARED(dispatch_thread_exit)) {
1299 break;
1300 }
1301
b8aa1682 1302 do {
f385ae0a
MD
1303 health_code_update();
1304
b8aa1682 1305 /* Dequeue commands */
8bdee6e2
SM
1306 node = cds_wfcq_dequeue_blocking(&relay_conn_queue.head,
1307 &relay_conn_queue.tail);
b8aa1682
JD
1308 if (node == NULL) {
1309 DBG("Woken up but nothing in the relay command queue");
1310 /* Continue thread execution */
1311 break;
1312 }
58eb9381 1313 new_conn = caa_container_of(node, struct relay_connection, qnode);
b8aa1682 1314
58eb9381 1315 DBG("Dispatching request waiting on sock %d", new_conn->sock->fd);
b8aa1682
JD
1316
1317 /*
7591bab1
MD
1318 * Inform worker thread of the new request. This
1319 * call is blocking so we can be assured that
1320 * the data will be read at some point in time
1321 * or wait to the end of the world :)
b8aa1682 1322 */
58eb9381
DG
1323 ret = lttng_write(relay_conn_pipe[1], &new_conn, sizeof(new_conn));
1324 if (ret < 0) {
1325 PERROR("write connection pipe");
7591bab1 1326 connection_put(new_conn);
b8aa1682
JD
1327 goto error;
1328 }
1329 } while (node != NULL);
1330
1331 /* Futex wait on queue. Blocking call on futex() */
f385ae0a 1332 health_poll_entry();
58eb9381 1333 futex_nto1_wait(&relay_conn_queue.futex);
f385ae0a 1334 health_poll_exit();
b8aa1682
JD
1335 }
1336
f385ae0a
MD
1337 /* Normal exit, no error */
1338 err = 0;
1339
b8aa1682 1340error:
9b5e0863 1341error_testpoint:
f385ae0a
MD
1342 if (err) {
1343 health_error();
1344 ERR("Health error occurred in %s", __func__);
1345 }
55706a7d 1346 health_unregister(health_relayd);
b8aa1682 1347 DBG("Dispatch thread dying");
b4aacfdc 1348 lttng_relay_stop_threads();
b8aa1682
JD
1349 return NULL;
1350}
1351
298a25ca
JG
1352static bool session_streams_have_index(const struct relay_session *session)
1353{
1354 return session->minor >= 4 && !session->snapshot;
1355}
1356
c5b6f4f0
DG
1357/*
1358 * Handle the RELAYD_CREATE_SESSION command.
1359 *
1360 * On success, send back the session id or else return a negative value.
1361 */
5312a3ed
JG
1362static int relay_create_session(const struct lttcomm_relayd_hdr *recv_hdr,
1363 struct relay_connection *conn,
1364 const struct lttng_buffer_view *payload)
c5b6f4f0 1365{
5312a3ed
JG
1366 int ret = 0;
1367 ssize_t send_ret;
4c6885d2 1368 struct relay_session *session = NULL;
ecd1a12f 1369 struct lttcomm_relayd_create_session_reply_2_11 reply = {};
1e791a74
JG
1370 char session_name[LTTNG_NAME_MAX] = {};
1371 char hostname[LTTNG_HOST_NAME_MAX] = {};
7591bab1
MD
1372 uint32_t live_timer = 0;
1373 bool snapshot = false;
46ef2188 1374 bool session_name_contains_creation_timestamp = false;
23c8ff50 1375 /* Left nil for peers < 2.11. */
6fa5fe7c 1376 char base_path[LTTNG_PATH_MAX] = {};
23c8ff50 1377 lttng_uuid sessiond_uuid = {};
1e791a74
JG
1378 LTTNG_OPTIONAL(uint64_t) id_sessiond = {};
1379 LTTNG_OPTIONAL(uint64_t) current_chunk_id = {};
db1da059 1380 LTTNG_OPTIONAL(time_t) creation_time = {};
ecd1a12f
MD
1381 struct lttng_dynamic_buffer reply_payload;
1382
1383 lttng_dynamic_buffer_init(&reply_payload);
c5b6f4f0 1384
f86f6389
JR
1385 if (conn->minor < 4) {
1386 /* From 2.1 to 2.3 */
1387 ret = 0;
1388 } else if (conn->minor >= 4 && conn->minor < 11) {
1389 /* From 2.4 to 2.10 */
5312a3ed 1390 ret = cmd_create_session_2_4(payload, session_name,
7591bab1 1391 hostname, &live_timer, &snapshot);
f86f6389 1392 } else {
84fa4db5 1393 bool has_current_chunk;
db1da059
JG
1394 uint64_t current_chunk_id_value;
1395 time_t creation_time_value;
1396 uint64_t id_sessiond_value;
84fa4db5 1397
f86f6389 1398 /* From 2.11 to ... */
db1da059 1399 ret = cmd_create_session_2_11(payload, session_name, hostname,
6fa5fe7c 1400 base_path, &live_timer, &snapshot, &id_sessiond_value,
db1da059 1401 sessiond_uuid, &has_current_chunk,
46ef2188
MD
1402 &current_chunk_id_value, &creation_time_value,
1403 &session_name_contains_creation_timestamp);
23c8ff50
JG
1404 if (lttng_uuid_is_nil(sessiond_uuid)) {
1405 /* The nil UUID is reserved for pre-2.11 clients. */
1406 ERR("Illegal nil UUID announced by peer in create session command");
1407 ret = -1;
1408 goto send_reply;
1409 }
db1da059
JG
1410 LTTNG_OPTIONAL_SET(&id_sessiond, id_sessiond_value);
1411 LTTNG_OPTIONAL_SET(&creation_time, creation_time_value);
1412 if (has_current_chunk) {
1413 LTTNG_OPTIONAL_SET(&current_chunk_id,
1414 current_chunk_id_value);
1415 }
7591bab1 1416 }
f86f6389 1417
7591bab1
MD
1418 if (ret < 0) {
1419 goto send_reply;
d3e2ba59
JD
1420 }
1421
6fa5fe7c 1422 session = session_create(session_name, hostname, base_path, live_timer,
1e791a74
JG
1423 snapshot, sessiond_uuid,
1424 id_sessiond.is_set ? &id_sessiond.value : NULL,
1425 current_chunk_id.is_set ? &current_chunk_id.value : NULL,
db1da059 1426 creation_time.is_set ? &creation_time.value : NULL,
46ef2188
MD
1427 conn->major, conn->minor,
1428 session_name_contains_creation_timestamp);
7591bab1
MD
1429 if (!session) {
1430 ret = -1;
1431 goto send_reply;
1432 }
1433 assert(!conn->session);
1434 conn->session = session;
c5b6f4f0
DG
1435 DBG("Created session %" PRIu64, session->id);
1436
ecd1a12f 1437 reply.generic.session_id = htobe64(session->id);
7591bab1
MD
1438
1439send_reply:
c5b6f4f0 1440 if (ret < 0) {
ecd1a12f 1441 reply.generic.ret_code = htobe32(LTTNG_ERR_FATAL);
c5b6f4f0 1442 } else {
ecd1a12f 1443 reply.generic.ret_code = htobe32(LTTNG_OK);
c5b6f4f0
DG
1444 }
1445
ecd1a12f
MD
1446 if (conn->minor < 11) {
1447 /* From 2.1 to 2.10 */
1448 ret = lttng_dynamic_buffer_append(&reply_payload,
1449 &reply.generic, sizeof(reply.generic));
1450 if (ret) {
1451 ERR("Failed to append \"create session\" command reply header to payload buffer");
1452 ret = -1;
1453 goto end;
1454 }
1455 } else {
1456 const uint32_t output_path_length =
8d382dd4 1457 session ? strlen(session->output_path) + 1 : 0;
ecd1a12f
MD
1458
1459 reply.output_path_length = htobe32(output_path_length);
8d382dd4
JG
1460 ret = lttng_dynamic_buffer_append(
1461 &reply_payload, &reply, sizeof(reply));
ecd1a12f
MD
1462 if (ret) {
1463 ERR("Failed to append \"create session\" command reply header to payload buffer");
1464 goto end;
1465 }
1466
8d382dd4
JG
1467 if (output_path_length) {
1468 ret = lttng_dynamic_buffer_append(&reply_payload,
1469 session->output_path,
1470 output_path_length);
1471 if (ret) {
1472 ERR("Failed to append \"create session\" command reply path to payload buffer");
1473 goto end;
1474 }
ecd1a12f
MD
1475 }
1476 }
1477
1478 send_ret = conn->sock->ops->sendmsg(conn->sock, reply_payload.data,
1479 reply_payload.size, 0);
1480 if (send_ret < (ssize_t) reply_payload.size) {
1481 ERR("Failed to send \"create session\" command reply of %zu bytes (ret = %zd)",
1482 reply_payload.size, send_ret);
5312a3ed 1483 ret = -1;
c5b6f4f0 1484 }
ecd1a12f 1485end:
4c6885d2
JG
1486 if (ret < 0 && session) {
1487 session_put(session);
1488 }
ecd1a12f 1489 lttng_dynamic_buffer_reset(&reply_payload);
c5b6f4f0
DG
1490 return ret;
1491}
1492
a4baae1b
JD
1493/*
1494 * When we have received all the streams and the metadata for a channel,
1495 * we make them visible to the viewer threads.
1496 */
7591bab1 1497static void publish_connection_local_streams(struct relay_connection *conn)
a4baae1b 1498{
7591bab1
MD
1499 struct relay_stream *stream;
1500 struct relay_session *session = conn->session;
a4baae1b 1501
7591bab1
MD
1502 /*
1503 * We publish all streams belonging to a session atomically wrt
1504 * session lock.
1505 */
1506 pthread_mutex_lock(&session->lock);
1507 rcu_read_lock();
1508 cds_list_for_each_entry_rcu(stream, &session->recv_list,
1509 recv_node) {
1510 stream_publish(stream);
a4baae1b 1511 }
7591bab1 1512 rcu_read_unlock();
a4baae1b 1513
7591bab1
MD
1514 /*
1515 * Inform the viewer that there are new streams in the session.
1516 */
1517 if (session->viewer_attached) {
1518 uatomic_set(&session->new_streams, 1);
1519 }
1520 pthread_mutex_unlock(&session->lock);
a4baae1b
JD
1521}
1522
348a81dc
JG
1523static int conform_channel_path(char *channel_path)
1524{
1525 int ret = 0;
1526
1527 if (strstr("../", channel_path)) {
1528 ERR("Refusing channel path as it walks up the path hierarchy: \"%s\"",
1529 channel_path);
1530 ret = -1;
1531 goto end;
1532 }
1533
1534 if (*channel_path == '/') {
1535 const size_t len = strlen(channel_path);
1536
1537 /*
1538 * Channel paths from peers prior to 2.11 are expressed as an
1539 * absolute path that is, in reality, relative to the relay
1540 * daemon's output directory. Remove the leading slash so it
1541 * is correctly interpreted as a relative path later on.
1542 *
1543 * len (and not len - 1) is used to copy the trailing NULL.
1544 */
1545 bcopy(channel_path + 1, channel_path, len);
1546 }
1547end:
1548 return ret;
1549}
1550
b8aa1682
JD
1551/*
1552 * relay_add_stream: allocate a new stream for a session
1553 */
5312a3ed
JG
1554static int relay_add_stream(const struct lttcomm_relayd_hdr *recv_hdr,
1555 struct relay_connection *conn,
1556 const struct lttng_buffer_view *payload)
b8aa1682 1557{
7591bab1
MD
1558 int ret;
1559 ssize_t send_ret;
58eb9381 1560 struct relay_session *session = conn->session;
b8aa1682
JD
1561 struct relay_stream *stream = NULL;
1562 struct lttcomm_relayd_status_stream reply;
4030a636 1563 struct ctf_trace *trace = NULL;
7591bab1
MD
1564 uint64_t stream_handle = -1ULL;
1565 char *path_name = NULL, *channel_name = NULL;
1566 uint64_t tracefile_size = 0, tracefile_count = 0;
348a81dc 1567 LTTNG_OPTIONAL(uint64_t) stream_chunk_id = {};
b8aa1682 1568
5312a3ed 1569 if (!session || !conn->version_check_done) {
b8aa1682
JD
1570 ERR("Trying to add a stream before version check");
1571 ret = -1;
1572 goto end_no_session;
1573 }
1574
2f21a469
JR
1575 if (session->minor == 1) {
1576 /* For 2.1 */
5312a3ed 1577 ret = cmd_recv_stream_2_1(payload, &path_name,
7591bab1 1578 &channel_name);
2f21a469
JR
1579 } else if (session->minor > 1 && session->minor < 11) {
1580 /* From 2.2 to 2.10 */
5312a3ed 1581 ret = cmd_recv_stream_2_2(payload, &path_name,
7591bab1 1582 &channel_name, &tracefile_size, &tracefile_count);
2f21a469
JR
1583 } else {
1584 /* From 2.11 to ... */
1585 ret = cmd_recv_stream_2_11(payload, &path_name,
0b50e4b3
JG
1586 &channel_name, &tracefile_size, &tracefile_count,
1587 &stream_chunk_id.value);
1588 stream_chunk_id.is_set = true;
0f907de1 1589 }
2f21a469 1590
0f907de1 1591 if (ret < 0) {
7591bab1 1592 goto send_reply;
b8aa1682
JD
1593 }
1594
348a81dc
JG
1595 if (conform_channel_path(path_name)) {
1596 goto send_reply;
1597 }
1598
2a635488
JR
1599 /*
1600 * Backward compatibility for --group-output-by-session.
1601 * Prior to lttng 2.11, the complete path is passed by the stream.
1602 * Starting at 2.11, lttng-relayd uses chunk. When dealing with producer
1603 * >=2.11 the chunk is responsible for the output path. When dealing
1604 * with producer < 2.11 the chunk output_path is the root output path
1605 * and the stream carries the complete path (path_name).
1606 * To support --group-output-by-session with older producer (<2.11), we
1607 * need to craft the path based on the stream path.
1608 */
1609 if (opt_group_output_by == RELAYD_GROUP_OUTPUT_BY_SESSION) {
1610 if (conn->minor < 4) {
1611 /*
1612 * From 2.1 to 2.3, the session_name is not passed on
1613 * the RELAYD_CREATE_SESSION command. The session name
1614 * is necessary to detect the presence of a base_path
1615 * inside the stream path. Without it we cannot perform
1616 * a valid group-output-by-session transformation.
1617 */
1618 WARN("Unable to perform a --group-by-session transformation for session %" PRIu64
1619 " for stream with path \"%s\" as it is produced by a peer using a protocol older than v2.4",
1620 session->id, path_name);
1621 } else if (conn->minor >= 4 && conn->minor < 11) {
1622 char *group_by_session_path_name;
1623
1624 assert(session->session_name[0] != '\0');
1625
1626 group_by_session_path_name =
1627 backward_compat_group_by_session(
1628 path_name,
1629 session->session_name);
1630 if (!group_by_session_path_name) {
1631 ERR("Failed to apply group by session to stream of session %" PRIu64,
1632 session->id);
1633 goto send_reply;
1634 }
1635
1636 DBG("Transformed session path from \"%s\" to \"%s\" to honor per-session name grouping",
1637 path_name, group_by_session_path_name);
1638
1639 free(path_name);
1640 path_name = group_by_session_path_name;
1641 }
1642 }
1643
7591bab1 1644 trace = ctf_trace_get_by_path_or_create(session, path_name);
2a174661 1645 if (!trace) {
7591bab1 1646 goto send_reply;
2a174661 1647 }
2a174661 1648
2a635488 1649 /* This stream here has one reference on the trace. */
7591bab1
MD
1650 pthread_mutex_lock(&last_relay_stream_id_lock);
1651 stream_handle = ++last_relay_stream_id;
1652 pthread_mutex_unlock(&last_relay_stream_id_lock);
d3e2ba59 1653
7591bab1
MD
1654 /* We pass ownership of path_name and channel_name. */
1655 stream = stream_create(trace, stream_handle, path_name,
348a81dc 1656 channel_name, tracefile_size, tracefile_count);
7591bab1
MD
1657 path_name = NULL;
1658 channel_name = NULL;
a4baae1b 1659
2a174661 1660 /*
7591bab1
MD
1661 * Streams are the owners of their trace. Reference to trace is
1662 * kept within stream_create().
2a174661 1663 */
7591bab1 1664 ctf_trace_put(trace);
d3e2ba59 1665
7591bab1 1666send_reply:
53efb85a 1667 memset(&reply, 0, sizeof(reply));
7591bab1
MD
1668 reply.handle = htobe64(stream_handle);
1669 if (!stream) {
f73fabfd 1670 reply.ret_code = htobe32(LTTNG_ERR_UNK);
b8aa1682 1671 } else {
f73fabfd 1672 reply.ret_code = htobe32(LTTNG_OK);
b8aa1682 1673 }
5af40280 1674
58eb9381 1675 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
b8aa1682 1676 sizeof(struct lttcomm_relayd_status_stream), 0);
5312a3ed
JG
1677 if (send_ret < (ssize_t) sizeof(reply)) {
1678 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1679 send_ret);
1680 ret = -1;
b8aa1682
JD
1681 }
1682
1683end_no_session:
7591bab1
MD
1684 free(path_name);
1685 free(channel_name);
0f907de1 1686 return ret;
b8aa1682
JD
1687}
1688
173af62f
DG
1689/*
1690 * relay_close_stream: close a specific stream
1691 */
5312a3ed
JG
1692static int relay_close_stream(const struct lttcomm_relayd_hdr *recv_hdr,
1693 struct relay_connection *conn,
1694 const struct lttng_buffer_view *payload)
173af62f 1695{
5312a3ed
JG
1696 int ret;
1697 ssize_t send_ret;
58eb9381 1698 struct relay_session *session = conn->session;
173af62f
DG
1699 struct lttcomm_relayd_close_stream stream_info;
1700 struct lttcomm_relayd_generic_reply reply;
1701 struct relay_stream *stream;
173af62f
DG
1702
1703 DBG("Close stream received");
1704
5312a3ed 1705 if (!session || !conn->version_check_done) {
173af62f
DG
1706 ERR("Trying to close a stream before version check");
1707 ret = -1;
1708 goto end_no_session;
1709 }
1710
5312a3ed
JG
1711 if (payload->size < sizeof(stream_info)) {
1712 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1713 sizeof(stream_info), payload->size);
173af62f
DG
1714 ret = -1;
1715 goto end_no_session;
1716 }
5312a3ed
JG
1717 memcpy(&stream_info, payload->data, sizeof(stream_info));
1718 stream_info.stream_id = be64toh(stream_info.stream_id);
1719 stream_info.last_net_seq_num = be64toh(stream_info.last_net_seq_num);
173af62f 1720
5312a3ed 1721 stream = stream_get_by_id(stream_info.stream_id);
173af62f
DG
1722 if (!stream) {
1723 ret = -1;
7591bab1 1724 goto end;
173af62f 1725 }
77f7bd85
MD
1726
1727 /*
1728 * Set last_net_seq_num before the close flag. Required by data
1729 * pending check.
1730 */
7591bab1 1731 pthread_mutex_lock(&stream->lock);
5312a3ed 1732 stream->last_net_seq_num = stream_info.last_net_seq_num;
77f7bd85
MD
1733 pthread_mutex_unlock(&stream->lock);
1734
bda7c7b9
JG
1735 /*
1736 * This is one of the conditions which may trigger a stream close
1737 * with the others being:
1738 * 1) A close command is received for a stream
1739 * 2) The control connection owning the stream is closed
1740 * 3) We have received all of the stream's data _after_ a close
1741 * request.
1742 */
1743 try_stream_close(stream);
7591bab1
MD
1744 if (stream->is_metadata) {
1745 struct relay_viewer_stream *vstream;
173af62f 1746
7591bab1
MD
1747 vstream = viewer_stream_get_by_id(stream->stream_handle);
1748 if (vstream) {
94f73d08 1749 if (stream->no_new_metadata_notified) {
7591bab1
MD
1750 /*
1751 * Since all the metadata has been sent to the
1752 * viewer and that we have a request to close
1753 * its stream, we can safely teardown the
1754 * corresponding metadata viewer stream.
1755 */
1756 viewer_stream_put(vstream);
1757 }
1758 /* Put local reference. */
1759 viewer_stream_put(vstream);
1760 }
1761 }
7591bab1 1762 stream_put(stream);
5312a3ed 1763 ret = 0;
173af62f 1764
7591bab1 1765end:
53efb85a 1766 memset(&reply, 0, sizeof(reply));
173af62f 1767 if (ret < 0) {
f73fabfd 1768 reply.ret_code = htobe32(LTTNG_ERR_UNK);
173af62f 1769 } else {
f73fabfd 1770 reply.ret_code = htobe32(LTTNG_OK);
173af62f 1771 }
58eb9381 1772 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
173af62f 1773 sizeof(struct lttcomm_relayd_generic_reply), 0);
5312a3ed
JG
1774 if (send_ret < (ssize_t) sizeof(reply)) {
1775 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1776 send_ret);
1777 ret = -1;
173af62f
DG
1778 }
1779
1780end_no_session:
1781 return ret;
1782}
1783
93ec662e
JD
1784/*
1785 * relay_reset_metadata: reset a metadata stream
1786 */
1787static
5312a3ed
JG
1788int relay_reset_metadata(const struct lttcomm_relayd_hdr *recv_hdr,
1789 struct relay_connection *conn,
1790 const struct lttng_buffer_view *payload)
93ec662e 1791{
5312a3ed
JG
1792 int ret;
1793 ssize_t send_ret;
93ec662e
JD
1794 struct relay_session *session = conn->session;
1795 struct lttcomm_relayd_reset_metadata stream_info;
1796 struct lttcomm_relayd_generic_reply reply;
1797 struct relay_stream *stream;
1798
1799 DBG("Reset metadata received");
1800
5312a3ed 1801 if (!session || !conn->version_check_done) {
93ec662e
JD
1802 ERR("Trying to reset a metadata stream before version check");
1803 ret = -1;
1804 goto end_no_session;
1805 }
1806
5312a3ed
JG
1807 if (payload->size < sizeof(stream_info)) {
1808 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1809 sizeof(stream_info), payload->size);
93ec662e
JD
1810 ret = -1;
1811 goto end_no_session;
1812 }
5312a3ed
JG
1813 memcpy(&stream_info, payload->data, sizeof(stream_info));
1814 stream_info.stream_id = be64toh(stream_info.stream_id);
1815 stream_info.version = be64toh(stream_info.version);
1816
1817 DBG("Update metadata to version %" PRIu64, stream_info.version);
93ec662e
JD
1818
1819 /* Unsupported for live sessions for now. */
1820 if (session->live_timer != 0) {
1821 ret = -1;
1822 goto end;
1823 }
1824
5312a3ed 1825 stream = stream_get_by_id(stream_info.stream_id);
93ec662e
JD
1826 if (!stream) {
1827 ret = -1;
1828 goto end;
1829 }
1830 pthread_mutex_lock(&stream->lock);
1831 if (!stream->is_metadata) {
1832 ret = -1;
1833 goto end_unlock;
1834 }
1835
c35f9726 1836 ret = stream_reset_file(stream);
93ec662e 1837 if (ret < 0) {
c35f9726
JG
1838 ERR("Failed to reset metadata stream %" PRIu64
1839 ": stream_path = %s, channel = %s",
1840 stream->stream_handle, stream->path_name,
1841 stream->channel_name);
93ec662e
JD
1842 goto end_unlock;
1843 }
93ec662e
JD
1844end_unlock:
1845 pthread_mutex_unlock(&stream->lock);
1846 stream_put(stream);
1847
1848end:
1849 memset(&reply, 0, sizeof(reply));
1850 if (ret < 0) {
1851 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1852 } else {
1853 reply.ret_code = htobe32(LTTNG_OK);
1854 }
1855 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1856 sizeof(struct lttcomm_relayd_generic_reply), 0);
5312a3ed
JG
1857 if (send_ret < (ssize_t) sizeof(reply)) {
1858 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1859 send_ret);
1860 ret = -1;
93ec662e
JD
1861 }
1862
1863end_no_session:
1864 return ret;
1865}
1866
b8aa1682
JD
1867/*
1868 * relay_unknown_command: send -1 if received unknown command
1869 */
7591bab1 1870static void relay_unknown_command(struct relay_connection *conn)
b8aa1682
JD
1871{
1872 struct lttcomm_relayd_generic_reply reply;
5312a3ed 1873 ssize_t send_ret;
b8aa1682 1874
53efb85a 1875 memset(&reply, 0, sizeof(reply));
f73fabfd 1876 reply.ret_code = htobe32(LTTNG_ERR_UNK);
5312a3ed
JG
1877 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1878 if (send_ret < sizeof(reply)) {
1879 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret);
b8aa1682
JD
1880 }
1881}
1882
1883/*
1884 * relay_start: send an acknowledgment to the client to tell if we are
1885 * ready to receive data. We are ready if a session is established.
1886 */
5312a3ed
JG
1887static int relay_start(const struct lttcomm_relayd_hdr *recv_hdr,
1888 struct relay_connection *conn,
1889 const struct lttng_buffer_view *payload)
b8aa1682 1890{
5312a3ed
JG
1891 int ret = 0;
1892 ssize_t send_ret;
b8aa1682 1893 struct lttcomm_relayd_generic_reply reply;
58eb9381 1894 struct relay_session *session = conn->session;
b8aa1682
JD
1895
1896 if (!session) {
1897 DBG("Trying to start the streaming without a session established");
f73fabfd 1898 ret = htobe32(LTTNG_ERR_UNK);
b8aa1682
JD
1899 }
1900
53efb85a 1901 memset(&reply, 0, sizeof(reply));
5312a3ed
JG
1902 reply.ret_code = htobe32(LTTNG_OK);
1903 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1904 sizeof(reply), 0);
1905 if (send_ret < (ssize_t) sizeof(reply)) {
1906 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1907 send_ret);
1908 ret = -1;
b8aa1682
JD
1909 }
1910
1911 return ret;
1912}
1913
b8aa1682 1914/*
7591bab1 1915 * relay_recv_metadata: receive the metadata for the session.
b8aa1682 1916 */
5312a3ed
JG
1917static int relay_recv_metadata(const struct lttcomm_relayd_hdr *recv_hdr,
1918 struct relay_connection *conn,
1919 const struct lttng_buffer_view *payload)
b8aa1682 1920{
32d1569c 1921 int ret = 0;
58eb9381 1922 struct relay_session *session = conn->session;
5312a3ed 1923 struct lttcomm_relayd_metadata_payload metadata_payload_header;
b8aa1682 1924 struct relay_stream *metadata_stream;
5312a3ed 1925 uint64_t metadata_payload_size;
c35f9726 1926 struct lttng_buffer_view packet_view;
b8aa1682
JD
1927
1928 if (!session) {
1929 ERR("Metadata sent before version check");
1930 ret = -1;
1931 goto end;
1932 }
1933
5312a3ed 1934 if (recv_hdr->data_size < sizeof(struct lttcomm_relayd_metadata_payload)) {
f6416125
MD
1935 ERR("Incorrect data size");
1936 ret = -1;
1937 goto end;
1938 }
5312a3ed
JG
1939 metadata_payload_size = recv_hdr->data_size -
1940 sizeof(struct lttcomm_relayd_metadata_payload);
f6416125 1941
5312a3ed
JG
1942 memcpy(&metadata_payload_header, payload->data,
1943 sizeof(metadata_payload_header));
1944 metadata_payload_header.stream_id = be64toh(
1945 metadata_payload_header.stream_id);
1946 metadata_payload_header.padding_size = be32toh(
1947 metadata_payload_header.padding_size);
9d1bbf21 1948
5312a3ed 1949 metadata_stream = stream_get_by_id(metadata_payload_header.stream_id);
b8aa1682
JD
1950 if (!metadata_stream) {
1951 ret = -1;
7591bab1 1952 goto end;
b8aa1682
JD
1953 }
1954
c35f9726
JG
1955 packet_view = lttng_buffer_view_from_view(payload,
1956 sizeof(metadata_payload_header), metadata_payload_size);
1957 if (!packet_view.data) {
1958 ERR("Invalid metadata packet length announced by header");
b8aa1682 1959 ret = -1;
7591bab1 1960 goto end_put;
b8aa1682 1961 }
1d4dfdef 1962
c35f9726
JG
1963 pthread_mutex_lock(&metadata_stream->lock);
1964 ret = stream_write(metadata_stream, &packet_view,
5312a3ed 1965 metadata_payload_header.padding_size);
c35f9726
JG
1966 pthread_mutex_unlock(&metadata_stream->lock);
1967 if (ret){
5312a3ed 1968 ret = -1;
7591bab1 1969 goto end_put;
1d4dfdef 1970 }
7591bab1 1971end_put:
7591bab1 1972 stream_put(metadata_stream);
b8aa1682
JD
1973end:
1974 return ret;
1975}
1976
1977/*
1978 * relay_send_version: send relayd version number
1979 */
5312a3ed
JG
1980static int relay_send_version(const struct lttcomm_relayd_hdr *recv_hdr,
1981 struct relay_connection *conn,
1982 const struct lttng_buffer_view *payload)
b8aa1682 1983{
7f51dcba 1984 int ret;
5312a3ed 1985 ssize_t send_ret;
092b6259 1986 struct lttcomm_relayd_version reply, msg;
87cb6359 1987 bool compatible = true;
b8aa1682 1988
5312a3ed 1989 conn->version_check_done = true;
b8aa1682 1990
092b6259 1991 /* Get version from the other side. */
5312a3ed
JG
1992 if (payload->size < sizeof(msg)) {
1993 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1994 sizeof(msg), payload->size);
092b6259 1995 ret = -1;
092b6259
DG
1996 goto end;
1997 }
1998
5312a3ed
JG
1999 memcpy(&msg, payload->data, sizeof(msg));
2000 msg.major = be32toh(msg.major);
2001 msg.minor = be32toh(msg.minor);
2002
53efb85a 2003 memset(&reply, 0, sizeof(reply));
d83a952c
MD
2004 reply.major = RELAYD_VERSION_COMM_MAJOR;
2005 reply.minor = RELAYD_VERSION_COMM_MINOR;
d4519fa3
JD
2006
2007 /* Major versions must be the same */
5312a3ed 2008 if (reply.major != msg.major) {
6151a90f 2009 DBG("Incompatible major versions (%u vs %u), deleting session",
5312a3ed 2010 reply.major, msg.major);
87cb6359 2011 compatible = false;
d4519fa3
JD
2012 }
2013
58eb9381 2014 conn->major = reply.major;
0f907de1 2015 /* We adapt to the lowest compatible version */
5312a3ed 2016 if (reply.minor <= msg.minor) {
58eb9381 2017 conn->minor = reply.minor;
0f907de1 2018 } else {
5312a3ed 2019 conn->minor = msg.minor;
0f907de1
JD
2020 }
2021
6151a90f
JD
2022 reply.major = htobe32(reply.major);
2023 reply.minor = htobe32(reply.minor);
5312a3ed
JG
2024 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
2025 sizeof(reply), 0);
2026 if (send_ret < (ssize_t) sizeof(reply)) {
2027 ERR("Failed to send \"send version\" command reply (ret = %zd)",
2028 send_ret);
2029 ret = -1;
2030 goto end;
2031 } else {
2032 ret = 0;
6151a90f
JD
2033 }
2034
87cb6359
JD
2035 if (!compatible) {
2036 ret = -1;
2037 goto end;
2038 }
2039
58eb9381
DG
2040 DBG("Version check done using protocol %u.%u", conn->major,
2041 conn->minor);
b8aa1682
JD
2042
2043end:
2044 return ret;
2045}
2046
c8f59ee5 2047/*
6d805429 2048 * Check for data pending for a given stream id from the session daemon.
c8f59ee5 2049 */
5312a3ed
JG
2050static int relay_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
2051 struct relay_connection *conn,
2052 const struct lttng_buffer_view *payload)
c8f59ee5 2053{
58eb9381 2054 struct relay_session *session = conn->session;
6d805429 2055 struct lttcomm_relayd_data_pending msg;
c8f59ee5
DG
2056 struct lttcomm_relayd_generic_reply reply;
2057 struct relay_stream *stream;
5312a3ed 2058 ssize_t send_ret;
c8f59ee5 2059 int ret;
298a25ca 2060 uint64_t stream_seq;
c8f59ee5 2061
6d805429 2062 DBG("Data pending command received");
c8f59ee5 2063
5312a3ed 2064 if (!session || !conn->version_check_done) {
c8f59ee5
DG
2065 ERR("Trying to check for data before version check");
2066 ret = -1;
2067 goto end_no_session;
2068 }
2069
5312a3ed
JG
2070 if (payload->size < sizeof(msg)) {
2071 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
2072 sizeof(msg), payload->size);
c8f59ee5
DG
2073 ret = -1;
2074 goto end_no_session;
2075 }
5312a3ed
JG
2076 memcpy(&msg, payload->data, sizeof(msg));
2077 msg.stream_id = be64toh(msg.stream_id);
2078 msg.last_net_seq_num = be64toh(msg.last_net_seq_num);
c8f59ee5 2079
5312a3ed 2080 stream = stream_get_by_id(msg.stream_id);
de91f48a 2081 if (stream == NULL) {
c8f59ee5 2082 ret = -1;
7591bab1 2083 goto end;
c8f59ee5
DG
2084 }
2085
7591bab1
MD
2086 pthread_mutex_lock(&stream->lock);
2087
298a25ca
JG
2088 if (session_streams_have_index(session)) {
2089 /*
2090 * Ensure that both the index and stream data have been
2091 * flushed up to the requested point.
2092 */
a8f9f353 2093 stream_seq = min(stream->prev_data_seq, stream->prev_index_seq);
298a25ca 2094 } else {
a8f9f353 2095 stream_seq = stream->prev_data_seq;
298a25ca 2096 }
a8f9f353 2097 DBG("Data pending for stream id %" PRIu64 ": prev_data_seq %" PRIu64
298a25ca
JG
2098 ", prev_index_seq %" PRIu64
2099 ", and last_seq %" PRIu64, msg.stream_id,
a8f9f353 2100 stream->prev_data_seq, stream->prev_index_seq,
298a25ca 2101 msg.last_net_seq_num);
c8f59ee5 2102
33832e64 2103 /* Avoid wrapping issue */
298a25ca 2104 if (((int64_t) (stream_seq - msg.last_net_seq_num)) >= 0) {
6d805429 2105 /* Data has in fact been written and is NOT pending */
c8f59ee5 2106 ret = 0;
6d805429
DG
2107 } else {
2108 /* Data still being streamed thus pending */
2109 ret = 1;
c8f59ee5
DG
2110 }
2111
7591bab1
MD
2112 stream->data_pending_check_done = true;
2113 pthread_mutex_unlock(&stream->lock);
f7079f67 2114
7591bab1
MD
2115 stream_put(stream);
2116end:
c8f59ee5 2117
53efb85a 2118 memset(&reply, 0, sizeof(reply));
c8f59ee5 2119 reply.ret_code = htobe32(ret);
5312a3ed
JG
2120 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2121 if (send_ret < (ssize_t) sizeof(reply)) {
2122 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
2123 send_ret);
2124 ret = -1;
c8f59ee5
DG
2125 }
2126
2127end_no_session:
2128 return ret;
2129}
2130
2131/*
2132 * Wait for the control socket to reach a quiescent state.
2133 *
7591bab1
MD
2134 * Note that for now, when receiving this command from the session
2135 * daemon, this means that every subsequent commands or data received on
2136 * the control socket has been handled. So, this is why we simply return
2137 * OK here.
c8f59ee5 2138 */
5312a3ed
JG
2139static int relay_quiescent_control(const struct lttcomm_relayd_hdr *recv_hdr,
2140 struct relay_connection *conn,
2141 const struct lttng_buffer_view *payload)
c8f59ee5
DG
2142{
2143 int ret;
5312a3ed 2144 ssize_t send_ret;
ad7051c0 2145 struct relay_stream *stream;
ad7051c0 2146 struct lttcomm_relayd_quiescent_control msg;
c8f59ee5
DG
2147 struct lttcomm_relayd_generic_reply reply;
2148
2149 DBG("Checking quiescent state on control socket");
2150
5312a3ed 2151 if (!conn->session || !conn->version_check_done) {
ad7051c0
DG
2152 ERR("Trying to check for data before version check");
2153 ret = -1;
2154 goto end_no_session;
2155 }
2156
5312a3ed
JG
2157 if (payload->size < sizeof(msg)) {
2158 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2159 sizeof(msg), payload->size);
ad7051c0
DG
2160 ret = -1;
2161 goto end_no_session;
2162 }
5312a3ed
JG
2163 memcpy(&msg, payload->data, sizeof(msg));
2164 msg.stream_id = be64toh(msg.stream_id);
ad7051c0 2165
5312a3ed 2166 stream = stream_get_by_id(msg.stream_id);
7591bab1
MD
2167 if (!stream) {
2168 goto reply;
2169 }
2170 pthread_mutex_lock(&stream->lock);
2171 stream->data_pending_check_done = true;
2172 pthread_mutex_unlock(&stream->lock);
5312a3ed
JG
2173
2174 DBG("Relay quiescent control pending flag set to %" PRIu64, msg.stream_id);
7591bab1
MD
2175 stream_put(stream);
2176reply:
53efb85a 2177 memset(&reply, 0, sizeof(reply));
c8f59ee5 2178 reply.ret_code = htobe32(LTTNG_OK);
5312a3ed
JG
2179 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2180 if (send_ret < (ssize_t) sizeof(reply)) {
2181 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
2182 send_ret);
2183 ret = -1;
2184 } else {
2185 ret = 0;
c8f59ee5
DG
2186 }
2187
ad7051c0 2188end_no_session:
c8f59ee5
DG
2189 return ret;
2190}
2191
f7079f67 2192/*
7591bab1
MD
2193 * Initialize a data pending command. This means that a consumer is about
2194 * to ask for data pending for each stream it holds. Simply iterate over
2195 * all streams of a session and set the data_pending_check_done flag.
f7079f67
DG
2196 *
2197 * This command returns to the client a LTTNG_OK code.
2198 */
5312a3ed
JG
2199static int relay_begin_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
2200 struct relay_connection *conn,
2201 const struct lttng_buffer_view *payload)
f7079f67
DG
2202{
2203 int ret;
5312a3ed 2204 ssize_t send_ret;
f7079f67
DG
2205 struct lttng_ht_iter iter;
2206 struct lttcomm_relayd_begin_data_pending msg;
2207 struct lttcomm_relayd_generic_reply reply;
2208 struct relay_stream *stream;
f7079f67
DG
2209
2210 assert(recv_hdr);
58eb9381 2211 assert(conn);
f7079f67
DG
2212
2213 DBG("Init streams for data pending");
2214
5312a3ed 2215 if (!conn->session || !conn->version_check_done) {
f7079f67
DG
2216 ERR("Trying to check for data before version check");
2217 ret = -1;
2218 goto end_no_session;
2219 }
2220
5312a3ed
JG
2221 if (payload->size < sizeof(msg)) {
2222 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2223 sizeof(msg), payload->size);
f7079f67
DG
2224 ret = -1;
2225 goto end_no_session;
2226 }
5312a3ed
JG
2227 memcpy(&msg, payload->data, sizeof(msg));
2228 msg.session_id = be64toh(msg.session_id);
f7079f67
DG
2229
2230 /*
7591bab1
MD
2231 * Iterate over all streams to set the begin data pending flag.
2232 * For now, the streams are indexed by stream handle so we have
2233 * to iterate over all streams to find the one associated with
2234 * the right session_id.
f7079f67
DG
2235 */
2236 rcu_read_lock();
d3e2ba59 2237 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2a174661 2238 node.node) {
7591bab1
MD
2239 if (!stream_get(stream)) {
2240 continue;
2241 }
5312a3ed 2242 if (stream->trace->session->id == msg.session_id) {
7591bab1
MD
2243 pthread_mutex_lock(&stream->lock);
2244 stream->data_pending_check_done = false;
2245 pthread_mutex_unlock(&stream->lock);
f7079f67
DG
2246 DBG("Set begin data pending flag to stream %" PRIu64,
2247 stream->stream_handle);
2248 }
7591bab1 2249 stream_put(stream);
f7079f67
DG
2250 }
2251 rcu_read_unlock();
2252
53efb85a 2253 memset(&reply, 0, sizeof(reply));
f7079f67
DG
2254 /* All good, send back reply. */
2255 reply.ret_code = htobe32(LTTNG_OK);
2256
5312a3ed
JG
2257 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2258 if (send_ret < (ssize_t) sizeof(reply)) {
2259 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2260 send_ret);
2261 ret = -1;
2262 } else {
2263 ret = 0;
f7079f67
DG
2264 }
2265
2266end_no_session:
2267 return ret;
2268}
2269
2270/*
7591bab1
MD
2271 * End data pending command. This will check, for a given session id, if
2272 * each stream associated with it has its data_pending_check_done flag
2273 * set. If not, this means that the client lost track of the stream but
2274 * the data is still being streamed on our side. In this case, we inform
2275 * the client that data is in flight.
f7079f67
DG
2276 *
2277 * Return to the client if there is data in flight or not with a ret_code.
2278 */
5312a3ed
JG
2279static int relay_end_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
2280 struct relay_connection *conn,
2281 const struct lttng_buffer_view *payload)
f7079f67
DG
2282{
2283 int ret;
5312a3ed 2284 ssize_t send_ret;
f7079f67
DG
2285 struct lttng_ht_iter iter;
2286 struct lttcomm_relayd_end_data_pending msg;
2287 struct lttcomm_relayd_generic_reply reply;
2288 struct relay_stream *stream;
f7079f67
DG
2289 uint32_t is_data_inflight = 0;
2290
f7079f67
DG
2291 DBG("End data pending command");
2292
5312a3ed 2293 if (!conn->session || !conn->version_check_done) {
f7079f67
DG
2294 ERR("Trying to check for data before version check");
2295 ret = -1;
2296 goto end_no_session;
2297 }
2298
5312a3ed
JG
2299 if (payload->size < sizeof(msg)) {
2300 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2301 sizeof(msg), payload->size);
f7079f67
DG
2302 ret = -1;
2303 goto end_no_session;
2304 }
5312a3ed
JG
2305 memcpy(&msg, payload->data, sizeof(msg));
2306 msg.session_id = be64toh(msg.session_id);
f7079f67 2307
7591bab1
MD
2308 /*
2309 * Iterate over all streams to see if the begin data pending
2310 * flag is set.
2311 */
f7079f67 2312 rcu_read_lock();
d3e2ba59 2313 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2a174661 2314 node.node) {
7591bab1
MD
2315 if (!stream_get(stream)) {
2316 continue;
2317 }
5312a3ed 2318 if (stream->trace->session->id != msg.session_id) {
7591bab1
MD
2319 stream_put(stream);
2320 continue;
2321 }
2322 pthread_mutex_lock(&stream->lock);
2323 if (!stream->data_pending_check_done) {
298a25ca
JG
2324 uint64_t stream_seq;
2325
2326 if (session_streams_have_index(conn->session)) {
2327 /*
2328 * Ensure that both the index and stream data have been
2329 * flushed up to the requested point.
2330 */
a8f9f353 2331 stream_seq = min(stream->prev_data_seq, stream->prev_index_seq);
298a25ca 2332 } else {
a8f9f353 2333 stream_seq = stream->prev_data_seq;
298a25ca
JG
2334 }
2335 if (!stream->closed || !(((int64_t) (stream_seq - stream->last_net_seq_num)) >= 0)) {
7591bab1
MD
2336 is_data_inflight = 1;
2337 DBG("Data is still in flight for stream %" PRIu64,
2338 stream->stream_handle);
2339 pthread_mutex_unlock(&stream->lock);
2340 stream_put(stream);
2341 break;
2342 }
f7079f67 2343 }
7591bab1
MD
2344 pthread_mutex_unlock(&stream->lock);
2345 stream_put(stream);
f7079f67
DG
2346 }
2347 rcu_read_unlock();
2348
53efb85a 2349 memset(&reply, 0, sizeof(reply));
f7079f67
DG
2350 /* All good, send back reply. */
2351 reply.ret_code = htobe32(is_data_inflight);
2352
5312a3ed
JG
2353 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2354 if (send_ret < (ssize_t) sizeof(reply)) {
2355 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2356 send_ret);
2357 ret = -1;
2358 } else {
2359 ret = 0;
f7079f67
DG
2360 }
2361
2362end_no_session:
2363 return ret;
2364}
2365
1c20f0e2
JD
2366/*
2367 * Receive an index for a specific stream.
2368 *
2369 * Return 0 on success else a negative value.
2370 */
5312a3ed
JG
2371static int relay_recv_index(const struct lttcomm_relayd_hdr *recv_hdr,
2372 struct relay_connection *conn,
2373 const struct lttng_buffer_view *payload)
1c20f0e2 2374{
5312a3ed
JG
2375 int ret;
2376 ssize_t send_ret;
58eb9381 2377 struct relay_session *session = conn->session;
1c20f0e2 2378 struct lttcomm_relayd_index index_info;
1c20f0e2
JD
2379 struct lttcomm_relayd_generic_reply reply;
2380 struct relay_stream *stream;
f8f3885c 2381 size_t msg_len;
1c20f0e2 2382
58eb9381 2383 assert(conn);
1c20f0e2
JD
2384
2385 DBG("Relay receiving index");
2386
5312a3ed 2387 if (!session || !conn->version_check_done) {
1c20f0e2
JD
2388 ERR("Trying to close a stream before version check");
2389 ret = -1;
2390 goto end_no_session;
2391 }
2392
f8f3885c
MD
2393 msg_len = lttcomm_relayd_index_len(
2394 lttng_to_index_major(conn->major, conn->minor),
2395 lttng_to_index_minor(conn->major, conn->minor));
5312a3ed
JG
2396 if (payload->size < msg_len) {
2397 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2398 msg_len, payload->size);
1c20f0e2
JD
2399 ret = -1;
2400 goto end_no_session;
2401 }
5312a3ed
JG
2402 memcpy(&index_info, payload->data, msg_len);
2403 index_info.relay_stream_id = be64toh(index_info.relay_stream_id);
2404 index_info.net_seq_num = be64toh(index_info.net_seq_num);
2405 index_info.packet_size = be64toh(index_info.packet_size);
2406 index_info.content_size = be64toh(index_info.content_size);
2407 index_info.timestamp_begin = be64toh(index_info.timestamp_begin);
2408 index_info.timestamp_end = be64toh(index_info.timestamp_end);
2409 index_info.events_discarded = be64toh(index_info.events_discarded);
2410 index_info.stream_id = be64toh(index_info.stream_id);
81df238b
JR
2411
2412 if (conn->minor >= 8) {
2413 index_info.stream_instance_id =
2414 be64toh(index_info.stream_instance_id);
2415 index_info.packet_seq_num = be64toh(index_info.packet_seq_num);
0f83d1cc
MD
2416 } else {
2417 index_info.stream_instance_id = -1ULL;
2418 index_info.packet_seq_num = -1ULL;
81df238b 2419 }
5312a3ed
JG
2420
2421 stream = stream_get_by_id(index_info.relay_stream_id);
1c20f0e2 2422 if (!stream) {
7591bab1 2423 ERR("stream_get_by_id not found");
1c20f0e2 2424 ret = -1;
7591bab1 2425 goto end;
1c20f0e2 2426 }
d3e2ba59 2427
c35f9726
JG
2428 pthread_mutex_lock(&stream->lock);
2429 ret = stream_add_index(stream, &index_info);
2430 pthread_mutex_unlock(&stream->lock);
2431 if (ret) {
7591bab1
MD
2432 goto end_stream_put;
2433 }
1c20f0e2 2434
7591bab1 2435end_stream_put:
7591bab1 2436 stream_put(stream);
7591bab1 2437end:
53efb85a 2438 memset(&reply, 0, sizeof(reply));
1c20f0e2
JD
2439 if (ret < 0) {
2440 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2441 } else {
2442 reply.ret_code = htobe32(LTTNG_OK);
2443 }
58eb9381 2444 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
5312a3ed
JG
2445 if (send_ret < (ssize_t) sizeof(reply)) {
2446 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret);
2447 ret = -1;
1c20f0e2
JD
2448 }
2449
2450end_no_session:
2451 return ret;
2452}
2453
a4baae1b
JD
2454/*
2455 * Receive the streams_sent message.
2456 *
2457 * Return 0 on success else a negative value.
2458 */
5312a3ed
JG
2459static int relay_streams_sent(const struct lttcomm_relayd_hdr *recv_hdr,
2460 struct relay_connection *conn,
2461 const struct lttng_buffer_view *payload)
a4baae1b 2462{
5312a3ed
JG
2463 int ret;
2464 ssize_t send_ret;
a4baae1b
JD
2465 struct lttcomm_relayd_generic_reply reply;
2466
58eb9381 2467 assert(conn);
a4baae1b
JD
2468
2469 DBG("Relay receiving streams_sent");
2470
5312a3ed 2471 if (!conn->session || !conn->version_check_done) {
a4baae1b
JD
2472 ERR("Trying to close a stream before version check");
2473 ret = -1;
2474 goto end_no_session;
2475 }
2476
2477 /*
7591bab1
MD
2478 * Publish every pending stream in the connection recv list which are
2479 * now ready to be used by the viewer.
4a9daf17 2480 */
7591bab1 2481 publish_connection_local_streams(conn);
4a9daf17 2482
53efb85a 2483 memset(&reply, 0, sizeof(reply));
a4baae1b 2484 reply.ret_code = htobe32(LTTNG_OK);
58eb9381 2485 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
5312a3ed
JG
2486 if (send_ret < (ssize_t) sizeof(reply)) {
2487 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2488 send_ret);
2489 ret = -1;
a4baae1b
JD
2490 } else {
2491 /* Success. */
2492 ret = 0;
2493 }
2494
2495end_no_session:
2496 return ret;
2497}
2498
d3ecc550 2499/*
c35f9726
JG
2500 * relay_rotate_session_stream: rotate a stream to a new tracefile for the
2501 * session rotation feature (not the tracefile rotation feature).
d3ecc550 2502 */
c35f9726
JG
2503static int relay_rotate_session_streams(
2504 const struct lttcomm_relayd_hdr *recv_hdr,
5312a3ed
JG
2505 struct relay_connection *conn,
2506 const struct lttng_buffer_view *payload)
d3ecc550 2507{
30b9d5ab 2508 int ret = 0;
c35f9726 2509 uint32_t i;
5312a3ed 2510 ssize_t send_ret;
c35f9726 2511 enum lttng_error_code reply_code = LTTNG_ERR_UNK;
d3ecc550 2512 struct relay_session *session = conn->session;
c35f9726
JG
2513 struct lttcomm_relayd_rotate_streams rotate_streams;
2514 struct lttcomm_relayd_generic_reply reply = {};
2515 struct relay_stream *stream = NULL;
2516 const size_t header_len = sizeof(struct lttcomm_relayd_rotate_streams);
2517 struct lttng_trace_chunk *next_trace_chunk = NULL;
2518 struct lttng_buffer_view stream_positions;
70626904
JG
2519 char chunk_id_buf[MAX_INT_DEC_LEN(uint64_t)];
2520 const char *chunk_id_str = "none";
d3ecc550 2521
d3ecc550
JD
2522 if (!session || !conn->version_check_done) {
2523 ERR("Trying to rotate a stream before version check");
2524 ret = -1;
2525 goto end_no_reply;
2526 }
2527
2528 if (session->major == 2 && session->minor < 11) {
2529 ERR("Unsupported feature before 2.11");
2530 ret = -1;
2531 goto end_no_reply;
2532 }
2533
5312a3ed
JG
2534 if (payload->size < header_len) {
2535 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2536 header_len, payload->size);
d3ecc550
JD
2537 ret = -1;
2538 goto end_no_reply;
2539 }
2540
c35f9726 2541 memcpy(&rotate_streams, payload->data, header_len);
5312a3ed 2542
c35f9726
JG
2543 /* Convert header to host endianness. */
2544 rotate_streams = (typeof(rotate_streams)) {
2545 .stream_count = be32toh(rotate_streams.stream_count),
2546 .new_chunk_id = (typeof(rotate_streams.new_chunk_id)) {
2547 .is_set = !!rotate_streams.new_chunk_id.is_set,
2548 .value = be64toh(rotate_streams.new_chunk_id.value),
2549 }
2550 };
d3ecc550 2551
c35f9726
JG
2552 if (rotate_streams.new_chunk_id.is_set) {
2553 /*
2554 * Retrieve the trace chunk the stream must transition to. As
2555 * per the protocol, this chunk should have been created
2556 * before this command is received.
2557 */
2558 next_trace_chunk = sessiond_trace_chunk_registry_get_chunk(
2559 sessiond_trace_chunk_registry,
2560 session->sessiond_uuid, session->id,
2561 rotate_streams.new_chunk_id.value);
2562 if (!next_trace_chunk) {
c70636a7 2563 char uuid_str[LTTNG_UUID_STR_LEN];
c35f9726
JG
2564
2565 lttng_uuid_to_str(session->sessiond_uuid, uuid_str);
2566 ERR("Unknown next trace chunk in ROTATE_STREAMS command: sessiond_uuid = {%s}, session_id = %" PRIu64
2567 ", trace_chunk_id = %" PRIu64,
2568 uuid_str, session->id,
2569 rotate_streams.new_chunk_id.value);
2570 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2571 ret = -1;
2572 goto end;
2573 }
70626904
JG
2574
2575 ret = snprintf(chunk_id_buf, sizeof(chunk_id_buf), "%" PRIu64,
2576 rotate_streams.new_chunk_id.value);
2577 if (ret < 0 || ret >= sizeof(chunk_id_buf)) {
2578 chunk_id_str = "formatting error";
2579 } else {
2580 chunk_id_str = chunk_id_buf;
2581 }
d3ecc550
JD
2582 }
2583
70626904
JG
2584 DBG("Rotate %" PRIu32 " streams of session \"%s\" to chunk \"%s\"",
2585 rotate_streams.stream_count, session->session_name,
2586 chunk_id_str);
2587
c35f9726
JG
2588 stream_positions = lttng_buffer_view_from_view(payload,
2589 sizeof(rotate_streams), -1);
2590 if (!stream_positions.data ||
2591 stream_positions.size <
2592 (rotate_streams.stream_count *
2593 sizeof(struct lttcomm_relayd_stream_rotation_position))) {
2594 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
d3ecc550 2595 ret = -1;
5312a3ed 2596 goto end;
d3ecc550
JD
2597 }
2598
c35f9726
JG
2599 for (i = 0; i < rotate_streams.stream_count; i++) {
2600 struct lttcomm_relayd_stream_rotation_position *position_comm =
2601 &((typeof(position_comm)) stream_positions.data)[i];
2602 const struct lttcomm_relayd_stream_rotation_position pos = {
2603 .stream_id = be64toh(position_comm->stream_id),
2604 .rotate_at_seq_num = be64toh(
2605 position_comm->rotate_at_seq_num),
2606 };
5312a3ed 2607
c35f9726
JG
2608 stream = stream_get_by_id(pos.stream_id);
2609 if (!stream) {
2610 reply_code = LTTNG_ERR_INVALID;
2611 ret = -1;
2612 goto end;
c6db3843
JG
2613 }
2614
c35f9726
JG
2615 pthread_mutex_lock(&stream->lock);
2616 ret = stream_set_pending_rotation(stream, next_trace_chunk,
2617 pos.rotate_at_seq_num);
2618 pthread_mutex_unlock(&stream->lock);
2619 if (ret) {
2620 reply_code = LTTNG_ERR_FILE_CREATION_ERROR;
2621 goto end;
c6db3843 2622 }
c35f9726
JG
2623
2624 stream_put(stream);
2625 stream = NULL;
d3ecc550
JD
2626 }
2627
c35f9726 2628 reply_code = LTTNG_OK;
eaeb64a9 2629 ret = 0;
d3ecc550 2630end:
c35f9726
JG
2631 if (stream) {
2632 stream_put(stream);
d3ecc550 2633 }
c35f9726
JG
2634
2635 reply.ret_code = htobe32((uint32_t) reply_code);
d3ecc550
JD
2636 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
2637 sizeof(struct lttcomm_relayd_generic_reply), 0);
5312a3ed
JG
2638 if (send_ret < (ssize_t) sizeof(reply)) {
2639 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2640 send_ret);
2641 ret = -1;
d3ecc550 2642 }
d3ecc550 2643end_no_reply:
c35f9726 2644 lttng_trace_chunk_put(next_trace_chunk);
d3ecc550
JD
2645 return ret;
2646}
2647
e5add6d0 2648
e5add6d0
JG
2649
2650/*
2651 * relay_create_trace_chunk: create a new trace chunk
2652 */
2653static int relay_create_trace_chunk(const struct lttcomm_relayd_hdr *recv_hdr,
2654 struct relay_connection *conn,
2655 const struct lttng_buffer_view *payload)
2656{
2657 int ret = 0;
2658 ssize_t send_ret;
2659 struct relay_session *session = conn->session;
2660 struct lttcomm_relayd_create_trace_chunk *msg;
2661 struct lttcomm_relayd_generic_reply reply = {};
2662 struct lttng_buffer_view header_view;
2663 struct lttng_buffer_view chunk_name_view;
2664 struct lttng_trace_chunk *chunk = NULL, *published_chunk = NULL;
2665 enum lttng_error_code reply_code = LTTNG_OK;
2666 enum lttng_trace_chunk_status chunk_status;
a7ceb342 2667 const char *new_path;
e5add6d0
JG
2668
2669 if (!session || !conn->version_check_done) {
2670 ERR("Trying to create a trace chunk before version check");
2671 ret = -1;
2672 goto end_no_reply;
2673 }
2674
2675 if (session->major == 2 && session->minor < 11) {
2676 ERR("Chunk creation command is unsupported before 2.11");
2677 ret = -1;
2678 goto end_no_reply;
2679 }
2680
2681 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
2682 if (!header_view.data) {
2683 ERR("Failed to receive payload of chunk creation command");
2684 ret = -1;
2685 goto end_no_reply;
2686 }
2687
2688 /* Convert to host endianness. */
2689 msg = (typeof(msg)) header_view.data;
2690 msg->chunk_id = be64toh(msg->chunk_id);
2691 msg->creation_timestamp = be64toh(msg->creation_timestamp);
2692 msg->override_name_length = be32toh(msg->override_name_length);
2693
a7ceb342
MD
2694 if (session->current_trace_chunk &&
2695 !lttng_trace_chunk_get_name_overridden(session->current_trace_chunk)) {
2696 chunk_status = lttng_trace_chunk_rename_path(session->current_trace_chunk,
2697 DEFAULT_CHUNK_TMP_OLD_DIRECTORY);
2698 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2699 ERR("Failed to rename old chunk");
2700 ret = -1;
2701 reply_code = LTTNG_ERR_UNK;
2702 goto end;
2703 }
2704 }
2705 session->ongoing_rotation = true;
2706 if (!session->current_trace_chunk) {
2707 if (!session->has_rotated) {
2708 new_path = "";
2709 } else {
2710 new_path = NULL;
2711 }
2712 } else {
2713 new_path = DEFAULT_CHUNK_TMP_NEW_DIRECTORY;
2714 }
e5add6d0 2715 chunk = lttng_trace_chunk_create(
a7ceb342 2716 msg->chunk_id, msg->creation_timestamp, new_path);
e5add6d0
JG
2717 if (!chunk) {
2718 ERR("Failed to create trace chunk in trace chunk creation command");
2719 ret = -1;
2720 reply_code = LTTNG_ERR_NOMEM;
2721 goto end;
2722 }
7145f5e9 2723 lttng_trace_chunk_set_fd_tracker(chunk, the_fd_tracker);
e5add6d0
JG
2724
2725 if (msg->override_name_length) {
2726 const char *name;
2727
2728 chunk_name_view = lttng_buffer_view_from_view(payload,
2729 sizeof(*msg),
2730 msg->override_name_length);
2731 name = chunk_name_view.data;
2732 if (!name || name[msg->override_name_length - 1]) {
2733 ERR("Failed to receive payload of chunk creation command");
2734 ret = -1;
2735 reply_code = LTTNG_ERR_INVALID;
2736 goto end;
2737 }
2738
2739 chunk_status = lttng_trace_chunk_override_name(
2740 chunk, chunk_name_view.data);
2741 switch (chunk_status) {
2742 case LTTNG_TRACE_CHUNK_STATUS_OK:
2743 break;
2744 case LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT:
2745 ERR("Failed to set the name of new trace chunk in trace chunk creation command (invalid name)");
2746 reply_code = LTTNG_ERR_INVALID;
2747 ret = -1;
2748 goto end;
2749 default:
2750 ERR("Failed to set the name of new trace chunk in trace chunk creation command (unknown error)");
2751 reply_code = LTTNG_ERR_UNK;
2752 ret = -1;
2753 goto end;
2754 }
2755 }
2756
e5add6d0
JG
2757 chunk_status = lttng_trace_chunk_set_credentials_current_user(chunk);
2758 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2759 reply_code = LTTNG_ERR_UNK;
2760 ret = -1;
2761 goto end;
2762 }
2763
7ceefac4
JG
2764 assert(conn->session->output_directory);
2765 chunk_status = lttng_trace_chunk_set_as_owner(chunk,
2766 conn->session->output_directory);
e5add6d0
JG
2767 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2768 reply_code = LTTNG_ERR_UNK;
2769 ret = -1;
2770 goto end;
2771 }
2772
2773 published_chunk = sessiond_trace_chunk_registry_publish_chunk(
2774 sessiond_trace_chunk_registry,
2775 conn->session->sessiond_uuid,
2776 conn->session->id,
2777 chunk);
2778 if (!published_chunk) {
c70636a7 2779 char uuid_str[LTTNG_UUID_STR_LEN];
e5add6d0
JG
2780
2781 lttng_uuid_to_str(conn->session->sessiond_uuid, uuid_str);
2782 ERR("Failed to publish chunk: sessiond_uuid = %s, session_id = %" PRIu64 ", chunk_id = %" PRIu64,
2783 uuid_str,
2784 conn->session->id,
2785 msg->chunk_id);
2786 ret = -1;
2787 reply_code = LTTNG_ERR_NOMEM;
2788 goto end;
2789 }
2790
2791 pthread_mutex_lock(&conn->session->lock);
62bad3bf
JG
2792 if (conn->session->pending_closure_trace_chunk) {
2793 /*
2794 * Invalid; this means a second create_trace_chunk command was
2795 * received before a close_trace_chunk.
2796 */
2797 ERR("Invalid trace chunk close command received; a trace chunk is already waiting for a trace chunk close command");
2798 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2799 ret = -1;
2800 goto end_unlock_session;
2801 }
2802 conn->session->pending_closure_trace_chunk =
2803 conn->session->current_trace_chunk;
e5add6d0 2804 conn->session->current_trace_chunk = published_chunk;
e5add6d0 2805 published_chunk = NULL;
a7ceb342
MD
2806 if (!conn->session->pending_closure_trace_chunk) {
2807 session->ongoing_rotation = false;
2808 }
62bad3bf 2809end_unlock_session:
c35f9726 2810 pthread_mutex_unlock(&conn->session->lock);
e5add6d0
JG
2811end:
2812 reply.ret_code = htobe32((uint32_t) reply_code);
2813 send_ret = conn->sock->ops->sendmsg(conn->sock,
2814 &reply,
2815 sizeof(struct lttcomm_relayd_generic_reply),
2816 0);
2817 if (send_ret < (ssize_t) sizeof(reply)) {
2818 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
2819 send_ret);
2820 ret = -1;
2821 }
2822end_no_reply:
2823 lttng_trace_chunk_put(chunk);
2824 lttng_trace_chunk_put(published_chunk);
e5add6d0
JG
2825 return ret;
2826}
2827
bbc4768c
JG
2828/*
2829 * relay_close_trace_chunk: close a trace chunk
2830 */
2831static int relay_close_trace_chunk(const struct lttcomm_relayd_hdr *recv_hdr,
2832 struct relay_connection *conn,
2833 const struct lttng_buffer_view *payload)
2834{
9898f786 2835 int ret = 0, buf_ret;
bbc4768c
JG
2836 ssize_t send_ret;
2837 struct relay_session *session = conn->session;
2838 struct lttcomm_relayd_close_trace_chunk *msg;
ecd1a12f 2839 struct lttcomm_relayd_close_trace_chunk_reply reply = {};
bbc4768c
JG
2840 struct lttng_buffer_view header_view;
2841 struct lttng_trace_chunk *chunk = NULL;
2842 enum lttng_error_code reply_code = LTTNG_OK;
2843 enum lttng_trace_chunk_status chunk_status;
2844 uint64_t chunk_id;
c35f9726 2845 LTTNG_OPTIONAL(enum lttng_trace_chunk_command_type) close_command = {};
bbc4768c 2846 time_t close_timestamp;
ecd1a12f
MD
2847 char closed_trace_chunk_path[LTTNG_PATH_MAX];
2848 size_t path_length = 0;
2849 const char *chunk_name = NULL;
2850 struct lttng_dynamic_buffer reply_payload;
a7ceb342 2851 const char *new_path;
ecd1a12f
MD
2852
2853 lttng_dynamic_buffer_init(&reply_payload);
bbc4768c
JG
2854
2855 if (!session || !conn->version_check_done) {
2856 ERR("Trying to close a trace chunk before version check");
2857 ret = -1;
2858 goto end_no_reply;
2859 }
2860
2861 if (session->major == 2 && session->minor < 11) {
2862 ERR("Chunk close command is unsupported before 2.11");
2863 ret = -1;
2864 goto end_no_reply;
2865 }
2866
2867 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
2868 if (!header_view.data) {
2869 ERR("Failed to receive payload of chunk close command");
2870 ret = -1;
2871 goto end_no_reply;
2872 }
2873
2874 /* Convert to host endianness. */
2875 msg = (typeof(msg)) header_view.data;
2876 chunk_id = be64toh(msg->chunk_id);
2877 close_timestamp = (time_t) be64toh(msg->close_timestamp);
2878 close_command = (typeof(close_command)){
2879 .value = be32toh(msg->close_command.value),
2880 .is_set = msg->close_command.is_set,
2881 };
2882
2883 chunk = sessiond_trace_chunk_registry_get_chunk(
2884 sessiond_trace_chunk_registry,
2885 conn->session->sessiond_uuid,
2886 conn->session->id,
2887 chunk_id);
2888 if (!chunk) {
c70636a7 2889 char uuid_str[LTTNG_UUID_STR_LEN];
bbc4768c
JG
2890
2891 lttng_uuid_to_str(conn->session->sessiond_uuid, uuid_str);
2892 ERR("Failed to find chunk to close: sessiond_uuid = %s, session_id = %" PRIu64 ", chunk_id = %" PRIu64,
2893 uuid_str,
2894 conn->session->id,
2895 msg->chunk_id);
2896 ret = -1;
2897 reply_code = LTTNG_ERR_NOMEM;
2898 goto end;
2899 }
2900
62bad3bf 2901 pthread_mutex_lock(&session->lock);
f77a6ec2
MD
2902 if (close_command.is_set &&
2903 close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE) {
2904 /*
2905 * Clear command. It is a protocol error to ask for a
2906 * clear on a relay which does not allow it. Querying
2907 * the configuration allows figuring out whether
2908 * clearing is allowed before doing the clear.
2909 */
2910 if (!opt_allow_clear) {
2911 ret = -1;
2912 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2913 goto end_unlock_session;
2914 }
2915 }
62bad3bf
JG
2916 if (session->pending_closure_trace_chunk &&
2917 session->pending_closure_trace_chunk != chunk) {
2918 ERR("Trace chunk close command for session \"%s\" does not target the trace chunk pending closure",
2919 session->session_name);
2920 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2921 ret = -1;
2922 goto end_unlock_session;
2923 }
2924
a7ceb342
MD
2925 if (session->current_trace_chunk && session->current_trace_chunk != chunk &&
2926 !lttng_trace_chunk_get_name_overridden(session->current_trace_chunk)) {
2927 if (close_command.is_set &&
2928 close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE &&
2929 !session->has_rotated) {
2930 /* New chunk stays in session output directory. */
2931 new_path = "";
2932 } else {
2933 /* Use chunk name for new chunk. */
2934 new_path = NULL;
2935 }
2936 /* Rename new chunk path. */
2937 chunk_status = lttng_trace_chunk_rename_path(session->current_trace_chunk,
2938 new_path);
2939 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2940 ret = -1;
88188199 2941 goto end_unlock_session;
a7ceb342
MD
2942 }
2943 session->ongoing_rotation = false;
2944 }
2945 if ((!close_command.is_set ||
2946 close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION) &&
2947 !lttng_trace_chunk_get_name_overridden(chunk)) {
2948 const char *old_path;
2949
2950 if (!session->has_rotated) {
2951 old_path = "";
2952 } else {
2953 old_path = NULL;
2954 }
2955 /* We need to move back the .tmp_old_chunk to its rightful place. */
2956 chunk_status = lttng_trace_chunk_rename_path(chunk, old_path);
2957 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2958 ret = -1;
88188199 2959 goto end_unlock_session;
a7ceb342
MD
2960 }
2961 }
bbc4768c
JG
2962 chunk_status = lttng_trace_chunk_set_close_timestamp(
2963 chunk, close_timestamp);
2964 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2965 ERR("Failed to set trace chunk close timestamp");
2966 ret = -1;
2967 reply_code = LTTNG_ERR_UNK;
62bad3bf 2968 goto end_unlock_session;
bbc4768c
JG
2969 }
2970
2971 if (close_command.is_set) {
2972 chunk_status = lttng_trace_chunk_set_close_command(
2973 chunk, close_command.value);
2974 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2975 ret = -1;
2976 reply_code = LTTNG_ERR_INVALID;
62bad3bf 2977 goto end_unlock_session;
bbc4768c
JG
2978 }
2979 }
ecd1a12f
MD
2980 chunk_status = lttng_trace_chunk_get_name(chunk, &chunk_name, NULL);
2981 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2982 ERR("Failed to get chunk name");
2983 ret = -1;
2984 reply_code = LTTNG_ERR_UNK;
2985 goto end_unlock_session;
2986 }
2987 if (!session->has_rotated && !session->snapshot) {
2988 ret = lttng_strncpy(closed_trace_chunk_path,
2989 session->output_path,
2990 sizeof(closed_trace_chunk_path));
2991 if (ret) {
2992 ERR("Failed to send trace chunk path: path length of %zu bytes exceeds the maximal allowed length of %zu bytes",
2993 strlen(session->output_path),
2994 sizeof(closed_trace_chunk_path));
2995 reply_code = LTTNG_ERR_NOMEM;
2996 ret = -1;
2997 goto end_unlock_session;
2998 }
2999 } else {
3000 if (session->snapshot) {
3001 ret = snprintf(closed_trace_chunk_path,
3002 sizeof(closed_trace_chunk_path),
3003 "%s/%s", session->output_path,
3004 chunk_name);
3005 } else {
3006 ret = snprintf(closed_trace_chunk_path,
3007 sizeof(closed_trace_chunk_path),
3008 "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY
3009 "/%s",
3010 session->output_path, chunk_name);
3011 }
3012 if (ret < 0 || ret == sizeof(closed_trace_chunk_path)) {
3013 ERR("Failed to format closed trace chunk resulting path");
3014 reply_code = ret < 0 ? LTTNG_ERR_UNK : LTTNG_ERR_NOMEM;
3015 ret = -1;
3016 goto end_unlock_session;
3017 }
3018 }
489ea154
MD
3019 if (close_command.is_set &&
3020 close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED) {
3021 session->has_rotated = true;
3022 }
ecd1a12f
MD
3023 DBG("Reply chunk path on close: %s", closed_trace_chunk_path);
3024 path_length = strlen(closed_trace_chunk_path) + 1;
3025 if (path_length > UINT32_MAX) {
3026 ERR("Closed trace chunk path exceeds the maximal length allowed by the protocol");
3027 ret = -1;
3028 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
3029 goto end_unlock_session;
3030 }
bbc4768c 3031
c35f9726
JG
3032 if (session->current_trace_chunk == chunk) {
3033 /*
3034 * After a trace chunk close command, no new streams
3035 * referencing the chunk may be created. Hence, on the
3036 * event that no new trace chunk have been created for
3037 * the session, the reference to the current trace chunk
3038 * is released in order to allow it to be reclaimed when
3039 * the last stream releases its reference to it.
3040 */
3041 lttng_trace_chunk_put(session->current_trace_chunk);
3042 session->current_trace_chunk = NULL;
3043 }
62bad3bf
JG
3044 lttng_trace_chunk_put(session->pending_closure_trace_chunk);
3045 session->pending_closure_trace_chunk = NULL;
3046end_unlock_session:
c35f9726
JG
3047 pthread_mutex_unlock(&session->lock);
3048
bbc4768c 3049end:
ecd1a12f
MD
3050 reply.generic.ret_code = htobe32((uint32_t) reply_code);
3051 reply.path_length = htobe32((uint32_t) path_length);
9898f786 3052 buf_ret = lttng_dynamic_buffer_append(
ecd1a12f 3053 &reply_payload, &reply, sizeof(reply));
9898f786 3054 if (buf_ret) {
ecd1a12f
MD
3055 ERR("Failed to append \"close trace chunk\" command reply header to payload buffer");
3056 goto end_no_reply;
3057 }
3058
3059 if (reply_code == LTTNG_OK) {
9898f786 3060 buf_ret = lttng_dynamic_buffer_append(&reply_payload,
ecd1a12f 3061 closed_trace_chunk_path, path_length);
9898f786 3062 if (buf_ret) {
ecd1a12f
MD
3063 ERR("Failed to append \"close trace chunk\" command reply path to payload buffer");
3064 goto end_no_reply;
3065 }
3066 }
3067
bbc4768c 3068 send_ret = conn->sock->ops->sendmsg(conn->sock,
ecd1a12f
MD
3069 reply_payload.data,
3070 reply_payload.size,
bbc4768c 3071 0);
ecd1a12f
MD
3072 if (send_ret < reply_payload.size) {
3073 ERR("Failed to send \"close trace chunk\" command reply of %zu bytes (ret = %zd)",
3074 reply_payload.size, send_ret);
bbc4768c 3075 ret = -1;
ecd1a12f 3076 goto end_no_reply;
bbc4768c
JG
3077 }
3078end_no_reply:
3079 lttng_trace_chunk_put(chunk);
ecd1a12f 3080 lttng_dynamic_buffer_reset(&reply_payload);
bbc4768c
JG
3081 return ret;
3082}
3083
c35f9726
JG
3084/*
3085 * relay_trace_chunk_exists: check if a trace chunk exists
3086 */
3087static int relay_trace_chunk_exists(const struct lttcomm_relayd_hdr *recv_hdr,
3088 struct relay_connection *conn,
3089 const struct lttng_buffer_view *payload)
3090{
3091 int ret = 0;
3092 ssize_t send_ret;
3093 struct relay_session *session = conn->session;
3094 struct lttcomm_relayd_trace_chunk_exists *msg;
3095 struct lttcomm_relayd_trace_chunk_exists_reply reply = {};
3096 struct lttng_buffer_view header_view;
c35f9726 3097 uint64_t chunk_id;
6b584c2e 3098 bool chunk_exists;
c35f9726
JG
3099
3100 if (!session || !conn->version_check_done) {
3101 ERR("Trying to close a trace chunk before version check");
3102 ret = -1;
3103 goto end_no_reply;
3104 }
3105
3106 if (session->major == 2 && session->minor < 11) {
3107 ERR("Chunk close command is unsupported before 2.11");
3108 ret = -1;
3109 goto end_no_reply;
3110 }
3111
3112 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
3113 if (!header_view.data) {
3114 ERR("Failed to receive payload of chunk close command");
3115 ret = -1;
3116 goto end_no_reply;
3117 }
3118
3119 /* Convert to host endianness. */
3120 msg = (typeof(msg)) header_view.data;
3121 chunk_id = be64toh(msg->chunk_id);
3122
6b584c2e 3123 ret = sessiond_trace_chunk_registry_chunk_exists(
c35f9726
JG
3124 sessiond_trace_chunk_registry,
3125 conn->session->sessiond_uuid,
3126 conn->session->id,
6b584c2e
JG
3127 chunk_id, &chunk_exists);
3128 /*
3129 * If ret is not 0, send the reply and report the error to the caller.
3130 * It is a protocol (or internal) error and the session/connection
3131 * should be torn down.
3132 */
3133 reply = (typeof(reply)){
3134 .generic.ret_code = htobe32((uint32_t)
3135 (ret == 0 ? LTTNG_OK : LTTNG_ERR_INVALID_PROTOCOL)),
3136 .trace_chunk_exists = ret == 0 ? chunk_exists : 0,
c35f9726 3137 };
6b584c2e
JG
3138 send_ret = conn->sock->ops->sendmsg(
3139 conn->sock, &reply, sizeof(reply), 0);
c35f9726
JG
3140 if (send_ret < (ssize_t) sizeof(reply)) {
3141 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
3142 send_ret);
3143 ret = -1;
3144 }
3145end_no_reply:
c35f9726
JG
3146 return ret;
3147}
3148
8614e600
MD
3149/*
3150 * relay_get_configuration: query whether feature is available
3151 */
3152static int relay_get_configuration(const struct lttcomm_relayd_hdr *recv_hdr,
3153 struct relay_connection *conn,
3154 const struct lttng_buffer_view *payload)
3155{
3156 int ret = 0;
3157 ssize_t send_ret;
3158 struct lttcomm_relayd_get_configuration *msg;
3159 struct lttcomm_relayd_get_configuration_reply reply = {};
3160 struct lttng_buffer_view header_view;
3161 uint64_t query_flags = 0;
3162 uint64_t result_flags = 0;
3163
3164 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
3165 if (!header_view.data) {
3166 ERR("Failed to receive payload of chunk close command");
3167 ret = -1;
3168 goto end_no_reply;
3169 }
3170
3171 /* Convert to host endianness. */
3172 msg = (typeof(msg)) header_view.data;
3173 query_flags = be64toh(msg->query_flags);
3174
3175 if (query_flags) {
3176 ret = LTTNG_ERR_INVALID_PROTOCOL;
3177 goto reply;
3178 }
3179 if (opt_allow_clear) {
3180 result_flags |= LTTCOMM_RELAYD_CONFIGURATION_FLAG_CLEAR_ALLOWED;
3181 }
3182 ret = 0;
3183reply:
3184 reply = (typeof(reply)){
3185 .generic.ret_code = htobe32((uint32_t)
3186 (ret == 0 ? LTTNG_OK : LTTNG_ERR_INVALID_PROTOCOL)),
3187 .relayd_configuration_flags = htobe64(result_flags),
3188 };
3189 send_ret = conn->sock->ops->sendmsg(
3190 conn->sock, &reply, sizeof(reply), 0);
3191 if (send_ret < (ssize_t) sizeof(reply)) {
3192 ERR("Failed to send \"get configuration\" command reply (ret = %zd)",
3193 send_ret);
3194 ret = -1;
3195 }
3196end_no_reply:
3197 return ret;
3198}
3199
5312a3ed
JG
3200#define DBG_CMD(cmd_name, conn) \
3201 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
3202
3203static int relay_process_control_command(struct relay_connection *conn,
3204 const struct lttcomm_relayd_hdr *header,
3205 const struct lttng_buffer_view *payload)
b8aa1682
JD
3206{
3207 int ret = 0;
3208
5312a3ed 3209 switch (header->cmd) {
b8aa1682 3210 case RELAYD_CREATE_SESSION:
5312a3ed
JG
3211 DBG_CMD("RELAYD_CREATE_SESSION", conn);
3212 ret = relay_create_session(header, conn, payload);
b8aa1682 3213 break;
b8aa1682 3214 case RELAYD_ADD_STREAM:
5312a3ed
JG
3215 DBG_CMD("RELAYD_ADD_STREAM", conn);
3216 ret = relay_add_stream(header, conn, payload);
b8aa1682
JD
3217 break;
3218 case RELAYD_START_DATA:
5312a3ed
JG
3219 DBG_CMD("RELAYD_START_DATA", conn);
3220 ret = relay_start(header, conn, payload);
b8aa1682
JD
3221 break;
3222 case RELAYD_SEND_METADATA:
5312a3ed
JG
3223 DBG_CMD("RELAYD_SEND_METADATA", conn);
3224 ret = relay_recv_metadata(header, conn, payload);
b8aa1682
JD
3225 break;
3226 case RELAYD_VERSION:
5312a3ed
JG
3227 DBG_CMD("RELAYD_VERSION", conn);
3228 ret = relay_send_version(header, conn, payload);
b8aa1682 3229 break;
173af62f 3230 case RELAYD_CLOSE_STREAM:
5312a3ed
JG
3231 DBG_CMD("RELAYD_CLOSE_STREAM", conn);
3232 ret = relay_close_stream(header, conn, payload);
173af62f 3233 break;
6d805429 3234 case RELAYD_DATA_PENDING:
5312a3ed
JG
3235 DBG_CMD("RELAYD_DATA_PENDING", conn);
3236 ret = relay_data_pending(header, conn, payload);
c8f59ee5
DG
3237 break;
3238 case RELAYD_QUIESCENT_CONTROL:
5312a3ed
JG
3239 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn);
3240 ret = relay_quiescent_control(header, conn, payload);
c8f59ee5 3241 break;
f7079f67 3242 case RELAYD_BEGIN_DATA_PENDING:
5312a3ed
JG
3243 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn);
3244 ret = relay_begin_data_pending(header, conn, payload);
f7079f67
DG
3245 break;
3246 case RELAYD_END_DATA_PENDING:
5312a3ed
JG
3247 DBG_CMD("RELAYD_END_DATA_PENDING", conn);
3248 ret = relay_end_data_pending(header, conn, payload);
f7079f67 3249 break;
1c20f0e2 3250 case RELAYD_SEND_INDEX:
5312a3ed
JG
3251 DBG_CMD("RELAYD_SEND_INDEX", conn);
3252 ret = relay_recv_index(header, conn, payload);
1c20f0e2 3253 break;
a4baae1b 3254 case RELAYD_STREAMS_SENT:
5312a3ed
JG
3255 DBG_CMD("RELAYD_STREAMS_SENT", conn);
3256 ret = relay_streams_sent(header, conn, payload);
a4baae1b 3257 break;
93ec662e 3258 case RELAYD_RESET_METADATA:
5312a3ed
JG
3259 DBG_CMD("RELAYD_RESET_METADATA", conn);
3260 ret = relay_reset_metadata(header, conn, payload);
93ec662e 3261 break;
c35f9726
JG
3262 case RELAYD_ROTATE_STREAMS:
3263 DBG_CMD("RELAYD_ROTATE_STREAMS", conn);
3264 ret = relay_rotate_session_streams(header, conn, payload);
d3ecc550 3265 break;
e5add6d0
JG
3266 case RELAYD_CREATE_TRACE_CHUNK:
3267 DBG_CMD("RELAYD_CREATE_TRACE_CHUNK", conn);
3268 ret = relay_create_trace_chunk(header, conn, payload);
3269 break;
bbc4768c
JG
3270 case RELAYD_CLOSE_TRACE_CHUNK:
3271 DBG_CMD("RELAYD_CLOSE_TRACE_CHUNK", conn);
3272 ret = relay_close_trace_chunk(header, conn, payload);
3273 break;
c35f9726
JG
3274 case RELAYD_TRACE_CHUNK_EXISTS:
3275 DBG_CMD("RELAYD_TRACE_CHUNK_EXISTS", conn);
3276 ret = relay_trace_chunk_exists(header, conn, payload);
3277 break;
8614e600
MD
3278 case RELAYD_GET_CONFIGURATION:
3279 DBG_CMD("RELAYD_GET_CONFIGURATION", conn);
3280 ret = relay_get_configuration(header, conn, payload);
3281 break;
b8aa1682
JD
3282 case RELAYD_UPDATE_SYNC_INFO:
3283 default:
5312a3ed 3284 ERR("Received unknown command (%u)", header->cmd);
58eb9381 3285 relay_unknown_command(conn);
b8aa1682
JD
3286 ret = -1;
3287 goto end;
3288 }
3289
3290end:
3291 return ret;
3292}
3293
5569b118
JG
3294static enum relay_connection_status relay_process_control_receive_payload(
3295 struct relay_connection *conn)
5312a3ed
JG
3296{
3297 int ret = 0;
5569b118 3298 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
5312a3ed
JG
3299 struct lttng_dynamic_buffer *reception_buffer =
3300 &conn->protocol.ctrl.reception_buffer;
3301 struct ctrl_connection_state_receive_payload *state =
3302 &conn->protocol.ctrl.state.receive_payload;
3303 struct lttng_buffer_view payload_view;
3304
3305 if (state->left_to_receive == 0) {
3306 /* Short-circuit for payload-less commands. */
3307 goto reception_complete;
3308 }
3309
3310 ret = conn->sock->ops->recvmsg(conn->sock,
3311 reception_buffer->data + state->received,
3312 state->left_to_receive, MSG_DONTWAIT);
3313 if (ret < 0) {
5569b118
JG
3314 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3315 PERROR("Unable to receive command payload on sock %d",
3316 conn->sock->fd);
3317 status = RELAY_CONNECTION_STATUS_ERROR;
3318 }
5312a3ed
JG
3319 goto end;
3320 } else if (ret == 0) {
3321 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
5569b118 3322 status = RELAY_CONNECTION_STATUS_CLOSED;
5312a3ed
JG
3323 goto end;
3324 }
3325
3326 assert(ret > 0);
3327 assert(ret <= state->left_to_receive);
3328
3329 state->left_to_receive -= ret;
3330 state->received += ret;
3331
3332 if (state->left_to_receive > 0) {
3333 /*
3334 * Can't transition to the protocol's next state, wait to
3335 * receive the rest of the header.
3336 */
3337 DBG3("Partial reception of control connection protocol payload (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
3338 state->received, state->left_to_receive,
3339 conn->sock->fd);
5312a3ed
JG
3340 goto end;
3341 }
3342
3343reception_complete:
3344 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64 " bytes",
3345 conn->sock->fd, state->received);
3346 /*
3347 * The payload required to process the command has been received.
3348 * A view to the reception buffer is forwarded to the various
3349 * commands and the state of the control is reset on success.
3350 *
3351 * Commands are responsible for sending their reply to the peer.
3352 */
3353 payload_view = lttng_buffer_view_from_dynamic_buffer(reception_buffer,
3354 0, -1);
3355 ret = relay_process_control_command(conn,
3356 &state->header, &payload_view);
3357 if (ret < 0) {
5569b118 3358 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed
JG
3359 goto end;
3360 }
3361
3362 ret = connection_reset_protocol_state(conn);
5569b118
JG
3363 if (ret) {
3364 status = RELAY_CONNECTION_STATUS_ERROR;
3365 }
5312a3ed 3366end:
5569b118 3367 return status;
5312a3ed
JG
3368}
3369
5569b118
JG
3370static enum relay_connection_status relay_process_control_receive_header(
3371 struct relay_connection *conn)
5312a3ed
JG
3372{
3373 int ret = 0;
5569b118 3374 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
5312a3ed
JG
3375 struct lttcomm_relayd_hdr header;
3376 struct lttng_dynamic_buffer *reception_buffer =
3377 &conn->protocol.ctrl.reception_buffer;
3378 struct ctrl_connection_state_receive_header *state =
3379 &conn->protocol.ctrl.state.receive_header;
3380
3381 assert(state->left_to_receive != 0);
3382
3383 ret = conn->sock->ops->recvmsg(conn->sock,
3384 reception_buffer->data + state->received,
3385 state->left_to_receive, MSG_DONTWAIT);
3386 if (ret < 0) {
5569b118
JG
3387 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3388 PERROR("Unable to receive control command header on sock %d",
3389 conn->sock->fd);
3390 status = RELAY_CONNECTION_STATUS_ERROR;
3391 }
5312a3ed
JG
3392 goto end;
3393 } else if (ret == 0) {
3394 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
5569b118 3395 status = RELAY_CONNECTION_STATUS_CLOSED;
5312a3ed
JG
3396 goto end;
3397 }
3398
3399 assert(ret > 0);
3400 assert(ret <= state->left_to_receive);
3401
3402 state->left_to_receive -= ret;
3403 state->received += ret;
3404
3405 if (state->left_to_receive > 0) {
3406 /*
3407 * Can't transition to the protocol's next state, wait to
3408 * receive the rest of the header.
3409 */
3410 DBG3("Partial reception of control connection protocol header (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
3411 state->received, state->left_to_receive,
3412 conn->sock->fd);
5312a3ed
JG
3413 goto end;
3414 }
3415
3416 /* Transition to next state: receiving the command's payload. */
3417 conn->protocol.ctrl.state_id =
3418 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD;
3419 memcpy(&header, reception_buffer->data, sizeof(header));
3420 header.circuit_id = be64toh(header.circuit_id);
3421 header.data_size = be64toh(header.data_size);
3422 header.cmd = be32toh(header.cmd);
3423 header.cmd_version = be32toh(header.cmd_version);
3424 memcpy(&conn->protocol.ctrl.state.receive_payload.header,
3425 &header, sizeof(header));
3426
3427 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32 ", cmd_version = %" PRIu32 ", payload size = %" PRIu64 " bytes",
3428 conn->sock->fd, header.cmd, header.cmd_version,
3429 header.data_size);
3430
715e6fb1 3431 if (header.data_size > DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE) {
5312a3ed
JG
3432 ERR("Command header indicates a payload (%" PRIu64 " bytes) that exceeds the maximal payload size allowed on a control connection.",
3433 header.data_size);
5569b118 3434 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed
JG
3435 goto end;
3436 }
3437
3438 conn->protocol.ctrl.state.receive_payload.left_to_receive =
3439 header.data_size;
3440 conn->protocol.ctrl.state.receive_payload.received = 0;
3441 ret = lttng_dynamic_buffer_set_size(reception_buffer,
3442 header.data_size);
3443 if (ret) {
5569b118 3444 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed
JG
3445 goto end;
3446 }
3447
3448 if (header.data_size == 0) {
3449 /*
3450 * Manually invoke the next state as the poll loop
3451 * will not wake-up to allow us to proceed further.
3452 */
5569b118 3453 status = relay_process_control_receive_payload(conn);
5312a3ed
JG
3454 }
3455end:
5569b118 3456 return status;
5312a3ed
JG
3457}
3458
3459/*
3460 * Process the commands received on the control socket
3461 */
5569b118
JG
3462static enum relay_connection_status relay_process_control(
3463 struct relay_connection *conn)
5312a3ed 3464{
5569b118 3465 enum relay_connection_status status;
5312a3ed
JG
3466
3467 switch (conn->protocol.ctrl.state_id) {
3468 case CTRL_CONNECTION_STATE_RECEIVE_HEADER:
5569b118 3469 status = relay_process_control_receive_header(conn);
5312a3ed
JG
3470 break;
3471 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD:
5569b118 3472 status = relay_process_control_receive_payload(conn);
5312a3ed
JG
3473 break;
3474 default:
3475 ERR("Unknown control connection protocol state encountered.");
3476 abort();
3477 }
3478
5569b118 3479 return status;
5312a3ed
JG
3480}
3481
5569b118
JG
3482static enum relay_connection_status relay_process_data_receive_header(
3483 struct relay_connection *conn)
b8aa1682 3484{
5312a3ed 3485 int ret;
5569b118 3486 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
5312a3ed
JG
3487 struct data_connection_state_receive_header *state =
3488 &conn->protocol.data.state.receive_header;
3489 struct lttcomm_relayd_data_hdr header;
b8aa1682 3490 struct relay_stream *stream;
5312a3ed
JG
3491
3492 assert(state->left_to_receive != 0);
3493
3494 ret = conn->sock->ops->recvmsg(conn->sock,
3495 state->header_reception_buffer + state->received,
3496 state->left_to_receive, MSG_DONTWAIT);
3497 if (ret < 0) {
5569b118
JG
3498 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3499 PERROR("Unable to receive data header on sock %d", conn->sock->fd);
3500 status = RELAY_CONNECTION_STATUS_ERROR;
3501 }
5312a3ed
JG
3502 goto end;
3503 } else if (ret == 0) {
3504 /* Orderly shutdown. Not necessary to print an error. */
3505 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
5569b118 3506 status = RELAY_CONNECTION_STATUS_CLOSED;
b8aa1682
JD
3507 goto end;
3508 }
3509
5312a3ed
JG
3510 assert(ret > 0);
3511 assert(ret <= state->left_to_receive);
3512
3513 state->left_to_receive -= ret;
3514 state->received += ret;
3515
3516 if (state->left_to_receive > 0) {
3517 /*
3518 * Can't transition to the protocol's next state, wait to
3519 * receive the rest of the header.
3520 */
3521 DBG3("Partial reception of data connection header (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
3522 state->received, state->left_to_receive,
3523 conn->sock->fd);
7591bab1 3524 goto end;
b8aa1682 3525 }
b8aa1682 3526
5312a3ed
JG
3527 /* Transition to next state: receiving the payload. */
3528 conn->protocol.data.state_id = DATA_CONNECTION_STATE_RECEIVE_PAYLOAD;
173af62f 3529
5312a3ed
JG
3530 memcpy(&header, state->header_reception_buffer, sizeof(header));
3531 header.circuit_id = be64toh(header.circuit_id);
3532 header.stream_id = be64toh(header.stream_id);
3533 header.data_size = be32toh(header.data_size);
3534 header.net_seq_num = be64toh(header.net_seq_num);
3535 header.padding_size = be32toh(header.padding_size);
3536 memcpy(&conn->protocol.data.state.receive_payload.header, &header, sizeof(header));
3537
3538 conn->protocol.data.state.receive_payload.left_to_receive =
3539 header.data_size;
3540 conn->protocol.data.state.receive_payload.received = 0;
3541 conn->protocol.data.state.receive_payload.rotate_index = false;
3542
3543 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64 ", stream_id = %" PRIu64 ", data_size = %" PRIu32 ", net_seq_num = %" PRIu64 ", padding_size = %" PRIu32,
3544 conn->sock->fd, header.circuit_id,
3545 header.stream_id, header.data_size,
3546 header.net_seq_num, header.padding_size);
3547
3548 stream = stream_get_by_id(header.stream_id);
3549 if (!stream) {
3550 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64,
3551 header.stream_id);
5569b118
JG
3552 /* Protocol error. */
3553 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed
JG
3554 goto end;
3555 }
b8aa1682 3556
7591bab1 3557 pthread_mutex_lock(&stream->lock);
c35f9726
JG
3558 /* Prepare stream for the reception of a new packet. */
3559 ret = stream_init_packet(stream, header.data_size,
3560 &conn->protocol.data.state.receive_payload.rotate_index);
3561 pthread_mutex_unlock(&stream->lock);
3562 if (ret) {
3563 ERR("Failed to rotate stream output file");
3564 status = RELAY_CONNECTION_STATUS_ERROR;
3565 goto end_stream_unlock;
1c20f0e2
JD
3566 }
3567
5312a3ed 3568end_stream_unlock:
5312a3ed
JG
3569 stream_put(stream);
3570end:
5569b118 3571 return status;
5312a3ed
JG
3572}
3573
5569b118
JG
3574static enum relay_connection_status relay_process_data_receive_payload(
3575 struct relay_connection *conn)
5312a3ed
JG
3576{
3577 int ret;
5569b118 3578 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
5312a3ed
JG
3579 struct relay_stream *stream;
3580 struct data_connection_state_receive_payload *state =
3581 &conn->protocol.data.state.receive_payload;
3582 const size_t chunk_size = RECV_DATA_BUFFER_SIZE;
3583 char data_buffer[chunk_size];
3584 bool partial_recv = false;
3585 bool new_stream = false, close_requested = false, index_flushed = false;
3586 uint64_t left_to_receive = state->left_to_receive;
3587 struct relay_session *session;
3588
fd0f1e3e
JR
3589 DBG3("Receiving data for stream id %" PRIu64 " seqnum %" PRIu64 ", %" PRIu64" bytes received, %" PRIu64 " bytes left to receive",
3590 state->header.stream_id, state->header.net_seq_num,
3591 state->received, left_to_receive);
3592
5312a3ed
JG
3593 stream = stream_get_by_id(state->header.stream_id);
3594 if (!stream) {
5569b118 3595 /* Protocol error. */
fd0f1e3e 3596 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64,
5312a3ed 3597 state->header.stream_id);
5569b118 3598 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed 3599 goto end;
1c20f0e2
JD
3600 }
3601
5312a3ed
JG
3602 pthread_mutex_lock(&stream->lock);
3603 session = stream->trace->session;
fd0f1e3e
JR
3604 if (!conn->session) {
3605 ret = connection_set_session(conn, session);
3606 if (ret) {
3607 status = RELAY_CONNECTION_STATUS_ERROR;
3608 goto end_stream_unlock;
3609 }
3610 }
5312a3ed
JG
3611
3612 /*
3613 * The size of the "chunk" received on any iteration is bounded by:
3614 * - the data left to receive,
3615 * - the data immediately available on the socket,
3616 * - the on-stack data buffer
3617 */
3618 while (left_to_receive > 0 && !partial_recv) {
5312a3ed 3619 size_t recv_size = min(left_to_receive, chunk_size);
c35f9726 3620 struct lttng_buffer_view packet_chunk;
5312a3ed
JG
3621
3622 ret = conn->sock->ops->recvmsg(conn->sock, data_buffer,
3623 recv_size, MSG_DONTWAIT);
3624 if (ret < 0) {
5569b118
JG
3625 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3626 PERROR("Socket %d error", conn->sock->fd);
3627 status = RELAY_CONNECTION_STATUS_ERROR;
3628 }
0848dba7 3629 goto end_stream_unlock;
5312a3ed
JG
3630 } else if (ret == 0) {
3631 /* No more data ready to be consumed on socket. */
3632 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64,
3633 state->header.stream_id);
5569b118 3634 status = RELAY_CONNECTION_STATUS_CLOSED;
5312a3ed
JG
3635 break;
3636 } else if (ret < (int) recv_size) {
3637 /*
3638 * All the data available on the socket has been
3639 * consumed.
3640 */
3641 partial_recv = true;
c35f9726 3642 recv_size = ret;
0848dba7
MD
3643 }
3644
c35f9726
JG
3645 packet_chunk = lttng_buffer_view_init(data_buffer,
3646 0, recv_size);
3647 assert(packet_chunk.data);
5312a3ed 3648
c35f9726
JG
3649 ret = stream_write(stream, &packet_chunk, 0);
3650 if (ret) {
0848dba7 3651 ERR("Relay error writing data to file");
5569b118 3652 status = RELAY_CONNECTION_STATUS_ERROR;
0848dba7
MD
3653 goto end_stream_unlock;
3654 }
3655
5312a3ed
JG
3656 left_to_receive -= recv_size;
3657 state->received += recv_size;
3658 state->left_to_receive = left_to_receive;
5312a3ed
JG
3659 }
3660
3661 if (state->left_to_receive > 0) {
3662 /*
3663 * Did not receive all the data expected, wait for more data to
3664 * become available on the socket.
3665 */
3666 DBG3("Partial receive on data connection of stream id %" PRIu64 ", %" PRIu64 " bytes received, %" PRIu64 " bytes left to receive",
3667 state->header.stream_id, state->received,
3668 state->left_to_receive);
5312a3ed 3669 goto end_stream_unlock;
0848dba7 3670 }
5ab7344e 3671
c35f9726
JG
3672 ret = stream_write(stream, NULL, state->header.padding_size);
3673 if (ret) {
5569b118 3674 status = RELAY_CONNECTION_STATUS_ERROR;
7591bab1 3675 goto end_stream_unlock;
1d4dfdef 3676 }
5312a3ed 3677
298a25ca 3678 if (session_streams_have_index(session)) {
c35f9726
JG
3679 ret = stream_update_index(stream, state->header.net_seq_num,
3680 state->rotate_index, &index_flushed,
3681 state->header.data_size + state->header.padding_size);
5312a3ed 3682 if (ret < 0) {
c35f9726 3683 ERR("Failed to update index: stream %" PRIu64 " net_seq_num %" PRIu64 " ret %d",
5312a3ed
JG
3684 stream->stream_handle,
3685 state->header.net_seq_num, ret);
5569b118 3686 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed
JG
3687 goto end_stream_unlock;
3688 }
3689 }
3690
a8f9f353 3691 if (stream->prev_data_seq == -1ULL) {
c0bae11d
MD
3692 new_stream = true;
3693 }
3694
c35f9726
JG
3695 ret = stream_complete_packet(stream, state->header.data_size +
3696 state->header.padding_size, state->header.net_seq_num,
3697 index_flushed);
3698 if (ret) {
3699 status = RELAY_CONNECTION_STATUS_ERROR;
3700 goto end_stream_unlock;
3701 }
5312a3ed
JG
3702
3703 /*
3704 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3705 * contents of *state which are aliased (union) to the same location as
3706 * the new state. Don't use it beyond this point.
3707 */
3708 connection_reset_protocol_state(conn);
3709 state = NULL;
173af62f 3710
7591bab1 3711end_stream_unlock:
bda7c7b9 3712 close_requested = stream->close_requested;
7591bab1 3713 pthread_mutex_unlock(&stream->lock);
5312a3ed 3714 if (close_requested && left_to_receive == 0) {
bda7c7b9
JG
3715 try_stream_close(stream);
3716 }
3717
c0bae11d
MD
3718 if (new_stream) {
3719 pthread_mutex_lock(&session->lock);
3720 uatomic_set(&session->new_streams, 1);
3721 pthread_mutex_unlock(&session->lock);
3722 }
5312a3ed 3723
7591bab1 3724 stream_put(stream);
b8aa1682 3725end:
5569b118 3726 return status;
b8aa1682
JD
3727}
3728
5312a3ed
JG
3729/*
3730 * relay_process_data: Process the data received on the data socket
3731 */
5569b118
JG
3732static enum relay_connection_status relay_process_data(
3733 struct relay_connection *conn)
5312a3ed 3734{
5569b118 3735 enum relay_connection_status status;
5312a3ed
JG
3736
3737 switch (conn->protocol.data.state_id) {
3738 case DATA_CONNECTION_STATE_RECEIVE_HEADER:
5569b118 3739 status = relay_process_data_receive_header(conn);
5312a3ed
JG
3740 break;
3741 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD:
5569b118 3742 status = relay_process_data_receive_payload(conn);
5312a3ed
JG
3743 break;
3744 default:
3745 ERR("Unexpected data connection communication state.");
3746 abort();
3747 }
3748
5569b118 3749 return status;
5312a3ed
JG
3750}
3751
7591bab1 3752static void cleanup_connection_pollfd(struct lttng_poll_event *events, int pollfd)
b8aa1682
JD
3753{
3754 int ret;
3755
58eb9381 3756 (void) lttng_poll_del(events, pollfd);
b8aa1682 3757
f355467e
JG
3758 ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker, &pollfd, 1,
3759 fd_tracker_util_close_fd, NULL);
b8aa1682
JD
3760 if (ret < 0) {
3761 ERR("Closing pollfd %d", pollfd);
3762 }
3763}
3764
7591bab1
MD
3765static void relay_thread_close_connection(struct lttng_poll_event *events,
3766 int pollfd, struct relay_connection *conn)
9d1bbf21 3767{
7591bab1 3768 const char *type_str;
2a174661 3769
7591bab1
MD
3770 switch (conn->type) {
3771 case RELAY_DATA:
3772 type_str = "Data";
3773 break;
3774 case RELAY_CONTROL:
3775 type_str = "Control";
3776 break;
3777 case RELAY_VIEWER_COMMAND:
3778 type_str = "Viewer Command";
3779 break;
3780 case RELAY_VIEWER_NOTIFICATION:
3781 type_str = "Viewer Notification";
3782 break;
3783 default:
3784 type_str = "Unknown";
9d1bbf21 3785 }
7591bab1
MD
3786 cleanup_connection_pollfd(events, pollfd);
3787 connection_put(conn);
3788 DBG("%s connection closed with %d", type_str, pollfd);
b8aa1682
JD
3789}
3790
3791/*
3792 * This thread does the actual work
3793 */
7591bab1 3794static void *relay_thread_worker(void *data)
b8aa1682 3795{
beaad64c
DG
3796 int ret, err = -1, last_seen_data_fd = -1;
3797 uint32_t nb_fd;
b8aa1682
JD
3798 struct lttng_poll_event events;
3799 struct lttng_ht *relay_connections_ht;
b8aa1682 3800 struct lttng_ht_iter iter;
90e7d72f 3801 struct relay_connection *destroy_conn = NULL;
b8aa1682
JD
3802
3803 DBG("[thread] Relay worker started");
3804
9d1bbf21
MD
3805 rcu_register_thread();
3806
55706a7d
MD
3807 health_register(health_relayd, HEALTH_RELAYD_TYPE_WORKER);
3808
9b5e0863
MD
3809 if (testpoint(relayd_thread_worker)) {
3810 goto error_testpoint;
3811 }
3812
f385ae0a
MD
3813 health_code_update();
3814
b8aa1682
JD
3815 /* table of connections indexed on socket */
3816 relay_connections_ht = lttng_ht_new(0, LTTNG_HT_TYPE_ULONG);
095a4ae5
MD
3817 if (!relay_connections_ht) {
3818 goto relay_connections_ht_error;
3819 }
b8aa1682 3820
e32a0864 3821 ret = create_named_thread_poll_set(&events, 2, "Worker thread epoll");
b8aa1682
JD
3822 if (ret < 0) {
3823 goto error_poll_create;
3824 }
3825
58eb9381 3826 ret = lttng_poll_add(&events, relay_conn_pipe[0], LPOLLIN | LPOLLRDHUP);
b8aa1682
JD
3827 if (ret < 0) {
3828 goto error;
3829 }
3830
beaad64c 3831restart:
b8aa1682 3832 while (1) {
beaad64c
DG
3833 int idx = -1, i, seen_control = 0, last_notdel_data_fd = -1;
3834
f385ae0a
MD
3835 health_code_update();
3836
b8aa1682 3837 /* Infinite blocking call, waiting for transmission */
87c1611d 3838 DBG3("Relayd worker thread polling...");
f385ae0a 3839 health_poll_entry();
b8aa1682 3840 ret = lttng_poll_wait(&events, -1);
f385ae0a 3841 health_poll_exit();
b8aa1682
JD
3842 if (ret < 0) {
3843 /*
3844 * Restart interrupted system call.
3845 */
3846 if (errno == EINTR) {
3847 goto restart;
3848 }
3849 goto error;
3850 }
3851
0d9c5d77
DG
3852 nb_fd = ret;
3853
beaad64c 3854 /*
7591bab1
MD
3855 * Process control. The control connection is
3856 * prioritized so we don't starve it with high
3857 * throughput tracing data on the data connection.
beaad64c 3858 */
b8aa1682
JD
3859 for (i = 0; i < nb_fd; i++) {
3860 /* Fetch once the poll data */
beaad64c
DG
3861 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
3862 int pollfd = LTTNG_POLL_GETFD(&events, i);
b8aa1682 3863
f385ae0a
MD
3864 health_code_update();
3865
b8aa1682
JD
3866 /* Thread quit pipe has been closed. Killing thread. */
3867 ret = check_thread_quit_pipe(pollfd, revents);
3868 if (ret) {
095a4ae5
MD
3869 err = 0;
3870 goto exit;
b8aa1682
JD
3871 }
3872
58eb9381
DG
3873 /* Inspect the relay conn pipe for new connection */
3874 if (pollfd == relay_conn_pipe[0]) {
03e43155 3875 if (revents & LPOLLIN) {
90e7d72f
JG
3876 struct relay_connection *conn;
3877
58eb9381 3878 ret = lttng_read(relay_conn_pipe[0], &conn, sizeof(conn));
b8aa1682
JD
3879 if (ret < 0) {
3880 goto error;
3881 }
73039936
FD
3882 ret = lttng_poll_add(&events,
3883 conn->sock->fd,
58eb9381 3884 LPOLLIN | LPOLLRDHUP);
73039936
FD
3885 if (ret) {
3886 ERR("Failed to add new connection file descriptor to poll set");
3887 goto error;
3888 }
7591bab1 3889 connection_ht_add(relay_connections_ht, conn);
58eb9381 3890 DBG("Connection socket %d added", conn->sock->fd);
03e43155
MD
3891 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
3892 ERR("Relay connection pipe error");
3893 goto error;
3894 } else {
3895 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
3896 goto error;
b8aa1682 3897 }
58eb9381 3898 } else {
90e7d72f
JG
3899 struct relay_connection *ctrl_conn;
3900
7591bab1 3901 ctrl_conn = connection_get_by_sock(relay_connections_ht, pollfd);
58eb9381 3902 /* If not found, there is a synchronization issue. */
90e7d72f 3903 assert(ctrl_conn);
58eb9381 3904
03e43155
MD
3905 if (ctrl_conn->type == RELAY_DATA) {
3906 if (revents & LPOLLIN) {
beaad64c
DG
3907 /*
3908 * Flag the last seen data fd not deleted. It will be
3909 * used as the last seen fd if any fd gets deleted in
3910 * this first loop.
3911 */
3912 last_notdel_data_fd = pollfd;
3913 }
03e43155
MD
3914 goto put_ctrl_connection;
3915 }
3916 assert(ctrl_conn->type == RELAY_CONTROL);
3917
3918 if (revents & LPOLLIN) {
5569b118
JG
3919 enum relay_connection_status status;
3920
3921 status = relay_process_control(ctrl_conn);
3922 if (status != RELAY_CONNECTION_STATUS_OK) {
fd0f1e3e
JR
3923 /*
3924 * On socket error flag the session as aborted to force
3925 * the cleanup of its stream otherwise it can leak
3926 * during the lifetime of the relayd.
3927 *
3928 * This prevents situations in which streams can be
3929 * left opened because an index was received, the
3930 * control connection is closed, and the data
3931 * connection is closed (uncleanly) before the packet's
3932 * data provided.
3933 *
3934 * Since the control connection encountered an error,
3935 * it is okay to be conservative and close the
3936 * session right now as we can't rely on the protocol
3937 * being respected anymore.
3938 */
3939 if (status == RELAY_CONNECTION_STATUS_ERROR) {
3940 session_abort(ctrl_conn->session);
3941 }
3942
5569b118 3943 /* Clear the connection on error or close. */
5312a3ed
JG
3944 relay_thread_close_connection(&events,
3945 pollfd,
03e43155 3946 ctrl_conn);
03e43155 3947 }
5312a3ed 3948 seen_control = 1;
03e43155
MD
3949 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
3950 relay_thread_close_connection(&events,
3951 pollfd, ctrl_conn);
3952 if (last_seen_data_fd == pollfd) {
3953 last_seen_data_fd = last_notdel_data_fd;
3954 }
58eb9381 3955 } else {
03e43155
MD
3956 ERR("Unexpected poll events %u for control sock %d",
3957 revents, pollfd);
3958 connection_put(ctrl_conn);
3959 goto error;
beaad64c 3960 }
03e43155 3961 put_ctrl_connection:
7591bab1 3962 connection_put(ctrl_conn);
beaad64c
DG
3963 }
3964 }
3965
3966 /*
3967 * The last loop handled a control request, go back to poll to make
3968 * sure we prioritise the control socket.
3969 */
3970 if (seen_control) {
3971 continue;
3972 }
3973
3974 if (last_seen_data_fd >= 0) {
3975 for (i = 0; i < nb_fd; i++) {
3976 int pollfd = LTTNG_POLL_GETFD(&events, i);
f385ae0a
MD
3977
3978 health_code_update();
3979
beaad64c
DG
3980 if (last_seen_data_fd == pollfd) {
3981 idx = i;
3982 break;
3983 }
3984 }
3985 }
3986
3987 /* Process data connection. */
3988 for (i = idx + 1; i < nb_fd; i++) {
3989 /* Fetch the poll data. */
3990 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
3991 int pollfd = LTTNG_POLL_GETFD(&events, i);
90e7d72f 3992 struct relay_connection *data_conn;
beaad64c 3993
f385ae0a
MD
3994 health_code_update();
3995
fd20dac9
MD
3996 if (!revents) {
3997 /* No activity for this FD (poll implementation). */
3998 continue;
3999 }
4000
beaad64c 4001 /* Skip the command pipe. It's handled in the first loop. */
58eb9381 4002 if (pollfd == relay_conn_pipe[0]) {
beaad64c
DG
4003 continue;
4004 }
4005
7591bab1 4006 data_conn = connection_get_by_sock(relay_connections_ht, pollfd);
90e7d72f 4007 if (!data_conn) {
fd20dac9 4008 /* Skip it. Might be removed before. */
fd20dac9
MD
4009 continue;
4010 }
03e43155
MD
4011 if (data_conn->type == RELAY_CONTROL) {
4012 goto put_data_connection;
4013 }
4014 assert(data_conn->type == RELAY_DATA);
fd20dac9
MD
4015
4016 if (revents & LPOLLIN) {
5569b118
JG
4017 enum relay_connection_status status;
4018
4019 status = relay_process_data(data_conn);
4020 /* Connection closed or error. */
4021 if (status != RELAY_CONNECTION_STATUS_OK) {
fd0f1e3e
JR
4022 /*
4023 * On socket error flag the session as aborted to force
4024 * the cleanup of its stream otherwise it can leak
4025 * during the lifetime of the relayd.
4026 *
4027 * This prevents situations in which streams can be
4028 * left opened because an index was received, the
4029 * control connection is closed, and the data
4030 * connection is closed (uncleanly) before the packet's
4031 * data provided.
4032 *
4033 * Since the data connection encountered an error,
4034 * it is okay to be conservative and close the
4035 * session right now as we can't rely on the protocol
4036 * being respected anymore.
4037 */
4038 if (status == RELAY_CONNECTION_STATUS_ERROR) {
4039 session_abort(data_conn->session);
4040 }
7591bab1 4041 relay_thread_close_connection(&events, pollfd,
03e43155 4042 data_conn);
fd20dac9
MD
4043 /*
4044 * Every goto restart call sets the last seen fd where
4045 * here we don't really care since we gracefully
4046 * continue the loop after the connection is deleted.
4047 */
4048 } else {
4049 /* Keep last seen port. */
4050 last_seen_data_fd = pollfd;
7591bab1 4051 connection_put(data_conn);
fd20dac9 4052 goto restart;
b8aa1682 4053 }
03e43155
MD
4054 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
4055 relay_thread_close_connection(&events, pollfd,
4056 data_conn);
4057 } else {
4058 ERR("Unknown poll events %u for data sock %d",
4059 revents, pollfd);
b8aa1682 4060 }
03e43155 4061 put_data_connection:
7591bab1 4062 connection_put(data_conn);
b8aa1682 4063 }
beaad64c 4064 last_seen_data_fd = -1;
b8aa1682
JD
4065 }
4066
f385ae0a
MD
4067 /* Normal exit, no error */
4068 ret = 0;
4069
095a4ae5 4070exit:
b8aa1682 4071error:
71efa8ef 4072 /* Cleanup remaining connection object. */
9d1bbf21 4073 rcu_read_lock();
90e7d72f
JG
4074 cds_lfht_for_each_entry(relay_connections_ht->ht, &iter.iter,
4075 destroy_conn,
58eb9381 4076 sock_n.node) {
f385ae0a 4077 health_code_update();
98ba050e 4078
fd0f1e3e 4079 session_abort(destroy_conn->session);
98ba050e 4080
7591bab1
MD
4081 /*
4082 * No need to grab another ref, because we own
4083 * destroy_conn.
4084 */
4085 relay_thread_close_connection(&events, destroy_conn->sock->fd,
4086 destroy_conn);
b8aa1682 4087 }
94d49140 4088 rcu_read_unlock();
7591bab1 4089
e32a0864 4090 (void) fd_tracker_util_poll_clean(the_fd_tracker, &events);
7d2f7452 4091error_poll_create:
b8aa1682 4092 lttng_ht_destroy(relay_connections_ht);
095a4ae5 4093relay_connections_ht_error:
58eb9381 4094 /* Close relay conn pipes */
726b2396
JG
4095 (void) fd_tracker_util_pipe_close(the_fd_tracker,
4096 relay_conn_pipe);
095a4ae5
MD
4097 if (err) {
4098 DBG("Thread exited with error");
4099 }
b8aa1682 4100 DBG("Worker thread cleanup complete");
9b5e0863 4101error_testpoint:
f385ae0a
MD
4102 if (err) {
4103 health_error();
4104 ERR("Health error occurred in %s", __func__);
4105 }
4106 health_unregister(health_relayd);
9d1bbf21 4107 rcu_unregister_thread();
b4aacfdc 4108 lttng_relay_stop_threads();
b8aa1682
JD
4109 return NULL;
4110}
4111
4112/*
4113 * Create the relay command pipe to wake thread_manage_apps.
4114 * Closed in cleanup().
4115 */
58eb9381 4116static int create_relay_conn_pipe(void)
b8aa1682 4117{
726b2396
JG
4118 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker,
4119 "Relayd connection pipe", relay_conn_pipe);
b8aa1682
JD
4120}
4121
9c256b01
JG
4122static int stdio_open(void *data, int *fds)
4123{
4124 fds[0] = fileno(stdout);
4125 fds[1] = fileno(stderr);
4126 return 0;
4127}
4128
9c256b01
JG
4129static int track_stdio(void)
4130{
4131 int fds[2];
4132 const char *names[] = { "stdout", "stderr" };
4133
4134 return fd_tracker_open_unsuspendable_fd(the_fd_tracker, fds,
4135 names, 2, stdio_open, NULL);
4136}
4137
b8aa1682
JD
4138/*
4139 * main
4140 */
4141int main(int argc, char **argv)
4142{
00e3b7f1 4143 bool thread_is_rcu_registered = false;
178a0557 4144 int ret = 0, retval = 0;
b8aa1682 4145 void *status;
f7c3ffd7 4146 char *unlinked_file_directory_path = NULL, *output_path = NULL;
b8aa1682 4147
2a10de3b
JR
4148 /* Parse environment variables */
4149 ret = parse_env_options();
4150 if (ret) {
4151 retval = -1;
4152 goto exit_options;
4153 }
4154
4155 /*
4156 * Parse arguments.
4157 * Command line arguments overwrite environment.
4158 */
b8aa1682 4159 progname = argv[0];
178a0557
MD
4160 if (set_options(argc, argv)) {
4161 retval = -1;
4162 goto exit_options;
b8aa1682
JD
4163 }
4164
178a0557
MD
4165 if (set_signal_handler()) {
4166 retval = -1;
4167 goto exit_options;
b8aa1682
JD
4168 }
4169
a3bc3918
JR
4170 relayd_config_log();
4171
4172 if (opt_print_version) {
4173 print_version();
4174 retval = 0;
4175 goto exit_options;
4176 }
4177
c0407718
JG
4178 ret = fclose(stdin);
4179 if (ret) {
4180 PERROR("Failed to close stdin");
4181 goto exit_options;
4182 }
4183
35ab25e5
MD
4184 DBG("Clear command %s", opt_allow_clear ? "allowed" : "disallowed");
4185
4d513a50
DG
4186 /* Try to create directory if -o, --output is specified. */
4187 if (opt_output_path) {
994fa64f
DG
4188 if (*opt_output_path != '/') {
4189 ERR("Please specify an absolute path for -o, --output PATH");
178a0557
MD
4190 retval = -1;
4191 goto exit_options;
994fa64f
DG
4192 }
4193
d77dded2
JG
4194 ret = utils_mkdir_recursive(opt_output_path, S_IRWXU | S_IRWXG,
4195 -1, -1);
4d513a50
DG
4196 if (ret < 0) {
4197 ERR("Unable to create %s", opt_output_path);
178a0557
MD
4198 retval = -1;
4199 goto exit_options;
4d513a50
DG
4200 }
4201 }
4202
b8aa1682 4203 /* Daemonize */
b5218ffb 4204 if (opt_daemon || opt_background) {
3fd27398
MD
4205 ret = lttng_daemonize(&child_ppid, &recv_child_signal,
4206 !opt_background);
b8aa1682 4207 if (ret < 0) {
178a0557
MD
4208 retval = -1;
4209 goto exit_options;
b8aa1682 4210 }
3fd27398
MD
4211 }
4212
ce9ee1fb
JR
4213 if (opt_working_directory) {
4214 ret = utils_change_working_directory(opt_working_directory);
4215 if (ret) {
4216 /* All errors are already logged. */
4217 goto exit_options;
4218 }
4219 }
4220
23c8ff50
JG
4221 sessiond_trace_chunk_registry = sessiond_trace_chunk_registry_create();
4222 if (!sessiond_trace_chunk_registry) {
4223 ERR("Failed to initialize session daemon trace chunk registry");
4224 retval = -1;
794e2e5f 4225 goto exit_options;
23c8ff50
JG
4226 }
4227
00e3b7f1
JG
4228 /*
4229 * The RCU thread registration (and use, through the fd-tracker's
4230 * creation) is done after the daemonization to allow us to not
4231 * deal with liburcu's fork() management as the call RCU needs to
4232 * be restored.
4233 */
4234 rcu_register_thread();
4235 thread_is_rcu_registered = true;
4236
f7c3ffd7
JG
4237 output_path = create_output_path("");
4238 if (!output_path) {
4239 ERR("Failed to get output path");
4240 retval = -1;
4241 goto exit_options;
4242 }
4243 ret = asprintf(&unlinked_file_directory_path, "%s/%s", output_path,
4244 DEFAULT_UNLINKED_FILES_DIRECTORY);
4245 free(output_path);
4246 if (ret < 0) {
4247 ERR("Failed to format unlinked file directory path");
4248 retval = -1;
4249 goto exit_options;
4250 }
4251 the_fd_tracker = fd_tracker_create(
4252 unlinked_file_directory_path, lttng_opt_fd_pool_size);
4253 free(unlinked_file_directory_path);
00e3b7f1
JG
4254 if (!the_fd_tracker) {
4255 retval = -1;
4256 goto exit_options;
4257 }
4258
9c256b01
JG
4259 ret = track_stdio();
4260 if (ret) {
4261 retval = -1;
4262 goto exit_options;
4263 }
4264
178a0557
MD
4265 /* Initialize thread health monitoring */
4266 health_relayd = health_app_create(NR_HEALTH_RELAYD_TYPES);
4267 if (!health_relayd) {
4268 PERROR("health_app_create error");
4269 retval = -1;
794e2e5f 4270 goto exit_options;
178a0557
MD
4271 }
4272
3fd27398 4273 /* Create thread quit pipe */
178a0557
MD
4274 if (init_thread_quit_pipe()) {
4275 retval = -1;
794e2e5f 4276 goto exit_options;
b8aa1682
JD
4277 }
4278
b8aa1682 4279 /* Setup the thread apps communication pipe. */
178a0557
MD
4280 if (create_relay_conn_pipe()) {
4281 retval = -1;
794e2e5f 4282 goto exit_options;
b8aa1682
JD
4283 }
4284
4285 /* Init relay command queue. */
8bdee6e2 4286 cds_wfcq_init(&relay_conn_queue.head, &relay_conn_queue.tail);
b8aa1682 4287
554831e7
MD
4288 /* Initialize communication library */
4289 lttcomm_init();
87e45c13 4290 lttcomm_inet_init();
554831e7 4291
d3e2ba59 4292 /* tables of sessions indexed by session ID */
7591bab1
MD
4293 sessions_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
4294 if (!sessions_ht) {
178a0557 4295 retval = -1;
794e2e5f 4296 goto exit_options;
d3e2ba59
JD
4297 }
4298
4299 /* tables of streams indexed by stream ID */
2a174661 4300 relay_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
d3e2ba59 4301 if (!relay_streams_ht) {
178a0557 4302 retval = -1;
794e2e5f 4303 goto exit_options;
d3e2ba59
JD
4304 }
4305
4306 /* tables of streams indexed by stream ID */
92c6ca54
DG
4307 viewer_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
4308 if (!viewer_streams_ht) {
178a0557 4309 retval = -1;
794e2e5f 4310 goto exit_options;
55706a7d
MD
4311 }
4312
bcee2b96 4313 ret = init_health_quit_pipe();
178a0557
MD
4314 if (ret) {
4315 retval = -1;
794e2e5f 4316 goto exit_options;
65931c8b
MD
4317 }
4318
4319 /* Create thread to manage the client socket */
1a1a34b4 4320 ret = pthread_create(&health_thread, default_pthread_attr(),
65931c8b 4321 thread_manage_health, (void *) NULL);
178a0557
MD
4322 if (ret) {
4323 errno = ret;
65931c8b 4324 PERROR("pthread_create health");
178a0557 4325 retval = -1;
794e2e5f 4326 goto exit_options;
65931c8b
MD
4327 }
4328
b8aa1682 4329 /* Setup the dispatcher thread */
1a1a34b4 4330 ret = pthread_create(&dispatcher_thread, default_pthread_attr(),
b8aa1682 4331 relay_thread_dispatcher, (void *) NULL);
178a0557
MD
4332 if (ret) {
4333 errno = ret;
b8aa1682 4334 PERROR("pthread_create dispatcher");
178a0557
MD
4335 retval = -1;
4336 goto exit_dispatcher_thread;
b8aa1682
JD
4337 }
4338
4339 /* Setup the worker thread */
1a1a34b4 4340 ret = pthread_create(&worker_thread, default_pthread_attr(),
7591bab1 4341 relay_thread_worker, NULL);
178a0557
MD
4342 if (ret) {
4343 errno = ret;
b8aa1682 4344 PERROR("pthread_create worker");
178a0557
MD
4345 retval = -1;
4346 goto exit_worker_thread;
b8aa1682
JD
4347 }
4348
4349 /* Setup the listener thread */
1a1a34b4 4350 ret = pthread_create(&listener_thread, default_pthread_attr(),
b8aa1682 4351 relay_thread_listener, (void *) NULL);
178a0557
MD
4352 if (ret) {
4353 errno = ret;
b8aa1682 4354 PERROR("pthread_create listener");
178a0557
MD
4355 retval = -1;
4356 goto exit_listener_thread;
b8aa1682
JD
4357 }
4358
7591bab1 4359 ret = relayd_live_create(live_uri);
178a0557 4360 if (ret) {
d3e2ba59 4361 ERR("Starting live viewer threads");
178a0557 4362 retval = -1;
50138f51 4363 goto exit_live;
d3e2ba59
JD
4364 }
4365
178a0557
MD
4366 /*
4367 * This is where we start awaiting program completion (e.g. through
4368 * signal that asks threads to teardown).
4369 */
4370
4371 ret = relayd_live_join();
4372 if (ret) {
4373 retval = -1;
4374 }
50138f51 4375exit_live:
178a0557 4376
b8aa1682 4377 ret = pthread_join(listener_thread, &status);
178a0557
MD
4378 if (ret) {
4379 errno = ret;
4380 PERROR("pthread_join listener_thread");
4381 retval = -1;
b8aa1682
JD
4382 }
4383
178a0557 4384exit_listener_thread:
b8aa1682 4385 ret = pthread_join(worker_thread, &status);
178a0557
MD
4386 if (ret) {
4387 errno = ret;
4388 PERROR("pthread_join worker_thread");
4389 retval = -1;
b8aa1682
JD
4390 }
4391
178a0557 4392exit_worker_thread:
b8aa1682 4393 ret = pthread_join(dispatcher_thread, &status);
178a0557
MD
4394 if (ret) {
4395 errno = ret;
4396 PERROR("pthread_join dispatcher_thread");
4397 retval = -1;
b8aa1682 4398 }
178a0557 4399exit_dispatcher_thread:
42415026 4400
65931c8b 4401 ret = pthread_join(health_thread, &status);
178a0557
MD
4402 if (ret) {
4403 errno = ret;
4404 PERROR("pthread_join health_thread");
4405 retval = -1;
65931c8b 4406 }
178a0557 4407exit_options:
4d62fbf8
MD
4408 /*
4409 * Wait for all pending call_rcu work to complete before tearing
4410 * down data structures. call_rcu worker may be trying to
4411 * perform lookups in those structures.
4412 */
4413 rcu_barrier();
7591bab1
MD
4414 relayd_cleanup();
4415
4416 /* Ensure all prior call_rcu are done. */
4417 rcu_barrier();
d3e2ba59 4418
00e3b7f1
JG
4419 if (thread_is_rcu_registered) {
4420 rcu_unregister_thread();
4421 }
4422
178a0557 4423 if (!retval) {
b8aa1682 4424 exit(EXIT_SUCCESS);
178a0557
MD
4425 } else {
4426 exit(EXIT_FAILURE);
b8aa1682 4427 }
b8aa1682 4428}
This page took 0.320807 seconds and 4 git commands to generate.