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