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