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