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