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