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