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