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