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