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