relayd: Retrieve a relay_session's trace chunk on creation
[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>
40#include <unistd.h>
41#include <fcntl.h>
b8aa1682
JD
42
43#include <lttng/lttng.h>
44#include <common/common.h>
45#include <common/compat/poll.h>
46#include <common/compat/socket.h>
f263b7fd 47#include <common/compat/endian.h>
e8fa9fb0 48#include <common/compat/getenv.h>
b8aa1682 49#include <common/defaults.h>
3fd27398 50#include <common/daemonize.h>
b8aa1682
JD
51#include <common/futex.h>
52#include <common/sessiond-comm/sessiond-comm.h>
53#include <common/sessiond-comm/inet.h>
b8aa1682
JD
54#include <common/sessiond-comm/relayd.h>
55#include <common/uri.h>
a02de639 56#include <common/utils.h>
d3ecc550 57#include <common/align.h>
f40ef1d5 58#include <common/config/session-config.h>
5312a3ed
JG
59#include <common/dynamic-buffer.h>
60#include <common/buffer-view.h>
7591bab1 61#include <urcu/rculist.h>
b8aa1682 62
0f907de1 63#include "cmd.h"
d3e2ba59 64#include "ctf-trace.h"
1c20f0e2 65#include "index.h"
0f907de1 66#include "utils.h"
b8aa1682 67#include "lttng-relayd.h"
d3e2ba59 68#include "live.h"
55706a7d 69#include "health-relayd.h"
9b5e0863 70#include "testpoint.h"
2f8f53af 71#include "viewer-stream.h"
2a174661
DG
72#include "session.h"
73#include "stream.h"
58eb9381 74#include "connection.h"
a44ca2ca 75#include "tracefile-array.h"
f056029c 76#include "tcp_keep_alive.h"
23c8ff50 77#include "sessiond-trace-chunks.h"
b8aa1682 78
4fc83d94
PP
79static const char *help_msg =
80#ifdef LTTNG_EMBED_HELP
81#include <lttng-relayd.8.h>
82#else
83NULL
84#endif
85;
86
5569b118
JG
87enum relay_connection_status {
88 RELAY_CONNECTION_STATUS_OK,
a9577b76 89 /* An error occurred while processing an event on the connection. */
5569b118
JG
90 RELAY_CONNECTION_STATUS_ERROR,
91 /* Connection closed/shutdown cleanly. */
92 RELAY_CONNECTION_STATUS_CLOSED,
93};
94
b8aa1682 95/* command line options */
0f907de1 96char *opt_output_path;
b5218ffb 97static int opt_daemon, opt_background;
3fd27398
MD
98
99/*
100 * We need to wait for listener and live listener threads, as well as
101 * health check thread, before being ready to signal readiness.
102 */
103#define NR_LTTNG_RELAY_READY 3
104static int lttng_relay_ready = NR_LTTNG_RELAY_READY;
0848dba7
MD
105
106/* Size of receive buffer. */
107#define RECV_DATA_BUFFER_SIZE 65536
d3ecc550 108#define FILE_COPY_BUFFER_SIZE 65536
0848dba7 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
b8aa1682 1054/*
7591bab1 1055 * Set index data from the control port to a given index object.
b8aa1682 1056 */
7591bab1 1057static int set_index_control_data(struct relay_index *index,
234cd636
JD
1058 struct lttcomm_relayd_index *data,
1059 struct relay_connection *conn)
1c20f0e2 1060{
7591bab1 1061 struct ctf_packet_index index_data;
1c20f0e2
JD
1062
1063 /*
5312a3ed 1064 * The index on disk is encoded in big endian.
1c20f0e2 1065 */
5312a3ed
JG
1066 index_data.packet_size = htobe64(data->packet_size);
1067 index_data.content_size = htobe64(data->content_size);
1068 index_data.timestamp_begin = htobe64(data->timestamp_begin);
1069 index_data.timestamp_end = htobe64(data->timestamp_end);
1070 index_data.events_discarded = htobe64(data->events_discarded);
1071 index_data.stream_id = htobe64(data->stream_id);
234cd636
JD
1072
1073 if (conn->minor >= 8) {
5312a3ed
JG
1074 index->index_data.stream_instance_id = htobe64(data->stream_instance_id);
1075 index->index_data.packet_seq_num = htobe64(data->packet_seq_num);
234cd636
JD
1076 }
1077
7591bab1 1078 return relay_index_set_data(index, &index_data);
1c20f0e2
JD
1079}
1080
298a25ca
JG
1081static bool session_streams_have_index(const struct relay_session *session)
1082{
1083 return session->minor >= 4 && !session->snapshot;
1084}
1085
c5b6f4f0
DG
1086/*
1087 * Handle the RELAYD_CREATE_SESSION command.
1088 *
1089 * On success, send back the session id or else return a negative value.
1090 */
5312a3ed
JG
1091static int relay_create_session(const struct lttcomm_relayd_hdr *recv_hdr,
1092 struct relay_connection *conn,
1093 const struct lttng_buffer_view *payload)
c5b6f4f0 1094{
5312a3ed
JG
1095 int ret = 0;
1096 ssize_t send_ret;
4c6885d2 1097 struct relay_session *session = NULL;
1e791a74
JG
1098 struct lttcomm_relayd_status_session reply = {};
1099 char session_name[LTTNG_NAME_MAX] = {};
1100 char hostname[LTTNG_HOST_NAME_MAX] = {};
7591bab1
MD
1101 uint32_t live_timer = 0;
1102 bool snapshot = false;
23c8ff50
JG
1103 /* Left nil for peers < 2.11. */
1104 lttng_uuid sessiond_uuid = {};
1e791a74
JG
1105 LTTNG_OPTIONAL(uint64_t) id_sessiond = {};
1106 LTTNG_OPTIONAL(uint64_t) current_chunk_id = {};
c5b6f4f0 1107
f86f6389
JR
1108 if (conn->minor < 4) {
1109 /* From 2.1 to 2.3 */
1110 ret = 0;
1111 } else if (conn->minor >= 4 && conn->minor < 11) {
1112 /* From 2.4 to 2.10 */
5312a3ed 1113 ret = cmd_create_session_2_4(payload, session_name,
7591bab1 1114 hostname, &live_timer, &snapshot);
f86f6389
JR
1115 } else {
1116 /* From 2.11 to ... */
1117 ret = cmd_create_session_2_11(payload, session_name,
23c8ff50 1118 hostname, &live_timer, &snapshot,
1e791a74
JG
1119 &id_sessiond.value, sessiond_uuid,
1120 &current_chunk_id.value);
23c8ff50
JG
1121 if (lttng_uuid_is_nil(sessiond_uuid)) {
1122 /* The nil UUID is reserved for pre-2.11 clients. */
1123 ERR("Illegal nil UUID announced by peer in create session command");
1124 ret = -1;
1125 goto send_reply;
1126 }
1e791a74
JG
1127 id_sessiond.is_set = true;
1128 current_chunk_id.is_set = true;
7591bab1 1129 }
f86f6389 1130
7591bab1
MD
1131 if (ret < 0) {
1132 goto send_reply;
d3e2ba59
JD
1133 }
1134
7591bab1 1135 session = session_create(session_name, hostname, live_timer,
1e791a74
JG
1136 snapshot, sessiond_uuid,
1137 id_sessiond.is_set ? &id_sessiond.value : NULL,
1138 current_chunk_id.is_set ? &current_chunk_id.value : NULL,
1139 conn->major, conn->minor);
7591bab1
MD
1140 if (!session) {
1141 ret = -1;
1142 goto send_reply;
1143 }
1144 assert(!conn->session);
1145 conn->session = session;
c5b6f4f0
DG
1146 DBG("Created session %" PRIu64, session->id);
1147
7591bab1
MD
1148 reply.session_id = htobe64(session->id);
1149
639ddf68
JG
1150 session->current_trace_chunk =
1151 sessiond_trace_chunk_registry_get_anonymous_chunk(
1152 sessiond_trace_chunk_registry, sessiond_uuid,
1e791a74 1153 session->id);
639ddf68
JG
1154 if (!session->current_trace_chunk) {
1155 ret = -1;
1156 }
1157
7591bab1 1158send_reply:
c5b6f4f0
DG
1159 if (ret < 0) {
1160 reply.ret_code = htobe32(LTTNG_ERR_FATAL);
1161 } else {
1162 reply.ret_code = htobe32(LTTNG_OK);
1163 }
1164
58eb9381 1165 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
5312a3ed
JG
1166 if (send_ret < (ssize_t) sizeof(reply)) {
1167 ERR("Failed to send \"create session\" command reply (ret = %zd)",
1168 send_ret);
1169 ret = -1;
c5b6f4f0 1170 }
4c6885d2
JG
1171 if (ret < 0 && session) {
1172 session_put(session);
1173 }
c5b6f4f0
DG
1174 return ret;
1175}
1176
a4baae1b
JD
1177/*
1178 * When we have received all the streams and the metadata for a channel,
1179 * we make them visible to the viewer threads.
1180 */
7591bab1 1181static void publish_connection_local_streams(struct relay_connection *conn)
a4baae1b 1182{
7591bab1
MD
1183 struct relay_stream *stream;
1184 struct relay_session *session = conn->session;
a4baae1b 1185
7591bab1
MD
1186 /*
1187 * We publish all streams belonging to a session atomically wrt
1188 * session lock.
1189 */
1190 pthread_mutex_lock(&session->lock);
1191 rcu_read_lock();
1192 cds_list_for_each_entry_rcu(stream, &session->recv_list,
1193 recv_node) {
1194 stream_publish(stream);
a4baae1b 1195 }
7591bab1 1196 rcu_read_unlock();
a4baae1b 1197
7591bab1
MD
1198 /*
1199 * Inform the viewer that there are new streams in the session.
1200 */
1201 if (session->viewer_attached) {
1202 uatomic_set(&session->new_streams, 1);
1203 }
1204 pthread_mutex_unlock(&session->lock);
a4baae1b
JD
1205}
1206
b8aa1682
JD
1207/*
1208 * relay_add_stream: allocate a new stream for a session
1209 */
5312a3ed
JG
1210static int relay_add_stream(const struct lttcomm_relayd_hdr *recv_hdr,
1211 struct relay_connection *conn,
1212 const struct lttng_buffer_view *payload)
b8aa1682 1213{
7591bab1
MD
1214 int ret;
1215 ssize_t send_ret;
58eb9381 1216 struct relay_session *session = conn->session;
b8aa1682
JD
1217 struct relay_stream *stream = NULL;
1218 struct lttcomm_relayd_status_stream reply;
4030a636 1219 struct ctf_trace *trace = NULL;
7591bab1
MD
1220 uint64_t stream_handle = -1ULL;
1221 char *path_name = NULL, *channel_name = NULL;
1222 uint64_t tracefile_size = 0, tracefile_count = 0;
81164b6b 1223 struct relay_stream_chunk_id stream_chunk_id = { 0 };
b8aa1682 1224
5312a3ed 1225 if (!session || !conn->version_check_done) {
b8aa1682
JD
1226 ERR("Trying to add a stream before version check");
1227 ret = -1;
1228 goto end_no_session;
1229 }
1230
2f21a469
JR
1231 if (session->minor == 1) {
1232 /* For 2.1 */
5312a3ed 1233 ret = cmd_recv_stream_2_1(payload, &path_name,
7591bab1 1234 &channel_name);
2f21a469
JR
1235 } else if (session->minor > 1 && session->minor < 11) {
1236 /* From 2.2 to 2.10 */
5312a3ed 1237 ret = cmd_recv_stream_2_2(payload, &path_name,
7591bab1 1238 &channel_name, &tracefile_size, &tracefile_count);
2f21a469
JR
1239 } else {
1240 /* From 2.11 to ... */
1241 ret = cmd_recv_stream_2_11(payload, &path_name,
0b50e4b3
JG
1242 &channel_name, &tracefile_size, &tracefile_count,
1243 &stream_chunk_id.value);
1244 stream_chunk_id.is_set = true;
0f907de1 1245 }
2f21a469 1246
0f907de1 1247 if (ret < 0) {
7591bab1 1248 goto send_reply;
b8aa1682
JD
1249 }
1250
7591bab1 1251 trace = ctf_trace_get_by_path_or_create(session, path_name);
2a174661 1252 if (!trace) {
7591bab1 1253 goto send_reply;
2a174661 1254 }
7591bab1 1255 /* This stream here has one reference on the trace. */
2a174661 1256
7591bab1
MD
1257 pthread_mutex_lock(&last_relay_stream_id_lock);
1258 stream_handle = ++last_relay_stream_id;
1259 pthread_mutex_unlock(&last_relay_stream_id_lock);
d3e2ba59 1260
7591bab1
MD
1261 /* We pass ownership of path_name and channel_name. */
1262 stream = stream_create(trace, stream_handle, path_name,
81164b6b
JG
1263 channel_name, tracefile_size, tracefile_count,
1264 &stream_chunk_id);
7591bab1
MD
1265 path_name = NULL;
1266 channel_name = NULL;
a4baae1b 1267
2a174661 1268 /*
7591bab1
MD
1269 * Streams are the owners of their trace. Reference to trace is
1270 * kept within stream_create().
2a174661 1271 */
7591bab1 1272 ctf_trace_put(trace);
d3e2ba59 1273
7591bab1 1274send_reply:
53efb85a 1275 memset(&reply, 0, sizeof(reply));
7591bab1
MD
1276 reply.handle = htobe64(stream_handle);
1277 if (!stream) {
f73fabfd 1278 reply.ret_code = htobe32(LTTNG_ERR_UNK);
b8aa1682 1279 } else {
f73fabfd 1280 reply.ret_code = htobe32(LTTNG_OK);
b8aa1682 1281 }
5af40280 1282
58eb9381 1283 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
b8aa1682 1284 sizeof(struct lttcomm_relayd_status_stream), 0);
5312a3ed
JG
1285 if (send_ret < (ssize_t) sizeof(reply)) {
1286 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1287 send_ret);
1288 ret = -1;
b8aa1682
JD
1289 }
1290
1291end_no_session:
7591bab1
MD
1292 free(path_name);
1293 free(channel_name);
0f907de1 1294 return ret;
b8aa1682
JD
1295}
1296
173af62f
DG
1297/*
1298 * relay_close_stream: close a specific stream
1299 */
5312a3ed
JG
1300static int relay_close_stream(const struct lttcomm_relayd_hdr *recv_hdr,
1301 struct relay_connection *conn,
1302 const struct lttng_buffer_view *payload)
173af62f 1303{
5312a3ed
JG
1304 int ret;
1305 ssize_t send_ret;
58eb9381 1306 struct relay_session *session = conn->session;
173af62f
DG
1307 struct lttcomm_relayd_close_stream stream_info;
1308 struct lttcomm_relayd_generic_reply reply;
1309 struct relay_stream *stream;
173af62f
DG
1310
1311 DBG("Close stream received");
1312
5312a3ed 1313 if (!session || !conn->version_check_done) {
173af62f
DG
1314 ERR("Trying to close a stream before version check");
1315 ret = -1;
1316 goto end_no_session;
1317 }
1318
5312a3ed
JG
1319 if (payload->size < sizeof(stream_info)) {
1320 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1321 sizeof(stream_info), payload->size);
173af62f
DG
1322 ret = -1;
1323 goto end_no_session;
1324 }
5312a3ed
JG
1325 memcpy(&stream_info, payload->data, sizeof(stream_info));
1326 stream_info.stream_id = be64toh(stream_info.stream_id);
1327 stream_info.last_net_seq_num = be64toh(stream_info.last_net_seq_num);
173af62f 1328
5312a3ed 1329 stream = stream_get_by_id(stream_info.stream_id);
173af62f
DG
1330 if (!stream) {
1331 ret = -1;
7591bab1 1332 goto end;
173af62f 1333 }
77f7bd85
MD
1334
1335 /*
1336 * Set last_net_seq_num before the close flag. Required by data
1337 * pending check.
1338 */
7591bab1 1339 pthread_mutex_lock(&stream->lock);
5312a3ed 1340 stream->last_net_seq_num = stream_info.last_net_seq_num;
77f7bd85
MD
1341 pthread_mutex_unlock(&stream->lock);
1342
bda7c7b9
JG
1343 /*
1344 * This is one of the conditions which may trigger a stream close
1345 * with the others being:
1346 * 1) A close command is received for a stream
1347 * 2) The control connection owning the stream is closed
1348 * 3) We have received all of the stream's data _after_ a close
1349 * request.
1350 */
1351 try_stream_close(stream);
7591bab1
MD
1352 if (stream->is_metadata) {
1353 struct relay_viewer_stream *vstream;
173af62f 1354
7591bab1
MD
1355 vstream = viewer_stream_get_by_id(stream->stream_handle);
1356 if (vstream) {
1357 if (vstream->metadata_sent == stream->metadata_received) {
1358 /*
1359 * Since all the metadata has been sent to the
1360 * viewer and that we have a request to close
1361 * its stream, we can safely teardown the
1362 * corresponding metadata viewer stream.
1363 */
1364 viewer_stream_put(vstream);
1365 }
1366 /* Put local reference. */
1367 viewer_stream_put(vstream);
1368 }
1369 }
7591bab1 1370 stream_put(stream);
5312a3ed 1371 ret = 0;
173af62f 1372
7591bab1 1373end:
53efb85a 1374 memset(&reply, 0, sizeof(reply));
173af62f 1375 if (ret < 0) {
f73fabfd 1376 reply.ret_code = htobe32(LTTNG_ERR_UNK);
173af62f 1377 } else {
f73fabfd 1378 reply.ret_code = htobe32(LTTNG_OK);
173af62f 1379 }
58eb9381 1380 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
173af62f 1381 sizeof(struct lttcomm_relayd_generic_reply), 0);
5312a3ed
JG
1382 if (send_ret < (ssize_t) sizeof(reply)) {
1383 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1384 send_ret);
1385 ret = -1;
173af62f
DG
1386 }
1387
1388end_no_session:
1389 return ret;
1390}
1391
93ec662e
JD
1392/*
1393 * relay_reset_metadata: reset a metadata stream
1394 */
1395static
5312a3ed
JG
1396int relay_reset_metadata(const struct lttcomm_relayd_hdr *recv_hdr,
1397 struct relay_connection *conn,
1398 const struct lttng_buffer_view *payload)
93ec662e 1399{
5312a3ed
JG
1400 int ret;
1401 ssize_t send_ret;
93ec662e
JD
1402 struct relay_session *session = conn->session;
1403 struct lttcomm_relayd_reset_metadata stream_info;
1404 struct lttcomm_relayd_generic_reply reply;
1405 struct relay_stream *stream;
1406
1407 DBG("Reset metadata received");
1408
5312a3ed 1409 if (!session || !conn->version_check_done) {
93ec662e
JD
1410 ERR("Trying to reset a metadata stream before version check");
1411 ret = -1;
1412 goto end_no_session;
1413 }
1414
5312a3ed
JG
1415 if (payload->size < sizeof(stream_info)) {
1416 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1417 sizeof(stream_info), payload->size);
93ec662e
JD
1418 ret = -1;
1419 goto end_no_session;
1420 }
5312a3ed
JG
1421 memcpy(&stream_info, payload->data, sizeof(stream_info));
1422 stream_info.stream_id = be64toh(stream_info.stream_id);
1423 stream_info.version = be64toh(stream_info.version);
1424
1425 DBG("Update metadata to version %" PRIu64, stream_info.version);
93ec662e
JD
1426
1427 /* Unsupported for live sessions for now. */
1428 if (session->live_timer != 0) {
1429 ret = -1;
1430 goto end;
1431 }
1432
5312a3ed 1433 stream = stream_get_by_id(stream_info.stream_id);
93ec662e
JD
1434 if (!stream) {
1435 ret = -1;
1436 goto end;
1437 }
1438 pthread_mutex_lock(&stream->lock);
1439 if (!stream->is_metadata) {
1440 ret = -1;
1441 goto end_unlock;
1442 }
1443
1444 ret = utils_rotate_stream_file(stream->path_name, stream->channel_name,
1445 0, 0, -1, -1, stream->stream_fd->fd, NULL,
1446 &stream->stream_fd->fd);
1447 if (ret < 0) {
1448 ERR("Failed to rotate metadata file %s of channel %s",
1449 stream->path_name, stream->channel_name);
1450 goto end_unlock;
1451 }
1452
1453end_unlock:
1454 pthread_mutex_unlock(&stream->lock);
1455 stream_put(stream);
1456
1457end:
1458 memset(&reply, 0, sizeof(reply));
1459 if (ret < 0) {
1460 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1461 } else {
1462 reply.ret_code = htobe32(LTTNG_OK);
1463 }
1464 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1465 sizeof(struct lttcomm_relayd_generic_reply), 0);
5312a3ed
JG
1466 if (send_ret < (ssize_t) sizeof(reply)) {
1467 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1468 send_ret);
1469 ret = -1;
93ec662e
JD
1470 }
1471
1472end_no_session:
1473 return ret;
1474}
1475
b8aa1682
JD
1476/*
1477 * relay_unknown_command: send -1 if received unknown command
1478 */
7591bab1 1479static void relay_unknown_command(struct relay_connection *conn)
b8aa1682
JD
1480{
1481 struct lttcomm_relayd_generic_reply reply;
5312a3ed 1482 ssize_t send_ret;
b8aa1682 1483
53efb85a 1484 memset(&reply, 0, sizeof(reply));
f73fabfd 1485 reply.ret_code = htobe32(LTTNG_ERR_UNK);
5312a3ed
JG
1486 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1487 if (send_ret < sizeof(reply)) {
1488 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret);
b8aa1682
JD
1489 }
1490}
1491
1492/*
1493 * relay_start: send an acknowledgment to the client to tell if we are
1494 * ready to receive data. We are ready if a session is established.
1495 */
5312a3ed
JG
1496static int relay_start(const struct lttcomm_relayd_hdr *recv_hdr,
1497 struct relay_connection *conn,
1498 const struct lttng_buffer_view *payload)
b8aa1682 1499{
5312a3ed
JG
1500 int ret = 0;
1501 ssize_t send_ret;
b8aa1682 1502 struct lttcomm_relayd_generic_reply reply;
58eb9381 1503 struct relay_session *session = conn->session;
b8aa1682
JD
1504
1505 if (!session) {
1506 DBG("Trying to start the streaming without a session established");
f73fabfd 1507 ret = htobe32(LTTNG_ERR_UNK);
b8aa1682
JD
1508 }
1509
53efb85a 1510 memset(&reply, 0, sizeof(reply));
5312a3ed
JG
1511 reply.ret_code = htobe32(LTTNG_OK);
1512 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1513 sizeof(reply), 0);
1514 if (send_ret < (ssize_t) sizeof(reply)) {
1515 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1516 send_ret);
1517 ret = -1;
b8aa1682
JD
1518 }
1519
1520 return ret;
1521}
1522
1d4dfdef
DG
1523/*
1524 * Append padding to the file pointed by the file descriptor fd.
1525 */
1526static int write_padding_to_file(int fd, uint32_t size)
1527{
6cd525e8 1528 ssize_t ret = 0;
1d4dfdef
DG
1529 char *zeros;
1530
1531 if (size == 0) {
1532 goto end;
1533 }
1534
1535 zeros = zmalloc(size);
1536 if (zeros == NULL) {
1537 PERROR("zmalloc zeros for padding");
1538 ret = -1;
1539 goto end;
1540 }
1541
6cd525e8
MD
1542 ret = lttng_write(fd, zeros, size);
1543 if (ret < size) {
1d4dfdef
DG
1544 PERROR("write padding to file");
1545 }
1546
e986c7a1
DG
1547 free(zeros);
1548
1d4dfdef
DG
1549end:
1550 return ret;
1551}
1552
d3ecc550
JD
1553/*
1554 * Close the current index file if it is open, and create a new one.
1555 *
1556 * Return 0 on success, -1 on error.
1557 */
1558static
cb523e02
JG
1559int create_rotate_index_file(struct relay_stream *stream,
1560 const char *stream_path)
d3ecc550
JD
1561{
1562 int ret;
1563 uint32_t major, minor;
1564
1565 /* Put ref on previous index_file. */
1566 if (stream->index_file) {
1567 lttng_index_file_put(stream->index_file);
1568 stream->index_file = NULL;
1569 }
1570 major = stream->trace->session->major;
1571 minor = stream->trace->session->minor;
cb523e02 1572 stream->index_file = lttng_index_file_create(stream_path,
d3ecc550
JD
1573 stream->channel_name,
1574 -1, -1, stream->tracefile_size,
1575 tracefile_array_get_file_index_head(stream->tfa),
1576 lttng_to_index_major(major, minor),
1577 lttng_to_index_minor(major, minor));
1578 if (!stream->index_file) {
1579 ret = -1;
1580 goto end;
1581 }
1582
1583 ret = 0;
1584
1585end:
1586 return ret;
1587}
1588
1589static
c6db3843 1590int do_rotate_stream_data(struct relay_stream *stream)
d3ecc550
JD
1591{
1592 int ret;
1593
c6db3843
JG
1594 DBG("Rotating stream %" PRIu64 " data file",
1595 stream->stream_handle);
d3ecc550
JD
1596 /* Perform the stream rotation. */
1597 ret = utils_rotate_stream_file(stream->path_name,
1598 stream->channel_name, stream->tracefile_size,
1599 stream->tracefile_count, -1,
1600 -1, stream->stream_fd->fd,
1601 NULL, &stream->stream_fd->fd);
1602 if (ret < 0) {
1603 ERR("Rotating stream output file");
1604 goto end;
1605 }
1606 stream->tracefile_size_current = 0;
d3ecc550 1607 stream->pos_after_last_complete_data_index = 0;
c6db3843 1608 stream->data_rotated = true;
d3ecc550 1609
c6db3843
JG
1610 if (stream->data_rotated && stream->index_rotated) {
1611 /* Rotation completed; reset its state. */
1612 DBG("Rotation completed for stream %" PRIu64,
1613 stream->stream_handle);
1614 stream->rotate_at_seq_num = -1ULL;
1615 stream->data_rotated = false;
1616 stream->index_rotated = false;
1617 }
d3ecc550
JD
1618end:
1619 return ret;
1620}
1621
1622/*
1623 * If too much data has been written in a tracefile before we received the
1624 * rotation command, we have to move the excess data to the new tracefile and
1625 * perform the rotation. This can happen because the control and data
1626 * connections are separate, the indexes as well as the commands arrive from
1627 * the control connection and we have no control over the order so we could be
1628 * in a situation where too much data has been received on the data connection
c6db3843 1629 * before the rotation command on the control connection arrives.
d3ecc550
JD
1630 */
1631static
1632int rotate_truncate_stream(struct relay_stream *stream)
1633{
1634 int ret, new_fd;
a5df8828 1635 off_t lseek_ret;
d3ecc550
JD
1636 uint64_t diff, pos = 0;
1637 char buf[FILE_COPY_BUFFER_SIZE];
1638
1639 assert(!stream->is_metadata);
1640
1641 assert(stream->tracefile_size_current >
1642 stream->pos_after_last_complete_data_index);
1643 diff = stream->tracefile_size_current -
1644 stream->pos_after_last_complete_data_index;
1645
1646 /* Create the new tracefile. */
1647 new_fd = utils_create_stream_file(stream->path_name,
1648 stream->channel_name,
1649 stream->tracefile_size, stream->tracefile_count,
1650 /* uid */ -1, /* gid */ -1, /* suffix */ NULL);
1651 if (new_fd < 0) {
1652 ERR("Failed to create new stream file at path %s for channel %s",
1653 stream->path_name, stream->channel_name);
1654 ret = -1;
1655 goto end;
1656 }
1657
1658 /*
1659 * Rewind the current tracefile to the position at which the rotation
a9577b76 1660 * should have occurred.
d3ecc550 1661 */
a5df8828 1662 lseek_ret = lseek(stream->stream_fd->fd,
d3ecc550 1663 stream->pos_after_last_complete_data_index, SEEK_SET);
a5df8828 1664 if (lseek_ret < 0) {
d3ecc550 1665 PERROR("seek truncate stream");
a5df8828 1666 ret = -1;
d3ecc550
JD
1667 goto end;
1668 }
1669
1670 /* Move data from the old file to the new file. */
1671 while (pos < diff) {
1672 uint64_t count, bytes_left;
1673 ssize_t io_ret;
1674
1675 bytes_left = diff - pos;
1676 count = bytes_left > sizeof(buf) ? sizeof(buf) : bytes_left;
1677 assert(count <= SIZE_MAX);
1678
1679 io_ret = lttng_read(stream->stream_fd->fd, buf, count);
1680 if (io_ret < (ssize_t) count) {
1681 char error_string[256];
1682
1683 snprintf(error_string, sizeof(error_string),
1684 "Failed to read %" PRIu64 " bytes from fd %i in rotate_truncate_stream(), returned %zi",
1685 count, stream->stream_fd->fd, io_ret);
1686 if (io_ret == -1) {
1687 PERROR("%s", error_string);
1688 } else {
1689 ERR("%s", error_string);
1690 }
1691 ret = -1;
1692 goto end;
1693 }
1694
1695 io_ret = lttng_write(new_fd, buf, count);
1696 if (io_ret < (ssize_t) count) {
1697 char error_string[256];
1698
1699 snprintf(error_string, sizeof(error_string),
1700 "Failed to write %" PRIu64 " bytes from fd %i in rotate_truncate_stream(), returned %zi",
1701 count, new_fd, io_ret);
1702 if (io_ret == -1) {
1703 PERROR("%s", error_string);
1704 } else {
1705 ERR("%s", error_string);
1706 }
1707 ret = -1;
1708 goto end;
1709 }
1710
1711 pos += count;
1712 }
1713
1714 /* Truncate the file to get rid of the excess data. */
1715 ret = ftruncate(stream->stream_fd->fd,
1716 stream->pos_after_last_complete_data_index);
1717 if (ret) {
1718 PERROR("ftruncate");
1719 goto end;
1720 }
1721
1722 ret = close(stream->stream_fd->fd);
1723 if (ret < 0) {
1724 PERROR("Closing tracefile");
1725 goto end;
1726 }
1727
d3ecc550
JD
1728 /*
1729 * Update the offset and FD of all the eventual indexes created by the
1730 * data connection before the rotation command arrived.
1731 */
1732 ret = relay_index_switch_all_files(stream);
1733 if (ret < 0) {
1734 ERR("Failed to rotate index file");
1735 goto end;
1736 }
1737
1738 stream->stream_fd->fd = new_fd;
1739 stream->tracefile_size_current = diff;
1740 stream->pos_after_last_complete_data_index = 0;
1741 stream->rotate_at_seq_num = -1ULL;
1742
1743 ret = 0;
1744
1745end:
1746 return ret;
1747}
1748
1749/*
c6db3843 1750 * Check if a stream's index file should be rotated (for session rotation).
d3ecc550
JD
1751 * Must be called with the stream lock held.
1752 *
1753 * Return 0 on success, a negative value on error.
1754 */
1755static
c6db3843 1756int try_rotate_stream_index(struct relay_stream *stream)
d3ecc550
JD
1757{
1758 int ret = 0;
1759
d3ecc550 1760 if (stream->rotate_at_seq_num == -1ULL) {
c6db3843 1761 /* No rotation expected. */
d3ecc550
JD
1762 goto end;
1763 }
1764
c6db3843
JG
1765 if (stream->index_rotated) {
1766 /* Rotation of the index has already occurred. */
1767 goto end;
1768 }
1769
1770 if (stream->prev_index_seq == -1ULL ||
1771 stream->prev_index_seq < stream->rotate_at_seq_num) {
1772 DBG("Stream %" PRIu64 " index not yet ready for rotation (rotate_at_seq_num = %" PRIu64 ", prev_index_seq = %" PRIu64 ")",
1773 stream->stream_handle,
1774 stream->rotate_at_seq_num,
1775 stream->prev_index_seq);
1776 goto end;
1777 } else if (stream->prev_index_seq != stream->rotate_at_seq_num) {
1778 /*
1779 * Unexpected, protocol error/bug.
1780 * It could mean that we received a rotation position
1781 * that is in the past.
1782 */
1783 ERR("Stream %" PRIu64 " index is in an inconsistent state (rotate_at_seq_num = %" PRIu64 ", prev_data_seq = %" PRIu64 ", prev_index_seq = %" PRIu64 ")",
c64c70f5
JG
1784 stream->stream_handle,
1785 stream->rotate_at_seq_num,
a8f9f353 1786 stream->prev_data_seq,
c64c70f5 1787 stream->prev_index_seq);
c6db3843
JG
1788 ret = -1;
1789 goto end;
1790 } else {
1791 DBG("Rotating stream %" PRIu64 " index file",
1792 stream->stream_handle);
1793 ret = create_rotate_index_file(stream, stream->path_name);
1794 stream->index_rotated = true;
1795
1796 if (stream->data_rotated && stream->index_rotated) {
1797 /* Rotation completed; reset its state. */
1798 DBG("Rotation completed for stream %" PRIu64,
1799 stream->stream_handle);
1800 stream->rotate_at_seq_num = -1ULL;
1801 stream->data_rotated = false;
1802 stream->index_rotated = false;
1803 }
1804 }
1805
1806end:
1807 return ret;
1808}
1809
1810/*
1811 * Check if a stream's data file (as opposed to index) should be rotated
1812 * (for session rotation).
1813 * Must be called with the stream lock held.
1814 *
1815 * Return 0 on success, a negative value on error.
1816 */
1817static
1818int try_rotate_stream_data(struct relay_stream *stream)
1819{
1820 int ret = 0;
1821
1822 if (stream->rotate_at_seq_num == -1ULL) {
1823 /* No rotation expected. */
1824 goto end;
1825 }
1826
1827 if (stream->data_rotated) {
1828 /* Rotation of the data file has already occurred. */
1829 goto end;
1830 }
1831
1832 if (stream->prev_data_seq == -1ULL ||
1833 stream->prev_data_seq < stream->rotate_at_seq_num) {
1834 DBG("Stream %" PRIu64 " not yet ready for rotation (rotate_at_seq_num = %" PRIu64 ", prev_data_seq = %" PRIu64 ")",
1835 stream->stream_handle,
1836 stream->rotate_at_seq_num,
1837 stream->prev_data_seq);
d3ecc550 1838 goto end;
a8f9f353 1839 } else if (stream->prev_data_seq > stream->rotate_at_seq_num) {
c64c70f5 1840 /*
a8f9f353 1841 * prev_data_seq is checked here since indexes and rotation
c64c70f5
JG
1842 * commands are serialized with respect to each other.
1843 */
d3ecc550
JD
1844 DBG("Rotation after too much data has been written in tracefile "
1845 "for stream %" PRIu64 ", need to truncate before "
1846 "rotating", stream->stream_handle);
1847 ret = rotate_truncate_stream(stream);
1848 if (ret) {
1849 ERR("Failed to truncate stream");
1850 goto end;
1851 }
c6db3843
JG
1852 } else if (stream->prev_data_seq != stream->rotate_at_seq_num) {
1853 /*
1854 * Unexpected, protocol error/bug.
1855 * It could mean that we received a rotation position
1856 * that is in the past.
1857 */
1858 ERR("Stream %" PRIu64 " data is in an inconsistent state (rotate_at_seq_num = %" PRIu64 ", prev_data_seq = %" PRIu64 ")",
c64c70f5
JG
1859 stream->stream_handle,
1860 stream->rotate_at_seq_num,
c6db3843
JG
1861 stream->prev_data_seq);
1862 ret = -1;
1863 goto end;
1864 } else {
1865 ret = do_rotate_stream_data(stream);
d3ecc550
JD
1866 }
1867
1868end:
1869 return ret;
1870}
1871
b8aa1682 1872/*
7591bab1 1873 * relay_recv_metadata: receive the metadata for the session.
b8aa1682 1874 */
5312a3ed
JG
1875static int relay_recv_metadata(const struct lttcomm_relayd_hdr *recv_hdr,
1876 struct relay_connection *conn,
1877 const struct lttng_buffer_view *payload)
b8aa1682 1878{
32d1569c 1879 int ret = 0;
6cd525e8 1880 ssize_t size_ret;
58eb9381 1881 struct relay_session *session = conn->session;
5312a3ed 1882 struct lttcomm_relayd_metadata_payload metadata_payload_header;
b8aa1682 1883 struct relay_stream *metadata_stream;
5312a3ed 1884 uint64_t metadata_payload_size;
b8aa1682
JD
1885
1886 if (!session) {
1887 ERR("Metadata sent before version check");
1888 ret = -1;
1889 goto end;
1890 }
1891
5312a3ed 1892 if (recv_hdr->data_size < sizeof(struct lttcomm_relayd_metadata_payload)) {
f6416125
MD
1893 ERR("Incorrect data size");
1894 ret = -1;
1895 goto end;
1896 }
5312a3ed
JG
1897 metadata_payload_size = recv_hdr->data_size -
1898 sizeof(struct lttcomm_relayd_metadata_payload);
f6416125 1899
5312a3ed
JG
1900 memcpy(&metadata_payload_header, payload->data,
1901 sizeof(metadata_payload_header));
1902 metadata_payload_header.stream_id = be64toh(
1903 metadata_payload_header.stream_id);
1904 metadata_payload_header.padding_size = be32toh(
1905 metadata_payload_header.padding_size);
9d1bbf21 1906
5312a3ed 1907 metadata_stream = stream_get_by_id(metadata_payload_header.stream_id);
b8aa1682
JD
1908 if (!metadata_stream) {
1909 ret = -1;
7591bab1 1910 goto end;
b8aa1682
JD
1911 }
1912
7591bab1
MD
1913 pthread_mutex_lock(&metadata_stream->lock);
1914
5312a3ed
JG
1915 size_ret = lttng_write(metadata_stream->stream_fd->fd,
1916 payload->data + sizeof(metadata_payload_header),
1917 metadata_payload_size);
1918 if (size_ret < metadata_payload_size) {
b8aa1682
JD
1919 ERR("Relay error writing metadata on file");
1920 ret = -1;
7591bab1 1921 goto end_put;
b8aa1682 1922 }
1d4dfdef 1923
32d1569c 1924 size_ret = write_padding_to_file(metadata_stream->stream_fd->fd,
5312a3ed 1925 metadata_payload_header.padding_size);
715e6fb1 1926 if (size_ret < (int64_t) metadata_payload_header.padding_size) {
5312a3ed 1927 ret = -1;
7591bab1 1928 goto end_put;
1d4dfdef 1929 }
2a174661 1930
7591bab1 1931 metadata_stream->metadata_received +=
5312a3ed 1932 metadata_payload_size + metadata_payload_header.padding_size;
7591bab1
MD
1933 DBG2("Relay metadata written. Updated metadata_received %" PRIu64,
1934 metadata_stream->metadata_received);
1d4dfdef 1935
c6db3843 1936 ret = try_rotate_stream_data(metadata_stream);
d3ecc550
JD
1937 if (ret < 0) {
1938 goto end_put;
1939 }
1940
7591bab1
MD
1941end_put:
1942 pthread_mutex_unlock(&metadata_stream->lock);
1943 stream_put(metadata_stream);
b8aa1682
JD
1944end:
1945 return ret;
1946}
1947
1948/*
1949 * relay_send_version: send relayd version number
1950 */
5312a3ed
JG
1951static int relay_send_version(const struct lttcomm_relayd_hdr *recv_hdr,
1952 struct relay_connection *conn,
1953 const struct lttng_buffer_view *payload)
b8aa1682 1954{
7f51dcba 1955 int ret;
5312a3ed 1956 ssize_t send_ret;
092b6259 1957 struct lttcomm_relayd_version reply, msg;
87cb6359 1958 bool compatible = true;
b8aa1682 1959
5312a3ed 1960 conn->version_check_done = true;
b8aa1682 1961
092b6259 1962 /* Get version from the other side. */
5312a3ed
JG
1963 if (payload->size < sizeof(msg)) {
1964 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1965 sizeof(msg), payload->size);
092b6259 1966 ret = -1;
092b6259
DG
1967 goto end;
1968 }
1969
5312a3ed
JG
1970 memcpy(&msg, payload->data, sizeof(msg));
1971 msg.major = be32toh(msg.major);
1972 msg.minor = be32toh(msg.minor);
1973
53efb85a 1974 memset(&reply, 0, sizeof(reply));
d83a952c
MD
1975 reply.major = RELAYD_VERSION_COMM_MAJOR;
1976 reply.minor = RELAYD_VERSION_COMM_MINOR;
d4519fa3
JD
1977
1978 /* Major versions must be the same */
5312a3ed 1979 if (reply.major != msg.major) {
6151a90f 1980 DBG("Incompatible major versions (%u vs %u), deleting session",
5312a3ed 1981 reply.major, msg.major);
87cb6359 1982 compatible = false;
d4519fa3
JD
1983 }
1984
58eb9381 1985 conn->major = reply.major;
0f907de1 1986 /* We adapt to the lowest compatible version */
5312a3ed 1987 if (reply.minor <= msg.minor) {
58eb9381 1988 conn->minor = reply.minor;
0f907de1 1989 } else {
5312a3ed 1990 conn->minor = msg.minor;
0f907de1
JD
1991 }
1992
6151a90f
JD
1993 reply.major = htobe32(reply.major);
1994 reply.minor = htobe32(reply.minor);
5312a3ed
JG
1995 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1996 sizeof(reply), 0);
1997 if (send_ret < (ssize_t) sizeof(reply)) {
1998 ERR("Failed to send \"send version\" command reply (ret = %zd)",
1999 send_ret);
2000 ret = -1;
2001 goto end;
2002 } else {
2003 ret = 0;
6151a90f
JD
2004 }
2005
87cb6359
JD
2006 if (!compatible) {
2007 ret = -1;
2008 goto end;
2009 }
2010
58eb9381
DG
2011 DBG("Version check done using protocol %u.%u", conn->major,
2012 conn->minor);
b8aa1682
JD
2013
2014end:
2015 return ret;
2016}
2017
c8f59ee5 2018/*
6d805429 2019 * Check for data pending for a given stream id from the session daemon.
c8f59ee5 2020 */
5312a3ed
JG
2021static int relay_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
2022 struct relay_connection *conn,
2023 const struct lttng_buffer_view *payload)
c8f59ee5 2024{
58eb9381 2025 struct relay_session *session = conn->session;
6d805429 2026 struct lttcomm_relayd_data_pending msg;
c8f59ee5
DG
2027 struct lttcomm_relayd_generic_reply reply;
2028 struct relay_stream *stream;
5312a3ed 2029 ssize_t send_ret;
c8f59ee5 2030 int ret;
298a25ca 2031 uint64_t stream_seq;
c8f59ee5 2032
6d805429 2033 DBG("Data pending command received");
c8f59ee5 2034
5312a3ed 2035 if (!session || !conn->version_check_done) {
c8f59ee5
DG
2036 ERR("Trying to check for data before version check");
2037 ret = -1;
2038 goto end_no_session;
2039 }
2040
5312a3ed
JG
2041 if (payload->size < sizeof(msg)) {
2042 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
2043 sizeof(msg), payload->size);
c8f59ee5
DG
2044 ret = -1;
2045 goto end_no_session;
2046 }
5312a3ed
JG
2047 memcpy(&msg, payload->data, sizeof(msg));
2048 msg.stream_id = be64toh(msg.stream_id);
2049 msg.last_net_seq_num = be64toh(msg.last_net_seq_num);
c8f59ee5 2050
5312a3ed 2051 stream = stream_get_by_id(msg.stream_id);
de91f48a 2052 if (stream == NULL) {
c8f59ee5 2053 ret = -1;
7591bab1 2054 goto end;
c8f59ee5
DG
2055 }
2056
7591bab1
MD
2057 pthread_mutex_lock(&stream->lock);
2058
298a25ca
JG
2059 if (session_streams_have_index(session)) {
2060 /*
2061 * Ensure that both the index and stream data have been
2062 * flushed up to the requested point.
2063 */
a8f9f353 2064 stream_seq = min(stream->prev_data_seq, stream->prev_index_seq);
298a25ca 2065 } else {
a8f9f353 2066 stream_seq = stream->prev_data_seq;
298a25ca 2067 }
a8f9f353 2068 DBG("Data pending for stream id %" PRIu64 ": prev_data_seq %" PRIu64
298a25ca
JG
2069 ", prev_index_seq %" PRIu64
2070 ", and last_seq %" PRIu64, msg.stream_id,
a8f9f353 2071 stream->prev_data_seq, stream->prev_index_seq,
298a25ca 2072 msg.last_net_seq_num);
c8f59ee5 2073
33832e64 2074 /* Avoid wrapping issue */
298a25ca 2075 if (((int64_t) (stream_seq - msg.last_net_seq_num)) >= 0) {
6d805429 2076 /* Data has in fact been written and is NOT pending */
c8f59ee5 2077 ret = 0;
6d805429
DG
2078 } else {
2079 /* Data still being streamed thus pending */
2080 ret = 1;
c8f59ee5
DG
2081 }
2082
7591bab1
MD
2083 stream->data_pending_check_done = true;
2084 pthread_mutex_unlock(&stream->lock);
f7079f67 2085
7591bab1
MD
2086 stream_put(stream);
2087end:
c8f59ee5 2088
53efb85a 2089 memset(&reply, 0, sizeof(reply));
c8f59ee5 2090 reply.ret_code = htobe32(ret);
5312a3ed
JG
2091 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2092 if (send_ret < (ssize_t) sizeof(reply)) {
2093 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
2094 send_ret);
2095 ret = -1;
c8f59ee5
DG
2096 }
2097
2098end_no_session:
2099 return ret;
2100}
2101
2102/*
2103 * Wait for the control socket to reach a quiescent state.
2104 *
7591bab1
MD
2105 * Note that for now, when receiving this command from the session
2106 * daemon, this means that every subsequent commands or data received on
2107 * the control socket has been handled. So, this is why we simply return
2108 * OK here.
c8f59ee5 2109 */
5312a3ed
JG
2110static int relay_quiescent_control(const struct lttcomm_relayd_hdr *recv_hdr,
2111 struct relay_connection *conn,
2112 const struct lttng_buffer_view *payload)
c8f59ee5
DG
2113{
2114 int ret;
5312a3ed 2115 ssize_t send_ret;
ad7051c0 2116 struct relay_stream *stream;
ad7051c0 2117 struct lttcomm_relayd_quiescent_control msg;
c8f59ee5
DG
2118 struct lttcomm_relayd_generic_reply reply;
2119
2120 DBG("Checking quiescent state on control socket");
2121
5312a3ed 2122 if (!conn->session || !conn->version_check_done) {
ad7051c0
DG
2123 ERR("Trying to check for data before version check");
2124 ret = -1;
2125 goto end_no_session;
2126 }
2127
5312a3ed
JG
2128 if (payload->size < sizeof(msg)) {
2129 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2130 sizeof(msg), payload->size);
ad7051c0
DG
2131 ret = -1;
2132 goto end_no_session;
2133 }
5312a3ed
JG
2134 memcpy(&msg, payload->data, sizeof(msg));
2135 msg.stream_id = be64toh(msg.stream_id);
ad7051c0 2136
5312a3ed 2137 stream = stream_get_by_id(msg.stream_id);
7591bab1
MD
2138 if (!stream) {
2139 goto reply;
2140 }
2141 pthread_mutex_lock(&stream->lock);
2142 stream->data_pending_check_done = true;
2143 pthread_mutex_unlock(&stream->lock);
5312a3ed
JG
2144
2145 DBG("Relay quiescent control pending flag set to %" PRIu64, msg.stream_id);
7591bab1
MD
2146 stream_put(stream);
2147reply:
53efb85a 2148 memset(&reply, 0, sizeof(reply));
c8f59ee5 2149 reply.ret_code = htobe32(LTTNG_OK);
5312a3ed
JG
2150 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2151 if (send_ret < (ssize_t) sizeof(reply)) {
2152 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
2153 send_ret);
2154 ret = -1;
2155 } else {
2156 ret = 0;
c8f59ee5
DG
2157 }
2158
ad7051c0 2159end_no_session:
c8f59ee5
DG
2160 return ret;
2161}
2162
f7079f67 2163/*
7591bab1
MD
2164 * Initialize a data pending command. This means that a consumer is about
2165 * to ask for data pending for each stream it holds. Simply iterate over
2166 * all streams of a session and set the data_pending_check_done flag.
f7079f67
DG
2167 *
2168 * This command returns to the client a LTTNG_OK code.
2169 */
5312a3ed
JG
2170static int relay_begin_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
2171 struct relay_connection *conn,
2172 const struct lttng_buffer_view *payload)
f7079f67
DG
2173{
2174 int ret;
5312a3ed 2175 ssize_t send_ret;
f7079f67
DG
2176 struct lttng_ht_iter iter;
2177 struct lttcomm_relayd_begin_data_pending msg;
2178 struct lttcomm_relayd_generic_reply reply;
2179 struct relay_stream *stream;
f7079f67
DG
2180
2181 assert(recv_hdr);
58eb9381 2182 assert(conn);
f7079f67
DG
2183
2184 DBG("Init streams for data pending");
2185
5312a3ed 2186 if (!conn->session || !conn->version_check_done) {
f7079f67
DG
2187 ERR("Trying to check for data before version check");
2188 ret = -1;
2189 goto end_no_session;
2190 }
2191
5312a3ed
JG
2192 if (payload->size < sizeof(msg)) {
2193 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2194 sizeof(msg), payload->size);
f7079f67
DG
2195 ret = -1;
2196 goto end_no_session;
2197 }
5312a3ed
JG
2198 memcpy(&msg, payload->data, sizeof(msg));
2199 msg.session_id = be64toh(msg.session_id);
f7079f67
DG
2200
2201 /*
7591bab1
MD
2202 * Iterate over all streams to set the begin data pending flag.
2203 * For now, the streams are indexed by stream handle so we have
2204 * to iterate over all streams to find the one associated with
2205 * the right session_id.
f7079f67
DG
2206 */
2207 rcu_read_lock();
d3e2ba59 2208 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2a174661 2209 node.node) {
7591bab1
MD
2210 if (!stream_get(stream)) {
2211 continue;
2212 }
5312a3ed 2213 if (stream->trace->session->id == msg.session_id) {
7591bab1
MD
2214 pthread_mutex_lock(&stream->lock);
2215 stream->data_pending_check_done = false;
2216 pthread_mutex_unlock(&stream->lock);
f7079f67
DG
2217 DBG("Set begin data pending flag to stream %" PRIu64,
2218 stream->stream_handle);
2219 }
7591bab1 2220 stream_put(stream);
f7079f67
DG
2221 }
2222 rcu_read_unlock();
2223
53efb85a 2224 memset(&reply, 0, sizeof(reply));
f7079f67
DG
2225 /* All good, send back reply. */
2226 reply.ret_code = htobe32(LTTNG_OK);
2227
5312a3ed
JG
2228 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2229 if (send_ret < (ssize_t) sizeof(reply)) {
2230 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2231 send_ret);
2232 ret = -1;
2233 } else {
2234 ret = 0;
f7079f67
DG
2235 }
2236
2237end_no_session:
2238 return ret;
2239}
2240
2241/*
7591bab1
MD
2242 * End data pending command. This will check, for a given session id, if
2243 * each stream associated with it has its data_pending_check_done flag
2244 * set. If not, this means that the client lost track of the stream but
2245 * the data is still being streamed on our side. In this case, we inform
2246 * the client that data is in flight.
f7079f67
DG
2247 *
2248 * Return to the client if there is data in flight or not with a ret_code.
2249 */
5312a3ed
JG
2250static int relay_end_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
2251 struct relay_connection *conn,
2252 const struct lttng_buffer_view *payload)
f7079f67
DG
2253{
2254 int ret;
5312a3ed 2255 ssize_t send_ret;
f7079f67
DG
2256 struct lttng_ht_iter iter;
2257 struct lttcomm_relayd_end_data_pending msg;
2258 struct lttcomm_relayd_generic_reply reply;
2259 struct relay_stream *stream;
f7079f67
DG
2260 uint32_t is_data_inflight = 0;
2261
f7079f67
DG
2262 DBG("End data pending command");
2263
5312a3ed 2264 if (!conn->session || !conn->version_check_done) {
f7079f67
DG
2265 ERR("Trying to check for data before version check");
2266 ret = -1;
2267 goto end_no_session;
2268 }
2269
5312a3ed
JG
2270 if (payload->size < sizeof(msg)) {
2271 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2272 sizeof(msg), payload->size);
f7079f67
DG
2273 ret = -1;
2274 goto end_no_session;
2275 }
5312a3ed
JG
2276 memcpy(&msg, payload->data, sizeof(msg));
2277 msg.session_id = be64toh(msg.session_id);
f7079f67 2278
7591bab1
MD
2279 /*
2280 * Iterate over all streams to see if the begin data pending
2281 * flag is set.
2282 */
f7079f67 2283 rcu_read_lock();
d3e2ba59 2284 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2a174661 2285 node.node) {
7591bab1
MD
2286 if (!stream_get(stream)) {
2287 continue;
2288 }
5312a3ed 2289 if (stream->trace->session->id != msg.session_id) {
7591bab1
MD
2290 stream_put(stream);
2291 continue;
2292 }
2293 pthread_mutex_lock(&stream->lock);
2294 if (!stream->data_pending_check_done) {
298a25ca
JG
2295 uint64_t stream_seq;
2296
2297 if (session_streams_have_index(conn->session)) {
2298 /*
2299 * Ensure that both the index and stream data have been
2300 * flushed up to the requested point.
2301 */
a8f9f353 2302 stream_seq = min(stream->prev_data_seq, stream->prev_index_seq);
298a25ca 2303 } else {
a8f9f353 2304 stream_seq = stream->prev_data_seq;
298a25ca
JG
2305 }
2306 if (!stream->closed || !(((int64_t) (stream_seq - stream->last_net_seq_num)) >= 0)) {
7591bab1
MD
2307 is_data_inflight = 1;
2308 DBG("Data is still in flight for stream %" PRIu64,
2309 stream->stream_handle);
2310 pthread_mutex_unlock(&stream->lock);
2311 stream_put(stream);
2312 break;
2313 }
f7079f67 2314 }
7591bab1
MD
2315 pthread_mutex_unlock(&stream->lock);
2316 stream_put(stream);
f7079f67
DG
2317 }
2318 rcu_read_unlock();
2319
53efb85a 2320 memset(&reply, 0, sizeof(reply));
f7079f67
DG
2321 /* All good, send back reply. */
2322 reply.ret_code = htobe32(is_data_inflight);
2323
5312a3ed
JG
2324 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2325 if (send_ret < (ssize_t) sizeof(reply)) {
2326 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2327 send_ret);
2328 ret = -1;
2329 } else {
2330 ret = 0;
f7079f67
DG
2331 }
2332
2333end_no_session:
2334 return ret;
2335}
2336
1c20f0e2
JD
2337/*
2338 * Receive an index for a specific stream.
2339 *
2340 * Return 0 on success else a negative value.
2341 */
5312a3ed
JG
2342static int relay_recv_index(const struct lttcomm_relayd_hdr *recv_hdr,
2343 struct relay_connection *conn,
2344 const struct lttng_buffer_view *payload)
1c20f0e2 2345{
5312a3ed
JG
2346 int ret;
2347 ssize_t send_ret;
58eb9381 2348 struct relay_session *session = conn->session;
1c20f0e2 2349 struct lttcomm_relayd_index index_info;
7591bab1 2350 struct relay_index *index;
1c20f0e2
JD
2351 struct lttcomm_relayd_generic_reply reply;
2352 struct relay_stream *stream;
f8f3885c 2353 size_t msg_len;
1c20f0e2 2354
58eb9381 2355 assert(conn);
1c20f0e2
JD
2356
2357 DBG("Relay receiving index");
2358
5312a3ed 2359 if (!session || !conn->version_check_done) {
1c20f0e2
JD
2360 ERR("Trying to close a stream before version check");
2361 ret = -1;
2362 goto end_no_session;
2363 }
2364
f8f3885c
MD
2365 msg_len = lttcomm_relayd_index_len(
2366 lttng_to_index_major(conn->major, conn->minor),
2367 lttng_to_index_minor(conn->major, conn->minor));
5312a3ed
JG
2368 if (payload->size < msg_len) {
2369 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2370 msg_len, payload->size);
1c20f0e2
JD
2371 ret = -1;
2372 goto end_no_session;
2373 }
5312a3ed
JG
2374 memcpy(&index_info, payload->data, msg_len);
2375 index_info.relay_stream_id = be64toh(index_info.relay_stream_id);
2376 index_info.net_seq_num = be64toh(index_info.net_seq_num);
2377 index_info.packet_size = be64toh(index_info.packet_size);
2378 index_info.content_size = be64toh(index_info.content_size);
2379 index_info.timestamp_begin = be64toh(index_info.timestamp_begin);
2380 index_info.timestamp_end = be64toh(index_info.timestamp_end);
2381 index_info.events_discarded = be64toh(index_info.events_discarded);
2382 index_info.stream_id = be64toh(index_info.stream_id);
81df238b
JR
2383
2384 if (conn->minor >= 8) {
2385 index_info.stream_instance_id =
2386 be64toh(index_info.stream_instance_id);
2387 index_info.packet_seq_num = be64toh(index_info.packet_seq_num);
2388 }
5312a3ed
JG
2389
2390 stream = stream_get_by_id(index_info.relay_stream_id);
1c20f0e2 2391 if (!stream) {
7591bab1 2392 ERR("stream_get_by_id not found");
1c20f0e2 2393 ret = -1;
7591bab1 2394 goto end;
1c20f0e2 2395 }
7591bab1 2396 pthread_mutex_lock(&stream->lock);
1c20f0e2 2397
d3e2ba59
JD
2398 /* Live beacon handling */
2399 if (index_info.packet_size == 0) {
7591bab1
MD
2400 DBG("Received live beacon for stream %" PRIu64,
2401 stream->stream_handle);
d3e2ba59
JD
2402
2403 /*
7591bab1
MD
2404 * Only flag a stream inactive when it has already
2405 * received data and no indexes are in flight.
d3e2ba59 2406 */
a44ca2ca 2407 if (stream->index_received_seqcount > 0
7591bab1 2408 && stream->indexes_in_flight == 0) {
5312a3ed 2409 stream->beacon_ts_end = index_info.timestamp_end;
d3e2ba59
JD
2410 }
2411 ret = 0;
7591bab1 2412 goto end_stream_put;
d3e2ba59
JD
2413 } else {
2414 stream->beacon_ts_end = -1ULL;
2415 }
2416
528f2ffa 2417 if (stream->ctf_stream_id == -1ULL) {
5312a3ed 2418 stream->ctf_stream_id = index_info.stream_id;
528f2ffa 2419 }
5312a3ed 2420 index = relay_index_get_by_id_or_create(stream, index_info.net_seq_num);
7591bab1
MD
2421 if (!index) {
2422 ret = -1;
2423 ERR("relay_index_get_by_id_or_create index NULL");
2424 goto end_stream_put;
1c20f0e2 2425 }
234cd636 2426 if (set_index_control_data(index, &index_info, conn)) {
7591bab1
MD
2427 ERR("set_index_control_data error");
2428 relay_index_put(index);
2429 ret = -1;
2430 goto end_stream_put;
2431 }
2432 ret = relay_index_try_flush(index);
2433 if (ret == 0) {
a44ca2ca
MD
2434 tracefile_array_commit_seq(stream->tfa);
2435 stream->index_received_seqcount++;
d3ecc550 2436 stream->pos_after_last_complete_data_index += index->total_size;
7a45c7e6 2437 stream->prev_index_seq = index_info.net_seq_num;
c6db3843
JG
2438
2439 ret = try_rotate_stream_index(stream);
2440 if (ret < 0) {
2441 goto end_stream_put;
2442 }
7591bab1
MD
2443 } else if (ret > 0) {
2444 /* no flush. */
2445 ret = 0;
2446 } else {
245f8bec
JR
2447 /*
2448 * ret < 0
2449 *
2450 * relay_index_try_flush is responsible for the self-reference
2451 * put of the index object on error.
2452 */
7591bab1 2453 ERR("relay_index_try_flush error %d", ret);
7591bab1 2454 ret = -1;
1c20f0e2
JD
2455 }
2456
7591bab1
MD
2457end_stream_put:
2458 pthread_mutex_unlock(&stream->lock);
2459 stream_put(stream);
2460
2461end:
1c20f0e2 2462
53efb85a 2463 memset(&reply, 0, sizeof(reply));
1c20f0e2
JD
2464 if (ret < 0) {
2465 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2466 } else {
2467 reply.ret_code = htobe32(LTTNG_OK);
2468 }
58eb9381 2469 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
5312a3ed
JG
2470 if (send_ret < (ssize_t) sizeof(reply)) {
2471 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret);
2472 ret = -1;
1c20f0e2
JD
2473 }
2474
2475end_no_session:
2476 return ret;
2477}
2478
a4baae1b
JD
2479/*
2480 * Receive the streams_sent message.
2481 *
2482 * Return 0 on success else a negative value.
2483 */
5312a3ed
JG
2484static int relay_streams_sent(const struct lttcomm_relayd_hdr *recv_hdr,
2485 struct relay_connection *conn,
2486 const struct lttng_buffer_view *payload)
a4baae1b 2487{
5312a3ed
JG
2488 int ret;
2489 ssize_t send_ret;
a4baae1b
JD
2490 struct lttcomm_relayd_generic_reply reply;
2491
58eb9381 2492 assert(conn);
a4baae1b
JD
2493
2494 DBG("Relay receiving streams_sent");
2495
5312a3ed 2496 if (!conn->session || !conn->version_check_done) {
a4baae1b
JD
2497 ERR("Trying to close a stream before version check");
2498 ret = -1;
2499 goto end_no_session;
2500 }
2501
2502 /*
7591bab1
MD
2503 * Publish every pending stream in the connection recv list which are
2504 * now ready to be used by the viewer.
4a9daf17 2505 */
7591bab1 2506 publish_connection_local_streams(conn);
4a9daf17 2507
53efb85a 2508 memset(&reply, 0, sizeof(reply));
a4baae1b 2509 reply.ret_code = htobe32(LTTNG_OK);
58eb9381 2510 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
5312a3ed
JG
2511 if (send_ret < (ssize_t) sizeof(reply)) {
2512 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2513 send_ret);
2514 ret = -1;
a4baae1b
JD
2515 } else {
2516 /* Success. */
2517 ret = 0;
2518 }
2519
2520end_no_session:
2521 return ret;
2522}
2523
d3ecc550 2524/*
5312a3ed 2525 * relay_rotate_session_stream: rotate a stream to a new tracefile for the session
d3ecc550
JD
2526 * rotation feature (not the tracefile rotation feature).
2527 */
5312a3ed
JG
2528static int relay_rotate_session_stream(const struct lttcomm_relayd_hdr *recv_hdr,
2529 struct relay_connection *conn,
2530 const struct lttng_buffer_view *payload)
d3ecc550 2531{
5312a3ed
JG
2532 int ret;
2533 ssize_t send_ret;
d3ecc550
JD
2534 struct relay_session *session = conn->session;
2535 struct lttcomm_relayd_rotate_stream stream_info;
2536 struct lttcomm_relayd_generic_reply reply;
2537 struct relay_stream *stream;
5312a3ed
JG
2538 size_t header_len;
2539 size_t path_len;
2540 struct lttng_buffer_view new_path_view;
d3ecc550
JD
2541
2542 DBG("Rotate stream received");
2543
2544 if (!session || !conn->version_check_done) {
2545 ERR("Trying to rotate a stream before version check");
2546 ret = -1;
2547 goto end_no_reply;
2548 }
2549
2550 if (session->major == 2 && session->minor < 11) {
2551 ERR("Unsupported feature before 2.11");
2552 ret = -1;
2553 goto end_no_reply;
2554 }
2555
5312a3ed 2556 header_len = sizeof(struct lttcomm_relayd_rotate_stream);
d3ecc550 2557
5312a3ed
JG
2558 if (payload->size < header_len) {
2559 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2560 header_len, payload->size);
d3ecc550
JD
2561 ret = -1;
2562 goto end_no_reply;
2563 }
2564
5312a3ed
JG
2565 memcpy(&stream_info, payload->data, header_len);
2566
2567 /* Convert to host */
2568 stream_info.pathname_length = be32toh(stream_info.pathname_length);
2569 stream_info.stream_id = be64toh(stream_info.stream_id);
2570 stream_info.new_chunk_id = be64toh(stream_info.new_chunk_id);
2571 stream_info.rotate_at_seq_num = be64toh(stream_info.rotate_at_seq_num);
d3ecc550 2572
5312a3ed
JG
2573 path_len = stream_info.pathname_length;
2574 if (payload->size < header_len + path_len) {
2575 ERR("Unexpected payload size in \"relay_rotate_session_stream\" including path: expected >= %zu bytes, got %zu bytes",
2576 header_len + path_len, payload->size);
2577 ret = -1;
2578 goto end_no_reply;
2579 }
2580
d3ecc550 2581 /* Ensure it fits in local filename length. */
5312a3ed 2582 if (path_len >= LTTNG_PATH_MAX) {
d3ecc550
JD
2583 ret = -ENAMETOOLONG;
2584 ERR("Length of relay_rotate_session_stream command's path name (%zu bytes) exceeds the maximal allowed length of %i bytes",
5312a3ed 2585 path_len, LTTNG_PATH_MAX);
d3ecc550
JD
2586 goto end;
2587 }
2588
5312a3ed
JG
2589 new_path_view = lttng_buffer_view_from_view(payload, header_len,
2590 stream_info.pathname_length);
d3ecc550 2591
5312a3ed
JG
2592 stream = stream_get_by_id(stream_info.stream_id);
2593 if (!stream) {
d3ecc550 2594 ret = -1;
5312a3ed 2595 goto end;
d3ecc550
JD
2596 }
2597
2598 pthread_mutex_lock(&stream->lock);
2599
2600 /*
2601 * Update the trace path (just the folder, the stream name does not
2602 * change).
2603 */
cb523e02
JG
2604 free(stream->prev_path_name);
2605 stream->prev_path_name = stream->path_name;
5312a3ed 2606 stream->path_name = create_output_path(new_path_view.data);
d3ecc550
JD
2607 if (!stream->path_name) {
2608 ERR("Failed to create a new output path");
5312a3ed 2609 ret = -1;
d3ecc550
JD
2610 goto end_stream_unlock;
2611 }
2612 ret = utils_mkdir_recursive(stream->path_name, S_IRWXU | S_IRWXG,
2613 -1, -1);
2614 if (ret < 0) {
2615 ERR("relay creating output directory");
5312a3ed 2616 ret = -1;
d3ecc550
JD
2617 goto end_stream_unlock;
2618 }
5312a3ed 2619
81164b6b
JG
2620 assert(stream->current_chunk_id.is_set);
2621 stream->current_chunk_id.value = stream_info.new_chunk_id;
d3ecc550
JD
2622
2623 if (stream->is_metadata) {
c6db3843
JG
2624 /*
2625 * Metadata streams have no index; consider its rotation
2626 * complete.
2627 */
2628 stream->index_rotated = true;
d3ecc550
JD
2629 /*
2630 * The metadata stream is sent only over the control connection
2631 * so we know we have all the data to perform the stream
2632 * rotation.
2633 */
c6db3843 2634 ret = do_rotate_stream_data(stream);
d3ecc550 2635 } else {
5312a3ed 2636 stream->rotate_at_seq_num = stream_info.rotate_at_seq_num;
c6db3843
JG
2637 ret = try_rotate_stream_data(stream);
2638 if (ret < 0) {
2639 goto end_stream_unlock;
2640 }
2641
2642 ret = try_rotate_stream_index(stream);
2643 if (ret < 0) {
2644 goto end_stream_unlock;
2645 }
d3ecc550
JD
2646 }
2647
2648end_stream_unlock:
2649 pthread_mutex_unlock(&stream->lock);
2650 stream_put(stream);
2651end:
2652 memset(&reply, 0, sizeof(reply));
2653 if (ret < 0) {
2654 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2655 } else {
2656 reply.ret_code = htobe32(LTTNG_OK);
2657 }
2658 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
2659 sizeof(struct lttcomm_relayd_generic_reply), 0);
5312a3ed
JG
2660 if (send_ret < (ssize_t) sizeof(reply)) {
2661 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2662 send_ret);
2663 ret = -1;
d3ecc550
JD
2664 }
2665
2666end_no_reply:
d3ecc550
JD
2667 return ret;
2668}
2669
5312a3ed
JG
2670#define DBG_CMD(cmd_name, conn) \
2671 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
2672
2673static int relay_process_control_command(struct relay_connection *conn,
2674 const struct lttcomm_relayd_hdr *header,
2675 const struct lttng_buffer_view *payload)
b8aa1682
JD
2676{
2677 int ret = 0;
2678
5312a3ed 2679 switch (header->cmd) {
b8aa1682 2680 case RELAYD_CREATE_SESSION:
5312a3ed
JG
2681 DBG_CMD("RELAYD_CREATE_SESSION", conn);
2682 ret = relay_create_session(header, conn, payload);
b8aa1682 2683 break;
b8aa1682 2684 case RELAYD_ADD_STREAM:
5312a3ed
JG
2685 DBG_CMD("RELAYD_ADD_STREAM", conn);
2686 ret = relay_add_stream(header, conn, payload);
b8aa1682
JD
2687 break;
2688 case RELAYD_START_DATA:
5312a3ed
JG
2689 DBG_CMD("RELAYD_START_DATA", conn);
2690 ret = relay_start(header, conn, payload);
b8aa1682
JD
2691 break;
2692 case RELAYD_SEND_METADATA:
5312a3ed
JG
2693 DBG_CMD("RELAYD_SEND_METADATA", conn);
2694 ret = relay_recv_metadata(header, conn, payload);
b8aa1682
JD
2695 break;
2696 case RELAYD_VERSION:
5312a3ed
JG
2697 DBG_CMD("RELAYD_VERSION", conn);
2698 ret = relay_send_version(header, conn, payload);
b8aa1682 2699 break;
173af62f 2700 case RELAYD_CLOSE_STREAM:
5312a3ed
JG
2701 DBG_CMD("RELAYD_CLOSE_STREAM", conn);
2702 ret = relay_close_stream(header, conn, payload);
173af62f 2703 break;
6d805429 2704 case RELAYD_DATA_PENDING:
5312a3ed
JG
2705 DBG_CMD("RELAYD_DATA_PENDING", conn);
2706 ret = relay_data_pending(header, conn, payload);
c8f59ee5
DG
2707 break;
2708 case RELAYD_QUIESCENT_CONTROL:
5312a3ed
JG
2709 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn);
2710 ret = relay_quiescent_control(header, conn, payload);
c8f59ee5 2711 break;
f7079f67 2712 case RELAYD_BEGIN_DATA_PENDING:
5312a3ed
JG
2713 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn);
2714 ret = relay_begin_data_pending(header, conn, payload);
f7079f67
DG
2715 break;
2716 case RELAYD_END_DATA_PENDING:
5312a3ed
JG
2717 DBG_CMD("RELAYD_END_DATA_PENDING", conn);
2718 ret = relay_end_data_pending(header, conn, payload);
f7079f67 2719 break;
1c20f0e2 2720 case RELAYD_SEND_INDEX:
5312a3ed
JG
2721 DBG_CMD("RELAYD_SEND_INDEX", conn);
2722 ret = relay_recv_index(header, conn, payload);
1c20f0e2 2723 break;
a4baae1b 2724 case RELAYD_STREAMS_SENT:
5312a3ed
JG
2725 DBG_CMD("RELAYD_STREAMS_SENT", conn);
2726 ret = relay_streams_sent(header, conn, payload);
a4baae1b 2727 break;
93ec662e 2728 case RELAYD_RESET_METADATA:
5312a3ed
JG
2729 DBG_CMD("RELAYD_RESET_METADATA", conn);
2730 ret = relay_reset_metadata(header, conn, payload);
93ec662e 2731 break;
d3ecc550 2732 case RELAYD_ROTATE_STREAM:
5312a3ed
JG
2733 DBG_CMD("RELAYD_ROTATE_STREAM", conn);
2734 ret = relay_rotate_session_stream(header, conn, payload);
d3ecc550 2735 break;
b8aa1682
JD
2736 case RELAYD_UPDATE_SYNC_INFO:
2737 default:
5312a3ed 2738 ERR("Received unknown command (%u)", header->cmd);
58eb9381 2739 relay_unknown_command(conn);
b8aa1682
JD
2740 ret = -1;
2741 goto end;
2742 }
2743
2744end:
2745 return ret;
2746}
2747
5569b118
JG
2748static enum relay_connection_status relay_process_control_receive_payload(
2749 struct relay_connection *conn)
5312a3ed
JG
2750{
2751 int ret = 0;
5569b118 2752 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
5312a3ed
JG
2753 struct lttng_dynamic_buffer *reception_buffer =
2754 &conn->protocol.ctrl.reception_buffer;
2755 struct ctrl_connection_state_receive_payload *state =
2756 &conn->protocol.ctrl.state.receive_payload;
2757 struct lttng_buffer_view payload_view;
2758
2759 if (state->left_to_receive == 0) {
2760 /* Short-circuit for payload-less commands. */
2761 goto reception_complete;
2762 }
2763
2764 ret = conn->sock->ops->recvmsg(conn->sock,
2765 reception_buffer->data + state->received,
2766 state->left_to_receive, MSG_DONTWAIT);
2767 if (ret < 0) {
5569b118
JG
2768 if (errno != EAGAIN && errno != EWOULDBLOCK) {
2769 PERROR("Unable to receive command payload on sock %d",
2770 conn->sock->fd);
2771 status = RELAY_CONNECTION_STATUS_ERROR;
2772 }
5312a3ed
JG
2773 goto end;
2774 } else if (ret == 0) {
2775 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
5569b118 2776 status = RELAY_CONNECTION_STATUS_CLOSED;
5312a3ed
JG
2777 goto end;
2778 }
2779
2780 assert(ret > 0);
2781 assert(ret <= state->left_to_receive);
2782
2783 state->left_to_receive -= ret;
2784 state->received += ret;
2785
2786 if (state->left_to_receive > 0) {
2787 /*
2788 * Can't transition to the protocol's next state, wait to
2789 * receive the rest of the header.
2790 */
2791 DBG3("Partial reception of control connection protocol payload (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
2792 state->received, state->left_to_receive,
2793 conn->sock->fd);
5312a3ed
JG
2794 goto end;
2795 }
2796
2797reception_complete:
2798 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64 " bytes",
2799 conn->sock->fd, state->received);
2800 /*
2801 * The payload required to process the command has been received.
2802 * A view to the reception buffer is forwarded to the various
2803 * commands and the state of the control is reset on success.
2804 *
2805 * Commands are responsible for sending their reply to the peer.
2806 */
2807 payload_view = lttng_buffer_view_from_dynamic_buffer(reception_buffer,
2808 0, -1);
2809 ret = relay_process_control_command(conn,
2810 &state->header, &payload_view);
2811 if (ret < 0) {
5569b118 2812 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed
JG
2813 goto end;
2814 }
2815
2816 ret = connection_reset_protocol_state(conn);
5569b118
JG
2817 if (ret) {
2818 status = RELAY_CONNECTION_STATUS_ERROR;
2819 }
5312a3ed 2820end:
5569b118 2821 return status;
5312a3ed
JG
2822}
2823
5569b118
JG
2824static enum relay_connection_status relay_process_control_receive_header(
2825 struct relay_connection *conn)
5312a3ed
JG
2826{
2827 int ret = 0;
5569b118 2828 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
5312a3ed
JG
2829 struct lttcomm_relayd_hdr header;
2830 struct lttng_dynamic_buffer *reception_buffer =
2831 &conn->protocol.ctrl.reception_buffer;
2832 struct ctrl_connection_state_receive_header *state =
2833 &conn->protocol.ctrl.state.receive_header;
2834
2835 assert(state->left_to_receive != 0);
2836
2837 ret = conn->sock->ops->recvmsg(conn->sock,
2838 reception_buffer->data + state->received,
2839 state->left_to_receive, MSG_DONTWAIT);
2840 if (ret < 0) {
5569b118
JG
2841 if (errno != EAGAIN && errno != EWOULDBLOCK) {
2842 PERROR("Unable to receive control command header on sock %d",
2843 conn->sock->fd);
2844 status = RELAY_CONNECTION_STATUS_ERROR;
2845 }
5312a3ed
JG
2846 goto end;
2847 } else if (ret == 0) {
2848 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
5569b118 2849 status = RELAY_CONNECTION_STATUS_CLOSED;
5312a3ed
JG
2850 goto end;
2851 }
2852
2853 assert(ret > 0);
2854 assert(ret <= state->left_to_receive);
2855
2856 state->left_to_receive -= ret;
2857 state->received += ret;
2858
2859 if (state->left_to_receive > 0) {
2860 /*
2861 * Can't transition to the protocol's next state, wait to
2862 * receive the rest of the header.
2863 */
2864 DBG3("Partial reception of control connection protocol header (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
2865 state->received, state->left_to_receive,
2866 conn->sock->fd);
5312a3ed
JG
2867 goto end;
2868 }
2869
2870 /* Transition to next state: receiving the command's payload. */
2871 conn->protocol.ctrl.state_id =
2872 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD;
2873 memcpy(&header, reception_buffer->data, sizeof(header));
2874 header.circuit_id = be64toh(header.circuit_id);
2875 header.data_size = be64toh(header.data_size);
2876 header.cmd = be32toh(header.cmd);
2877 header.cmd_version = be32toh(header.cmd_version);
2878 memcpy(&conn->protocol.ctrl.state.receive_payload.header,
2879 &header, sizeof(header));
2880
2881 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32 ", cmd_version = %" PRIu32 ", payload size = %" PRIu64 " bytes",
2882 conn->sock->fd, header.cmd, header.cmd_version,
2883 header.data_size);
2884
715e6fb1 2885 if (header.data_size > DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE) {
5312a3ed
JG
2886 ERR("Command header indicates a payload (%" PRIu64 " bytes) that exceeds the maximal payload size allowed on a control connection.",
2887 header.data_size);
5569b118 2888 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed
JG
2889 goto end;
2890 }
2891
2892 conn->protocol.ctrl.state.receive_payload.left_to_receive =
2893 header.data_size;
2894 conn->protocol.ctrl.state.receive_payload.received = 0;
2895 ret = lttng_dynamic_buffer_set_size(reception_buffer,
2896 header.data_size);
2897 if (ret) {
5569b118 2898 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed
JG
2899 goto end;
2900 }
2901
2902 if (header.data_size == 0) {
2903 /*
2904 * Manually invoke the next state as the poll loop
2905 * will not wake-up to allow us to proceed further.
2906 */
5569b118 2907 status = relay_process_control_receive_payload(conn);
5312a3ed
JG
2908 }
2909end:
5569b118 2910 return status;
5312a3ed
JG
2911}
2912
2913/*
2914 * Process the commands received on the control socket
2915 */
5569b118
JG
2916static enum relay_connection_status relay_process_control(
2917 struct relay_connection *conn)
5312a3ed 2918{
5569b118 2919 enum relay_connection_status status;
5312a3ed
JG
2920
2921 switch (conn->protocol.ctrl.state_id) {
2922 case CTRL_CONNECTION_STATE_RECEIVE_HEADER:
5569b118 2923 status = relay_process_control_receive_header(conn);
5312a3ed
JG
2924 break;
2925 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD:
5569b118 2926 status = relay_process_control_receive_payload(conn);
5312a3ed
JG
2927 break;
2928 default:
2929 ERR("Unknown control connection protocol state encountered.");
2930 abort();
2931 }
2932
5569b118 2933 return status;
5312a3ed
JG
2934}
2935
7d2f7452
DG
2936/*
2937 * Handle index for a data stream.
2938 *
7591bab1 2939 * Called with the stream lock held.
7d2f7452
DG
2940 *
2941 * Return 0 on success else a negative value.
2942 */
2943static int handle_index_data(struct relay_stream *stream, uint64_t net_seq_num,
5312a3ed 2944 bool rotate_index, bool *flushed, uint64_t total_size)
7d2f7452 2945{
7591bab1
MD
2946 int ret = 0;
2947 uint64_t data_offset;
2948 struct relay_index *index;
7d2f7452 2949
7d2f7452
DG
2950 /* Get data offset because we are about to update the index. */
2951 data_offset = htobe64(stream->tracefile_size_current);
2952
65d66b19
MD
2953 DBG("handle_index_data: stream %" PRIu64 " net_seq_num %" PRIu64 " data offset %" PRIu64,
2954 stream->stream_handle, net_seq_num, stream->tracefile_size_current);
7591bab1 2955
7d2f7452 2956 /*
7591bab1
MD
2957 * Lookup for an existing index for that stream id/sequence
2958 * number. If it exists, the control thread has already received the
2959 * data for it, thus we need to write it to disk.
7d2f7452 2960 */
7591bab1 2961 index = relay_index_get_by_id_or_create(stream, net_seq_num);
7d2f7452 2962 if (!index) {
7591bab1
MD
2963 ret = -1;
2964 goto end;
7d2f7452
DG
2965 }
2966
f8f3885c 2967 if (rotate_index || !stream->index_file) {
cb523e02
JG
2968 const char *stream_path;
2969
2970 /*
2971 * The data connection creates the stream's first index file.
2972 *
2973 * This can happen _after_ a ROTATE_STREAM command. In
2974 * other words, the data of the first packet of this stream
2975 * can be received after a ROTATE_STREAM command.
2976 *
2977 * The ROTATE_STREAM command changes the stream's path_name
2978 * to point to the "next" chunk. If a rotation is pending for
2979 * this stream, as indicated by "rotate_at_seq_num != -1ULL",
2980 * it means that we are still receiving data that belongs in the
2981 * stream's former path.
2982 *
2983 * In this very specific case, we must ensure that the index
2984 * file is created in the streams's former path,
2985 * "prev_path_name".
2986 *
2987 * All other rotations beyond the first one are not affected
2988 * by this problem since the actual rotation operation creates
2989 * the new chunk's index file.
2990 */
2991 stream_path = stream->rotate_at_seq_num == -1ULL ?
2992 stream->path_name:
2993 stream->prev_path_name;
2994
2995 ret = create_rotate_index_file(stream, stream_path);
d3ecc550
JD
2996 if (ret < 0) {
2997 ERR("Failed to rotate index");
7591bab1
MD
2998 /* Put self-ref for this index due to error. */
2999 relay_index_put(index);
f8f3885c 3000 index = NULL;
7591bab1 3001 goto end;
7d2f7452 3002 }
7d2f7452
DG
3003 }
3004
f8f3885c 3005 if (relay_index_set_file(index, stream->index_file, data_offset)) {
7591bab1
MD
3006 ret = -1;
3007 /* Put self-ref for this index due to error. */
3008 relay_index_put(index);
f8f3885c 3009 index = NULL;
7591bab1 3010 goto end;
7d2f7452
DG
3011 }
3012
7591bab1
MD
3013 ret = relay_index_try_flush(index);
3014 if (ret == 0) {
a44ca2ca
MD
3015 tracefile_array_commit_seq(stream->tfa);
3016 stream->index_received_seqcount++;
d3ecc550 3017 *flushed = true;
7591bab1 3018 } else if (ret > 0) {
d3ecc550 3019 index->total_size = total_size;
7591bab1
MD
3020 /* No flush. */
3021 ret = 0;
3022 } else {
245f8bec
JR
3023 /*
3024 * ret < 0
3025 *
3026 * relay_index_try_flush is responsible for the self-reference
3027 * put of the index object on error.
3028 */
3029 ERR("relay_index_try_flush error %d", ret);
7591bab1
MD
3030 ret = -1;
3031 }
3032end:
7d2f7452
DG
3033 return ret;
3034}
3035
5569b118
JG
3036static enum relay_connection_status relay_process_data_receive_header(
3037 struct relay_connection *conn)
b8aa1682 3038{
5312a3ed 3039 int ret;
5569b118 3040 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
5312a3ed
JG
3041 struct data_connection_state_receive_header *state =
3042 &conn->protocol.data.state.receive_header;
3043 struct lttcomm_relayd_data_hdr header;
b8aa1682 3044 struct relay_stream *stream;
5312a3ed
JG
3045
3046 assert(state->left_to_receive != 0);
3047
3048 ret = conn->sock->ops->recvmsg(conn->sock,
3049 state->header_reception_buffer + state->received,
3050 state->left_to_receive, MSG_DONTWAIT);
3051 if (ret < 0) {
5569b118
JG
3052 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3053 PERROR("Unable to receive data header on sock %d", conn->sock->fd);
3054 status = RELAY_CONNECTION_STATUS_ERROR;
3055 }
5312a3ed
JG
3056 goto end;
3057 } else if (ret == 0) {
3058 /* Orderly shutdown. Not necessary to print an error. */
3059 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
5569b118 3060 status = RELAY_CONNECTION_STATUS_CLOSED;
b8aa1682
JD
3061 goto end;
3062 }
3063
5312a3ed
JG
3064 assert(ret > 0);
3065 assert(ret <= state->left_to_receive);
3066
3067 state->left_to_receive -= ret;
3068 state->received += ret;
3069
3070 if (state->left_to_receive > 0) {
3071 /*
3072 * Can't transition to the protocol's next state, wait to
3073 * receive the rest of the header.
3074 */
3075 DBG3("Partial reception of data connection header (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
3076 state->received, state->left_to_receive,
3077 conn->sock->fd);
7591bab1 3078 goto end;
b8aa1682 3079 }
b8aa1682 3080
5312a3ed
JG
3081 /* Transition to next state: receiving the payload. */
3082 conn->protocol.data.state_id = DATA_CONNECTION_STATE_RECEIVE_PAYLOAD;
173af62f 3083
5312a3ed
JG
3084 memcpy(&header, state->header_reception_buffer, sizeof(header));
3085 header.circuit_id = be64toh(header.circuit_id);
3086 header.stream_id = be64toh(header.stream_id);
3087 header.data_size = be32toh(header.data_size);
3088 header.net_seq_num = be64toh(header.net_seq_num);
3089 header.padding_size = be32toh(header.padding_size);
3090 memcpy(&conn->protocol.data.state.receive_payload.header, &header, sizeof(header));
3091
3092 conn->protocol.data.state.receive_payload.left_to_receive =
3093 header.data_size;
3094 conn->protocol.data.state.receive_payload.received = 0;
3095 conn->protocol.data.state.receive_payload.rotate_index = false;
3096
3097 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64 ", stream_id = %" PRIu64 ", data_size = %" PRIu32 ", net_seq_num = %" PRIu64 ", padding_size = %" PRIu32,
3098 conn->sock->fd, header.circuit_id,
3099 header.stream_id, header.data_size,
3100 header.net_seq_num, header.padding_size);
3101
3102 stream = stream_get_by_id(header.stream_id);
3103 if (!stream) {
3104 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64,
3105 header.stream_id);
5569b118
JG
3106 /* Protocol error. */
3107 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed
JG
3108 goto end;
3109 }
b8aa1682 3110
7591bab1
MD
3111 pthread_mutex_lock(&stream->lock);
3112
1c20f0e2 3113 /* Check if a rotation is needed. */
0f907de1 3114 if (stream->tracefile_size > 0 &&
5312a3ed 3115 (stream->tracefile_size_current + header.data_size) >
0f907de1 3116 stream->tracefile_size) {
a44ca2ca
MD
3117 uint64_t old_id, new_id;
3118
3119 old_id = tracefile_array_get_file_index_head(stream->tfa);
3120 tracefile_array_file_rotate(stream->tfa);
3121
3122 /* new_id is updated by utils_rotate_stream_file. */
3123 new_id = old_id;
6b6b9a5a 3124
7591bab1
MD
3125 ret = utils_rotate_stream_file(stream->path_name,
3126 stream->channel_name, stream->tracefile_size,
3127 stream->tracefile_count, -1,
3128 -1, stream->stream_fd->fd,
a44ca2ca 3129 &new_id, &stream->stream_fd->fd);
0f907de1 3130 if (ret < 0) {
5312a3ed 3131 ERR("Failed to rotate stream output file");
5569b118 3132 status = RELAY_CONNECTION_STATUS_ERROR;
7591bab1
MD
3133 goto end_stream_unlock;
3134 }
5312a3ed 3135
7591bab1
MD
3136 /*
3137 * Reset current size because we just performed a stream
3138 * rotation.
3139 */
a6976990 3140 stream->tracefile_size_current = 0;
5312a3ed 3141 conn->protocol.data.state.receive_payload.rotate_index = true;
1c20f0e2
JD
3142 }
3143
5312a3ed
JG
3144end_stream_unlock:
3145 pthread_mutex_unlock(&stream->lock);
3146 stream_put(stream);
3147end:
5569b118 3148 return status;
5312a3ed
JG
3149}
3150
5569b118
JG
3151static enum relay_connection_status relay_process_data_receive_payload(
3152 struct relay_connection *conn)
5312a3ed
JG
3153{
3154 int ret;
5569b118 3155 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
5312a3ed
JG
3156 struct relay_stream *stream;
3157 struct data_connection_state_receive_payload *state =
3158 &conn->protocol.data.state.receive_payload;
3159 const size_t chunk_size = RECV_DATA_BUFFER_SIZE;
3160 char data_buffer[chunk_size];
3161 bool partial_recv = false;
3162 bool new_stream = false, close_requested = false, index_flushed = false;
3163 uint64_t left_to_receive = state->left_to_receive;
3164 struct relay_session *session;
3165
fd0f1e3e
JR
3166 DBG3("Receiving data for stream id %" PRIu64 " seqnum %" PRIu64 ", %" PRIu64" bytes received, %" PRIu64 " bytes left to receive",
3167 state->header.stream_id, state->header.net_seq_num,
3168 state->received, left_to_receive);
3169
5312a3ed
JG
3170 stream = stream_get_by_id(state->header.stream_id);
3171 if (!stream) {
5569b118 3172 /* Protocol error. */
fd0f1e3e 3173 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64,
5312a3ed 3174 state->header.stream_id);
5569b118 3175 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed 3176 goto end;
1c20f0e2
JD
3177 }
3178
5312a3ed
JG
3179 pthread_mutex_lock(&stream->lock);
3180 session = stream->trace->session;
fd0f1e3e
JR
3181 if (!conn->session) {
3182 ret = connection_set_session(conn, session);
3183 if (ret) {
3184 status = RELAY_CONNECTION_STATUS_ERROR;
3185 goto end_stream_unlock;
3186 }
3187 }
5312a3ed
JG
3188
3189 /*
3190 * The size of the "chunk" received on any iteration is bounded by:
3191 * - the data left to receive,
3192 * - the data immediately available on the socket,
3193 * - the on-stack data buffer
3194 */
3195 while (left_to_receive > 0 && !partial_recv) {
3196 ssize_t write_ret;
3197 size_t recv_size = min(left_to_receive, chunk_size);
3198
3199 ret = conn->sock->ops->recvmsg(conn->sock, data_buffer,
3200 recv_size, MSG_DONTWAIT);
3201 if (ret < 0) {
5569b118
JG
3202 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3203 PERROR("Socket %d error", conn->sock->fd);
3204 status = RELAY_CONNECTION_STATUS_ERROR;
3205 }
0848dba7 3206 goto end_stream_unlock;
5312a3ed
JG
3207 } else if (ret == 0) {
3208 /* No more data ready to be consumed on socket. */
3209 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64,
3210 state->header.stream_id);
5569b118 3211 status = RELAY_CONNECTION_STATUS_CLOSED;
5312a3ed
JG
3212 break;
3213 } else if (ret < (int) recv_size) {
3214 /*
3215 * All the data available on the socket has been
3216 * consumed.
3217 */
3218 partial_recv = true;
0848dba7
MD
3219 }
3220
5312a3ed
JG
3221 recv_size = ret;
3222
0848dba7 3223 /* Write data to stream output fd. */
5312a3ed 3224 write_ret = lttng_write(stream->stream_fd->fd, data_buffer,
0848dba7 3225 recv_size);
5312a3ed 3226 if (write_ret < (ssize_t) recv_size) {
0848dba7 3227 ERR("Relay error writing data to file");
5569b118 3228 status = RELAY_CONNECTION_STATUS_ERROR;
0848dba7
MD
3229 goto end_stream_unlock;
3230 }
3231
5312a3ed
JG
3232 left_to_receive -= recv_size;
3233 state->received += recv_size;
3234 state->left_to_receive = left_to_receive;
3235
0848dba7 3236 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64,
5312a3ed
JG
3237 write_ret, stream->stream_handle);
3238 }
3239
3240 if (state->left_to_receive > 0) {
3241 /*
3242 * Did not receive all the data expected, wait for more data to
3243 * become available on the socket.
3244 */
3245 DBG3("Partial receive on data connection of stream id %" PRIu64 ", %" PRIu64 " bytes received, %" PRIu64 " bytes left to receive",
3246 state->header.stream_id, state->received,
3247 state->left_to_receive);
5312a3ed 3248 goto end_stream_unlock;
0848dba7 3249 }
5ab7344e 3250
7591bab1 3251 ret = write_padding_to_file(stream->stream_fd->fd,
5312a3ed 3252 state->header.padding_size);
46f4eaa5 3253 if ((int64_t) ret < (int64_t) state->header.padding_size) {
65d66b19 3254 ERR("write_padding_to_file: fail stream %" PRIu64 " net_seq_num %" PRIu64 " ret %d",
5312a3ed
JG
3255 stream->stream_handle,
3256 state->header.net_seq_num, ret);
5569b118 3257 status = RELAY_CONNECTION_STATUS_ERROR;
7591bab1 3258 goto end_stream_unlock;
1d4dfdef 3259 }
5312a3ed
JG
3260
3261
298a25ca 3262 if (session_streams_have_index(session)) {
5312a3ed
JG
3263 ret = handle_index_data(stream, state->header.net_seq_num,
3264 state->rotate_index, &index_flushed, state->header.data_size + state->header.padding_size);
3265 if (ret < 0) {
3266 ERR("handle_index_data: fail stream %" PRIu64 " net_seq_num %" PRIu64 " ret %d",
3267 stream->stream_handle,
3268 state->header.net_seq_num, ret);
5569b118 3269 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed
JG
3270 goto end_stream_unlock;
3271 }
3272 }
3273
3274 stream->tracefile_size_current += state->header.data_size +
3275 state->header.padding_size;
3276
a8f9f353 3277 if (stream->prev_data_seq == -1ULL) {
c0bae11d
MD
3278 new_stream = true;
3279 }
d3ecc550
JD
3280 if (index_flushed) {
3281 stream->pos_after_last_complete_data_index =
3282 stream->tracefile_size_current;
7a45c7e6 3283 stream->prev_index_seq = state->header.net_seq_num;
c6db3843
JG
3284 ret = try_rotate_stream_index(stream);
3285 if (ret < 0) {
3286 goto end_stream_unlock;
3287 }
d3ecc550 3288 }
c0bae11d 3289
a8f9f353 3290 stream->prev_data_seq = state->header.net_seq_num;
5312a3ed
JG
3291
3292 /*
3293 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3294 * contents of *state which are aliased (union) to the same location as
3295 * the new state. Don't use it beyond this point.
3296 */
3297 connection_reset_protocol_state(conn);
3298 state = NULL;
173af62f 3299
c6db3843 3300 ret = try_rotate_stream_data(stream);
d3ecc550 3301 if (ret < 0) {
5569b118 3302 status = RELAY_CONNECTION_STATUS_ERROR;
d3ecc550
JD
3303 goto end_stream_unlock;
3304 }
3305
7591bab1 3306end_stream_unlock:
bda7c7b9 3307 close_requested = stream->close_requested;
7591bab1 3308 pthread_mutex_unlock(&stream->lock);
5312a3ed 3309 if (close_requested && left_to_receive == 0) {
bda7c7b9
JG
3310 try_stream_close(stream);
3311 }
3312
c0bae11d
MD
3313 if (new_stream) {
3314 pthread_mutex_lock(&session->lock);
3315 uatomic_set(&session->new_streams, 1);
3316 pthread_mutex_unlock(&session->lock);
3317 }
5312a3ed 3318
7591bab1 3319 stream_put(stream);
b8aa1682 3320end:
5569b118 3321 return status;
b8aa1682
JD
3322}
3323
5312a3ed
JG
3324/*
3325 * relay_process_data: Process the data received on the data socket
3326 */
5569b118
JG
3327static enum relay_connection_status relay_process_data(
3328 struct relay_connection *conn)
5312a3ed 3329{
5569b118 3330 enum relay_connection_status status;
5312a3ed
JG
3331
3332 switch (conn->protocol.data.state_id) {
3333 case DATA_CONNECTION_STATE_RECEIVE_HEADER:
5569b118 3334 status = relay_process_data_receive_header(conn);
5312a3ed
JG
3335 break;
3336 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD:
5569b118 3337 status = relay_process_data_receive_payload(conn);
5312a3ed
JG
3338 break;
3339 default:
3340 ERR("Unexpected data connection communication state.");
3341 abort();
3342 }
3343
5569b118 3344 return status;
5312a3ed
JG
3345}
3346
7591bab1 3347static void cleanup_connection_pollfd(struct lttng_poll_event *events, int pollfd)
b8aa1682
JD
3348{
3349 int ret;
3350
58eb9381 3351 (void) lttng_poll_del(events, pollfd);
b8aa1682
JD
3352
3353 ret = close(pollfd);
3354 if (ret < 0) {
3355 ERR("Closing pollfd %d", pollfd);
3356 }
3357}
3358
7591bab1
MD
3359static void relay_thread_close_connection(struct lttng_poll_event *events,
3360 int pollfd, struct relay_connection *conn)
9d1bbf21 3361{
7591bab1 3362 const char *type_str;
2a174661 3363
7591bab1
MD
3364 switch (conn->type) {
3365 case RELAY_DATA:
3366 type_str = "Data";
3367 break;
3368 case RELAY_CONTROL:
3369 type_str = "Control";
3370 break;
3371 case RELAY_VIEWER_COMMAND:
3372 type_str = "Viewer Command";
3373 break;
3374 case RELAY_VIEWER_NOTIFICATION:
3375 type_str = "Viewer Notification";
3376 break;
3377 default:
3378 type_str = "Unknown";
9d1bbf21 3379 }
7591bab1
MD
3380 cleanup_connection_pollfd(events, pollfd);
3381 connection_put(conn);
3382 DBG("%s connection closed with %d", type_str, pollfd);
b8aa1682
JD
3383}
3384
3385/*
3386 * This thread does the actual work
3387 */
7591bab1 3388static void *relay_thread_worker(void *data)
b8aa1682 3389{
beaad64c
DG
3390 int ret, err = -1, last_seen_data_fd = -1;
3391 uint32_t nb_fd;
b8aa1682
JD
3392 struct lttng_poll_event events;
3393 struct lttng_ht *relay_connections_ht;
b8aa1682 3394 struct lttng_ht_iter iter;
90e7d72f 3395 struct relay_connection *destroy_conn = NULL;
b8aa1682
JD
3396
3397 DBG("[thread] Relay worker started");
3398
9d1bbf21
MD
3399 rcu_register_thread();
3400
55706a7d
MD
3401 health_register(health_relayd, HEALTH_RELAYD_TYPE_WORKER);
3402
9b5e0863
MD
3403 if (testpoint(relayd_thread_worker)) {
3404 goto error_testpoint;
3405 }
3406
f385ae0a
MD
3407 health_code_update();
3408
b8aa1682
JD
3409 /* table of connections indexed on socket */
3410 relay_connections_ht = lttng_ht_new(0, LTTNG_HT_TYPE_ULONG);
095a4ae5
MD
3411 if (!relay_connections_ht) {
3412 goto relay_connections_ht_error;
3413 }
b8aa1682 3414
b8aa1682
JD
3415 ret = create_thread_poll_set(&events, 2);
3416 if (ret < 0) {
3417 goto error_poll_create;
3418 }
3419
58eb9381 3420 ret = lttng_poll_add(&events, relay_conn_pipe[0], LPOLLIN | LPOLLRDHUP);
b8aa1682
JD
3421 if (ret < 0) {
3422 goto error;
3423 }
3424
beaad64c 3425restart:
b8aa1682 3426 while (1) {
beaad64c
DG
3427 int idx = -1, i, seen_control = 0, last_notdel_data_fd = -1;
3428
f385ae0a
MD
3429 health_code_update();
3430
b8aa1682 3431 /* Infinite blocking call, waiting for transmission */
87c1611d 3432 DBG3("Relayd worker thread polling...");
f385ae0a 3433 health_poll_entry();
b8aa1682 3434 ret = lttng_poll_wait(&events, -1);
f385ae0a 3435 health_poll_exit();
b8aa1682
JD
3436 if (ret < 0) {
3437 /*
3438 * Restart interrupted system call.
3439 */
3440 if (errno == EINTR) {
3441 goto restart;
3442 }
3443 goto error;
3444 }
3445
0d9c5d77
DG
3446 nb_fd = ret;
3447
beaad64c 3448 /*
7591bab1
MD
3449 * Process control. The control connection is
3450 * prioritized so we don't starve it with high
3451 * throughput tracing data on the data connection.
beaad64c 3452 */
b8aa1682
JD
3453 for (i = 0; i < nb_fd; i++) {
3454 /* Fetch once the poll data */
beaad64c
DG
3455 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
3456 int pollfd = LTTNG_POLL_GETFD(&events, i);
b8aa1682 3457
f385ae0a
MD
3458 health_code_update();
3459
b8aa1682
JD
3460 /* Thread quit pipe has been closed. Killing thread. */
3461 ret = check_thread_quit_pipe(pollfd, revents);
3462 if (ret) {
095a4ae5
MD
3463 err = 0;
3464 goto exit;
b8aa1682
JD
3465 }
3466
58eb9381
DG
3467 /* Inspect the relay conn pipe for new connection */
3468 if (pollfd == relay_conn_pipe[0]) {
03e43155 3469 if (revents & LPOLLIN) {
90e7d72f
JG
3470 struct relay_connection *conn;
3471
58eb9381 3472 ret = lttng_read(relay_conn_pipe[0], &conn, sizeof(conn));
b8aa1682
JD
3473 if (ret < 0) {
3474 goto error;
3475 }
58eb9381
DG
3476 lttng_poll_add(&events, conn->sock->fd,
3477 LPOLLIN | LPOLLRDHUP);
7591bab1 3478 connection_ht_add(relay_connections_ht, conn);
58eb9381 3479 DBG("Connection socket %d added", conn->sock->fd);
03e43155
MD
3480 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
3481 ERR("Relay connection pipe error");
3482 goto error;
3483 } else {
3484 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
3485 goto error;
b8aa1682 3486 }
58eb9381 3487 } else {
90e7d72f
JG
3488 struct relay_connection *ctrl_conn;
3489
7591bab1 3490 ctrl_conn = connection_get_by_sock(relay_connections_ht, pollfd);
58eb9381 3491 /* If not found, there is a synchronization issue. */
90e7d72f 3492 assert(ctrl_conn);
58eb9381 3493
03e43155
MD
3494 if (ctrl_conn->type == RELAY_DATA) {
3495 if (revents & LPOLLIN) {
beaad64c
DG
3496 /*
3497 * Flag the last seen data fd not deleted. It will be
3498 * used as the last seen fd if any fd gets deleted in
3499 * this first loop.
3500 */
3501 last_notdel_data_fd = pollfd;
3502 }
03e43155
MD
3503 goto put_ctrl_connection;
3504 }
3505 assert(ctrl_conn->type == RELAY_CONTROL);
3506
3507 if (revents & LPOLLIN) {
5569b118
JG
3508 enum relay_connection_status status;
3509
3510 status = relay_process_control(ctrl_conn);
3511 if (status != RELAY_CONNECTION_STATUS_OK) {
fd0f1e3e
JR
3512 /*
3513 * On socket error flag the session as aborted to force
3514 * the cleanup of its stream otherwise it can leak
3515 * during the lifetime of the relayd.
3516 *
3517 * This prevents situations in which streams can be
3518 * left opened because an index was received, the
3519 * control connection is closed, and the data
3520 * connection is closed (uncleanly) before the packet's
3521 * data provided.
3522 *
3523 * Since the control connection encountered an error,
3524 * it is okay to be conservative and close the
3525 * session right now as we can't rely on the protocol
3526 * being respected anymore.
3527 */
3528 if (status == RELAY_CONNECTION_STATUS_ERROR) {
3529 session_abort(ctrl_conn->session);
3530 }
3531
5569b118 3532 /* Clear the connection on error or close. */
5312a3ed
JG
3533 relay_thread_close_connection(&events,
3534 pollfd,
03e43155 3535 ctrl_conn);
03e43155 3536 }
5312a3ed 3537 seen_control = 1;
03e43155
MD
3538 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
3539 relay_thread_close_connection(&events,
3540 pollfd, ctrl_conn);
3541 if (last_seen_data_fd == pollfd) {
3542 last_seen_data_fd = last_notdel_data_fd;
3543 }
58eb9381 3544 } else {
03e43155
MD
3545 ERR("Unexpected poll events %u for control sock %d",
3546 revents, pollfd);
3547 connection_put(ctrl_conn);
3548 goto error;
beaad64c 3549 }
03e43155 3550 put_ctrl_connection:
7591bab1 3551 connection_put(ctrl_conn);
beaad64c
DG
3552 }
3553 }
3554
3555 /*
3556 * The last loop handled a control request, go back to poll to make
3557 * sure we prioritise the control socket.
3558 */
3559 if (seen_control) {
3560 continue;
3561 }
3562
3563 if (last_seen_data_fd >= 0) {
3564 for (i = 0; i < nb_fd; i++) {
3565 int pollfd = LTTNG_POLL_GETFD(&events, i);
f385ae0a
MD
3566
3567 health_code_update();
3568
beaad64c
DG
3569 if (last_seen_data_fd == pollfd) {
3570 idx = i;
3571 break;
3572 }
3573 }
3574 }
3575
3576 /* Process data connection. */
3577 for (i = idx + 1; i < nb_fd; i++) {
3578 /* Fetch the poll data. */
3579 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
3580 int pollfd = LTTNG_POLL_GETFD(&events, i);
90e7d72f 3581 struct relay_connection *data_conn;
beaad64c 3582
f385ae0a
MD
3583 health_code_update();
3584
fd20dac9
MD
3585 if (!revents) {
3586 /* No activity for this FD (poll implementation). */
3587 continue;
3588 }
3589
beaad64c 3590 /* Skip the command pipe. It's handled in the first loop. */
58eb9381 3591 if (pollfd == relay_conn_pipe[0]) {
beaad64c
DG
3592 continue;
3593 }
3594
7591bab1 3595 data_conn = connection_get_by_sock(relay_connections_ht, pollfd);
90e7d72f 3596 if (!data_conn) {
fd20dac9 3597 /* Skip it. Might be removed before. */
fd20dac9
MD
3598 continue;
3599 }
03e43155
MD
3600 if (data_conn->type == RELAY_CONTROL) {
3601 goto put_data_connection;
3602 }
3603 assert(data_conn->type == RELAY_DATA);
fd20dac9
MD
3604
3605 if (revents & LPOLLIN) {
5569b118
JG
3606 enum relay_connection_status status;
3607
3608 status = relay_process_data(data_conn);
3609 /* Connection closed or error. */
3610 if (status != RELAY_CONNECTION_STATUS_OK) {
fd0f1e3e
JR
3611 /*
3612 * On socket error flag the session as aborted to force
3613 * the cleanup of its stream otherwise it can leak
3614 * during the lifetime of the relayd.
3615 *
3616 * This prevents situations in which streams can be
3617 * left opened because an index was received, the
3618 * control connection is closed, and the data
3619 * connection is closed (uncleanly) before the packet's
3620 * data provided.
3621 *
3622 * Since the data connection encountered an error,
3623 * it is okay to be conservative and close the
3624 * session right now as we can't rely on the protocol
3625 * being respected anymore.
3626 */
3627 if (status == RELAY_CONNECTION_STATUS_ERROR) {
3628 session_abort(data_conn->session);
3629 }
7591bab1 3630 relay_thread_close_connection(&events, pollfd,
03e43155 3631 data_conn);
fd20dac9
MD
3632 /*
3633 * Every goto restart call sets the last seen fd where
3634 * here we don't really care since we gracefully
3635 * continue the loop after the connection is deleted.
3636 */
3637 } else {
3638 /* Keep last seen port. */
3639 last_seen_data_fd = pollfd;
7591bab1 3640 connection_put(data_conn);
fd20dac9 3641 goto restart;
b8aa1682 3642 }
03e43155
MD
3643 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
3644 relay_thread_close_connection(&events, pollfd,
3645 data_conn);
3646 } else {
3647 ERR("Unknown poll events %u for data sock %d",
3648 revents, pollfd);
b8aa1682 3649 }
03e43155 3650 put_data_connection:
7591bab1 3651 connection_put(data_conn);
b8aa1682 3652 }
beaad64c 3653 last_seen_data_fd = -1;
b8aa1682
JD
3654 }
3655
f385ae0a
MD
3656 /* Normal exit, no error */
3657 ret = 0;
3658
095a4ae5 3659exit:
b8aa1682 3660error:
71efa8ef 3661 /* Cleanup remaining connection object. */
9d1bbf21 3662 rcu_read_lock();
90e7d72f
JG
3663 cds_lfht_for_each_entry(relay_connections_ht->ht, &iter.iter,
3664 destroy_conn,
58eb9381 3665 sock_n.node) {
f385ae0a 3666 health_code_update();
98ba050e 3667
fd0f1e3e 3668 session_abort(destroy_conn->session);
98ba050e 3669
7591bab1
MD
3670 /*
3671 * No need to grab another ref, because we own
3672 * destroy_conn.
3673 */
3674 relay_thread_close_connection(&events, destroy_conn->sock->fd,
3675 destroy_conn);
b8aa1682 3676 }
94d49140 3677 rcu_read_unlock();
7591bab1
MD
3678
3679 lttng_poll_clean(&events);
7d2f7452 3680error_poll_create:
b8aa1682 3681 lttng_ht_destroy(relay_connections_ht);
095a4ae5 3682relay_connections_ht_error:
58eb9381
DG
3683 /* Close relay conn pipes */
3684 utils_close_pipe(relay_conn_pipe);
095a4ae5
MD
3685 if (err) {
3686 DBG("Thread exited with error");
3687 }
b8aa1682 3688 DBG("Worker thread cleanup complete");
9b5e0863 3689error_testpoint:
f385ae0a
MD
3690 if (err) {
3691 health_error();
3692 ERR("Health error occurred in %s", __func__);
3693 }
3694 health_unregister(health_relayd);
9d1bbf21 3695 rcu_unregister_thread();
b4aacfdc 3696 lttng_relay_stop_threads();
b8aa1682
JD
3697 return NULL;
3698}
3699
3700/*
3701 * Create the relay command pipe to wake thread_manage_apps.
3702 * Closed in cleanup().
3703 */
58eb9381 3704static int create_relay_conn_pipe(void)
b8aa1682 3705{
a02de639 3706 int ret;
b8aa1682 3707
58eb9381 3708 ret = utils_create_pipe_cloexec(relay_conn_pipe);
b8aa1682 3709
b8aa1682
JD
3710 return ret;
3711}
3712
3713/*
3714 * main
3715 */
3716int main(int argc, char **argv)
3717{
178a0557 3718 int ret = 0, retval = 0;
b8aa1682
JD
3719 void *status;
3720
b8aa1682
JD
3721 /* Parse arguments */
3722 progname = argv[0];
178a0557
MD
3723 if (set_options(argc, argv)) {
3724 retval = -1;
3725 goto exit_options;
b8aa1682
JD
3726 }
3727
178a0557
MD
3728 if (set_signal_handler()) {
3729 retval = -1;
3730 goto exit_options;
b8aa1682
JD
3731 }
3732
4d513a50
DG
3733 /* Try to create directory if -o, --output is specified. */
3734 if (opt_output_path) {
994fa64f
DG
3735 if (*opt_output_path != '/') {
3736 ERR("Please specify an absolute path for -o, --output PATH");
178a0557
MD
3737 retval = -1;
3738 goto exit_options;
994fa64f
DG
3739 }
3740
d77dded2
JG
3741 ret = utils_mkdir_recursive(opt_output_path, S_IRWXU | S_IRWXG,
3742 -1, -1);
4d513a50
DG
3743 if (ret < 0) {
3744 ERR("Unable to create %s", opt_output_path);
178a0557
MD
3745 retval = -1;
3746 goto exit_options;
4d513a50
DG
3747 }
3748 }
3749
b8aa1682 3750 /* Daemonize */
b5218ffb 3751 if (opt_daemon || opt_background) {
3fd27398
MD
3752 int i;
3753
3754 ret = lttng_daemonize(&child_ppid, &recv_child_signal,
3755 !opt_background);
b8aa1682 3756 if (ret < 0) {
178a0557
MD
3757 retval = -1;
3758 goto exit_options;
b8aa1682 3759 }
3fd27398
MD
3760
3761 /*
3762 * We are in the child. Make sure all other file
3763 * descriptors are closed, in case we are called with
3764 * more opened file descriptors than the standard ones.
3765 */
3766 for (i = 3; i < sysconf(_SC_OPEN_MAX); i++) {
3767 (void) close(i);
3768 }
3769 }
3770
23c8ff50
JG
3771 sessiond_trace_chunk_registry = sessiond_trace_chunk_registry_create();
3772 if (!sessiond_trace_chunk_registry) {
3773 ERR("Failed to initialize session daemon trace chunk registry");
3774 retval = -1;
3775 goto exit_sessiond_trace_chunk_registry;
3776 }
3777
178a0557
MD
3778 /* Initialize thread health monitoring */
3779 health_relayd = health_app_create(NR_HEALTH_RELAYD_TYPES);
3780 if (!health_relayd) {
3781 PERROR("health_app_create error");
3782 retval = -1;
3783 goto exit_health_app_create;
3784 }
3785
3fd27398 3786 /* Create thread quit pipe */
178a0557
MD
3787 if (init_thread_quit_pipe()) {
3788 retval = -1;
3789 goto exit_init_data;
b8aa1682
JD
3790 }
3791
b8aa1682 3792 /* Setup the thread apps communication pipe. */
178a0557
MD
3793 if (create_relay_conn_pipe()) {
3794 retval = -1;
3795 goto exit_init_data;
b8aa1682
JD
3796 }
3797
3798 /* Init relay command queue. */
8bdee6e2 3799 cds_wfcq_init(&relay_conn_queue.head, &relay_conn_queue.tail);
b8aa1682 3800
554831e7
MD
3801 /* Initialize communication library */
3802 lttcomm_init();
87e45c13 3803 lttcomm_inet_init();
554831e7 3804
d3e2ba59 3805 /* tables of sessions indexed by session ID */
7591bab1
MD
3806 sessions_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3807 if (!sessions_ht) {
178a0557
MD
3808 retval = -1;
3809 goto exit_init_data;
d3e2ba59
JD
3810 }
3811
3812 /* tables of streams indexed by stream ID */
2a174661 3813 relay_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
d3e2ba59 3814 if (!relay_streams_ht) {
178a0557
MD
3815 retval = -1;
3816 goto exit_init_data;
d3e2ba59
JD
3817 }
3818
3819 /* tables of streams indexed by stream ID */
92c6ca54
DG
3820 viewer_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3821 if (!viewer_streams_ht) {
178a0557
MD
3822 retval = -1;
3823 goto exit_init_data;
55706a7d
MD
3824 }
3825
65931c8b 3826 ret = utils_create_pipe(health_quit_pipe);
178a0557
MD
3827 if (ret) {
3828 retval = -1;
3829 goto exit_health_quit_pipe;
65931c8b
MD
3830 }
3831
3832 /* Create thread to manage the client socket */
1a1a34b4 3833 ret = pthread_create(&health_thread, default_pthread_attr(),
65931c8b 3834 thread_manage_health, (void *) NULL);
178a0557
MD
3835 if (ret) {
3836 errno = ret;
65931c8b 3837 PERROR("pthread_create health");
178a0557
MD
3838 retval = -1;
3839 goto exit_health_thread;
65931c8b
MD
3840 }
3841
b8aa1682 3842 /* Setup the dispatcher thread */
1a1a34b4 3843 ret = pthread_create(&dispatcher_thread, default_pthread_attr(),
b8aa1682 3844 relay_thread_dispatcher, (void *) NULL);
178a0557
MD
3845 if (ret) {
3846 errno = ret;
b8aa1682 3847 PERROR("pthread_create dispatcher");
178a0557
MD
3848 retval = -1;
3849 goto exit_dispatcher_thread;
b8aa1682
JD
3850 }
3851
3852 /* Setup the worker thread */
1a1a34b4 3853 ret = pthread_create(&worker_thread, default_pthread_attr(),
7591bab1 3854 relay_thread_worker, NULL);
178a0557
MD
3855 if (ret) {
3856 errno = ret;
b8aa1682 3857 PERROR("pthread_create worker");
178a0557
MD
3858 retval = -1;
3859 goto exit_worker_thread;
b8aa1682
JD
3860 }
3861
3862 /* Setup the listener thread */
1a1a34b4 3863 ret = pthread_create(&listener_thread, default_pthread_attr(),
b8aa1682 3864 relay_thread_listener, (void *) NULL);
178a0557
MD
3865 if (ret) {
3866 errno = ret;
b8aa1682 3867 PERROR("pthread_create listener");
178a0557
MD
3868 retval = -1;
3869 goto exit_listener_thread;
b8aa1682
JD
3870 }
3871
7591bab1 3872 ret = relayd_live_create(live_uri);
178a0557 3873 if (ret) {
d3e2ba59 3874 ERR("Starting live viewer threads");
178a0557 3875 retval = -1;
50138f51 3876 goto exit_live;
d3e2ba59
JD
3877 }
3878
178a0557
MD
3879 /*
3880 * This is where we start awaiting program completion (e.g. through
3881 * signal that asks threads to teardown).
3882 */
3883
3884 ret = relayd_live_join();
3885 if (ret) {
3886 retval = -1;
3887 }
50138f51 3888exit_live:
178a0557 3889
b8aa1682 3890 ret = pthread_join(listener_thread, &status);
178a0557
MD
3891 if (ret) {
3892 errno = ret;
3893 PERROR("pthread_join listener_thread");
3894 retval = -1;
b8aa1682
JD
3895 }
3896
178a0557 3897exit_listener_thread:
b8aa1682 3898 ret = pthread_join(worker_thread, &status);
178a0557
MD
3899 if (ret) {
3900 errno = ret;
3901 PERROR("pthread_join worker_thread");
3902 retval = -1;
b8aa1682
JD
3903 }
3904
178a0557 3905exit_worker_thread:
b8aa1682 3906 ret = pthread_join(dispatcher_thread, &status);
178a0557
MD
3907 if (ret) {
3908 errno = ret;
3909 PERROR("pthread_join dispatcher_thread");
3910 retval = -1;
b8aa1682 3911 }
178a0557 3912exit_dispatcher_thread:
42415026 3913
65931c8b 3914 ret = pthread_join(health_thread, &status);
178a0557
MD
3915 if (ret) {
3916 errno = ret;
3917 PERROR("pthread_join health_thread");
3918 retval = -1;
65931c8b 3919 }
178a0557 3920exit_health_thread:
65931c8b 3921
65931c8b 3922 utils_close_pipe(health_quit_pipe);
178a0557 3923exit_health_quit_pipe:
65931c8b 3924
178a0557 3925exit_init_data:
55706a7d 3926 health_app_destroy(health_relayd);
23c8ff50 3927 sessiond_trace_chunk_registry_destroy(sessiond_trace_chunk_registry);
55706a7d 3928exit_health_app_create:
23c8ff50 3929exit_sessiond_trace_chunk_registry:
178a0557 3930exit_options:
4d62fbf8
MD
3931 /*
3932 * Wait for all pending call_rcu work to complete before tearing
3933 * down data structures. call_rcu worker may be trying to
3934 * perform lookups in those structures.
3935 */
3936 rcu_barrier();
7591bab1
MD
3937 relayd_cleanup();
3938
3939 /* Ensure all prior call_rcu are done. */
3940 rcu_barrier();
d3e2ba59 3941
178a0557 3942 if (!retval) {
b8aa1682 3943 exit(EXIT_SUCCESS);
178a0557
MD
3944 } else {
3945 exit(EXIT_FAILURE);
b8aa1682 3946 }
b8aa1682 3947}
This page took 0.29595 seconds and 5 git commands to generate.