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