Fix: don't expose empty streams
[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
21#define _GNU_SOURCE
6c1c0768 22#define _LGPL_SOURCE
b8aa1682
JD
23#include <getopt.h>
24#include <grp.h>
25#include <limits.h>
26#include <pthread.h>
27#include <signal.h>
28#include <stdio.h>
29#include <stdlib.h>
30#include <string.h>
31#include <sys/mman.h>
32#include <sys/mount.h>
33#include <sys/resource.h>
34#include <sys/socket.h>
35#include <sys/stat.h>
36#include <sys/types.h>
37#include <sys/wait.h>
173af62f 38#include <inttypes.h>
b8aa1682
JD
39#include <urcu/futex.h>
40#include <urcu/uatomic.h>
41#include <unistd.h>
42#include <fcntl.h>
43#include <config.h>
44
45#include <lttng/lttng.h>
46#include <common/common.h>
47#include <common/compat/poll.h>
48#include <common/compat/socket.h>
f263b7fd 49#include <common/compat/endian.h>
e8fa9fb0 50#include <common/compat/getenv.h>
b8aa1682 51#include <common/defaults.h>
3fd27398 52#include <common/daemonize.h>
b8aa1682
JD
53#include <common/futex.h>
54#include <common/sessiond-comm/sessiond-comm.h>
55#include <common/sessiond-comm/inet.h>
b8aa1682
JD
56#include <common/sessiond-comm/relayd.h>
57#include <common/uri.h>
a02de639 58#include <common/utils.h>
cd60b05a 59#include <common/config/config.h>
7591bab1 60#include <urcu/rculist.h>
b8aa1682 61
0f907de1 62#include "cmd.h"
d3e2ba59 63#include "ctf-trace.h"
1c20f0e2 64#include "index.h"
0f907de1 65#include "utils.h"
b8aa1682 66#include "lttng-relayd.h"
d3e2ba59 67#include "live.h"
55706a7d 68#include "health-relayd.h"
9b5e0863 69#include "testpoint.h"
2f8f53af 70#include "viewer-stream.h"
2a174661
DG
71#include "session.h"
72#include "stream.h"
58eb9381 73#include "connection.h"
b8aa1682
JD
74
75/* command line options */
0f907de1 76char *opt_output_path;
b5218ffb 77static int opt_daemon, opt_background;
3fd27398
MD
78
79/*
80 * We need to wait for listener and live listener threads, as well as
81 * health check thread, before being ready to signal readiness.
82 */
83#define NR_LTTNG_RELAY_READY 3
84static int lttng_relay_ready = NR_LTTNG_RELAY_READY;
85static int recv_child_signal; /* Set to 1 when a SIGUSR1 signal is received. */
86static pid_t child_ppid; /* Internal parent PID use with daemonize. */
87
095a4ae5
MD
88static struct lttng_uri *control_uri;
89static struct lttng_uri *data_uri;
d3e2ba59 90static struct lttng_uri *live_uri;
b8aa1682
JD
91
92const char *progname;
b8aa1682 93
65931c8b 94const char *tracing_group_name = DEFAULT_TRACING_GROUP;
cd60b05a
JG
95static int tracing_group_name_override;
96
97const char * const config_section_name = "relayd";
65931c8b 98
b8aa1682
JD
99/*
100 * Quit pipe for all threads. This permits a single cancellation point
101 * for all threads when receiving an event on the pipe.
102 */
0b242f62 103int thread_quit_pipe[2] = { -1, -1 };
b8aa1682
JD
104
105/*
106 * This pipe is used to inform the worker thread that a command is queued and
107 * ready to be processed.
108 */
58eb9381 109static int relay_conn_pipe[2] = { -1, -1 };
b8aa1682 110
26c9d55e 111/* Shared between threads */
b8aa1682
JD
112static int dispatch_thread_exit;
113
114static pthread_t listener_thread;
115static pthread_t dispatcher_thread;
116static pthread_t worker_thread;
65931c8b 117static pthread_t health_thread;
b8aa1682 118
7591bab1
MD
119/*
120 * last_relay_stream_id_lock protects last_relay_stream_id increment
121 * atomicity on 32-bit architectures.
122 */
123static pthread_mutex_t last_relay_stream_id_lock = PTHREAD_MUTEX_INITIALIZER;
095a4ae5 124static uint64_t last_relay_stream_id;
b8aa1682
JD
125
126/*
127 * Relay command queue.
128 *
129 * The relay_thread_listener and relay_thread_dispatcher communicate with this
130 * queue.
131 */
58eb9381 132static struct relay_conn_queue relay_conn_queue;
b8aa1682
JD
133
134/* buffer allocated at startup, used to store the trace data */
095a4ae5
MD
135static char *data_buffer;
136static unsigned int data_buffer_size;
b8aa1682 137
d3e2ba59
JD
138/* Global relay stream hash table. */
139struct lttng_ht *relay_streams_ht;
140
92c6ca54
DG
141/* Global relay viewer stream hash table. */
142struct lttng_ht *viewer_streams_ht;
143
7591bab1
MD
144/* Global relay sessions hash table. */
145struct lttng_ht *sessions_ht;
0a6518b0 146
55706a7d 147/* Relayd health monitoring */
eea7556c 148struct health_app *health_relayd;
55706a7d 149
cd60b05a
JG
150static struct option long_options[] = {
151 { "control-port", 1, 0, 'C', },
152 { "data-port", 1, 0, 'D', },
8d5c808e 153 { "live-port", 1, 0, 'L', },
cd60b05a 154 { "daemonize", 0, 0, 'd', },
b5218ffb 155 { "background", 0, 0, 'b', },
cd60b05a
JG
156 { "group", 1, 0, 'g', },
157 { "help", 0, 0, 'h', },
158 { "output", 1, 0, 'o', },
159 { "verbose", 0, 0, 'v', },
160 { "config", 1, 0, 'f' },
161 { NULL, 0, 0, 0, },
162};
163
164static const char *config_ignore_options[] = { "help", "config" };
165
b8aa1682
JD
166/*
167 * usage function on stderr
168 */
7591bab1 169static void usage(void)
b8aa1682
JD
170{
171 fprintf(stderr, "Usage: %s OPTIONS\n\nOptions:\n", progname);
994fa64f
DG
172 fprintf(stderr, " -h, --help Display this usage.\n");
173 fprintf(stderr, " -d, --daemonize Start as a daemon.\n");
b5218ffb 174 fprintf(stderr, " -b, --background Start as a daemon, keeping console open.\n");
994fa64f
DG
175 fprintf(stderr, " -C, --control-port URL Control port listening.\n");
176 fprintf(stderr, " -D, --data-port URL Data port listening.\n");
8d5c808e 177 fprintf(stderr, " -L, --live-port URL Live view port listening.\n");
994fa64f
DG
178 fprintf(stderr, " -o, --output PATH Output path for traces. Must use an absolute path.\n");
179 fprintf(stderr, " -v, --verbose Verbose mode. Activate DBG() macro.\n");
65931c8b 180 fprintf(stderr, " -g, --group NAME Specify the tracing group name. (default: tracing)\n");
cd60b05a 181 fprintf(stderr, " -f --config Load daemon configuration file\n");
b8aa1682
JD
182}
183
cd60b05a
JG
184/*
185 * Take an option from the getopt output and set it in the right variable to be
186 * used later.
187 *
188 * Return 0 on success else a negative value.
189 */
7591bab1 190static int set_option(int opt, const char *arg, const char *optname)
b8aa1682 191{
cd60b05a
JG
192 int ret;
193
194 switch (opt) {
195 case 0:
196 fprintf(stderr, "option %s", optname);
197 if (arg) {
198 fprintf(stderr, " with arg %s\n", arg);
199 }
200 break;
201 case 'C':
e8fa9fb0
MD
202 if (lttng_is_setuid_setgid()) {
203 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
204 "-C, --control-port");
205 } else {
206 ret = uri_parse(arg, &control_uri);
207 if (ret < 0) {
208 ERR("Invalid control URI specified");
209 goto end;
210 }
211 if (control_uri->port == 0) {
212 control_uri->port = DEFAULT_NETWORK_CONTROL_PORT;
213 }
cd60b05a
JG
214 }
215 break;
216 case 'D':
e8fa9fb0
MD
217 if (lttng_is_setuid_setgid()) {
218 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
219 "-D, -data-port");
220 } else {
221 ret = uri_parse(arg, &data_uri);
222 if (ret < 0) {
223 ERR("Invalid data URI specified");
224 goto end;
225 }
226 if (data_uri->port == 0) {
227 data_uri->port = DEFAULT_NETWORK_DATA_PORT;
228 }
cd60b05a
JG
229 }
230 break;
8d5c808e 231 case 'L':
e8fa9fb0
MD
232 if (lttng_is_setuid_setgid()) {
233 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
234 "-L, -live-port");
235 } else {
236 ret = uri_parse(arg, &live_uri);
237 if (ret < 0) {
238 ERR("Invalid live URI specified");
239 goto end;
240 }
241 if (live_uri->port == 0) {
242 live_uri->port = DEFAULT_NETWORK_VIEWER_PORT;
243 }
8d5c808e
AM
244 }
245 break;
cd60b05a
JG
246 case 'd':
247 opt_daemon = 1;
248 break;
b5218ffb
MD
249 case 'b':
250 opt_background = 1;
251 break;
cd60b05a 252 case 'g':
e8fa9fb0
MD
253 if (lttng_is_setuid_setgid()) {
254 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
255 "-g, --group");
256 } else {
257 tracing_group_name = strdup(arg);
258 if (tracing_group_name == NULL) {
259 ret = -errno;
260 PERROR("strdup");
261 goto end;
262 }
263 tracing_group_name_override = 1;
330a40bb 264 }
cd60b05a
JG
265 break;
266 case 'h':
267 usage();
268 exit(EXIT_FAILURE);
269 case 'o':
e8fa9fb0
MD
270 if (lttng_is_setuid_setgid()) {
271 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
272 "-o, --output");
273 } else {
274 ret = asprintf(&opt_output_path, "%s", arg);
275 if (ret < 0) {
276 ret = -errno;
277 PERROR("asprintf opt_output_path");
278 goto end;
279 }
cd60b05a
JG
280 }
281 break;
282 case 'v':
283 /* Verbose level can increase using multiple -v */
284 if (arg) {
285 lttng_opt_verbose = config_parse_value(arg);
286 } else {
849e5b7b
DG
287 /* Only 3 level of verbosity (-vvv). */
288 if (lttng_opt_verbose < 3) {
289 lttng_opt_verbose += 1;
290 }
cd60b05a
JG
291 }
292 break;
293 default:
294 /* Unknown option or other error.
295 * Error is printed by getopt, just return */
296 ret = -1;
297 goto end;
298 }
299
300 /* All good. */
301 ret = 0;
302
303end:
304 return ret;
305}
306
307/*
308 * config_entry_handler_cb used to handle options read from a config file.
309 * See config_entry_handler_cb comment in common/config/config.h for the
310 * return value conventions.
311 */
7591bab1 312static int config_entry_handler(const struct config_entry *entry, void *unused)
cd60b05a
JG
313{
314 int ret = 0, i;
315
316 if (!entry || !entry->name || !entry->value) {
317 ret = -EINVAL;
318 goto end;
319 }
320
321 /* Check if the option is to be ignored */
322 for (i = 0; i < sizeof(config_ignore_options) / sizeof(char *); i++) {
323 if (!strcmp(entry->name, config_ignore_options[i])) {
324 goto end;
325 }
326 }
327
328 for (i = 0; i < (sizeof(long_options) / sizeof(struct option)) - 1; i++) {
329 /* Ignore if entry name is not fully matched. */
330 if (strcmp(entry->name, long_options[i].name)) {
331 continue;
332 }
333
334 /*
7591bab1
MD
335 * If the option takes no argument on the command line,
336 * we have to check if the value is "true". We support
337 * non-zero numeric values, true, on and yes.
cd60b05a
JG
338 */
339 if (!long_options[i].has_arg) {
340 ret = config_parse_value(entry->value);
341 if (ret <= 0) {
342 if (ret) {
343 WARN("Invalid configuration value \"%s\" for option %s",
344 entry->value, entry->name);
345 }
346 /* False, skip boolean config option. */
347 goto end;
348 }
349 }
350
351 ret = set_option(long_options[i].val, entry->value, entry->name);
352 goto end;
353 }
354
355 WARN("Unrecognized option \"%s\" in daemon configuration file.",
356 entry->name);
357
358end:
359 return ret;
360}
361
7591bab1 362static int set_options(int argc, char **argv)
cd60b05a 363{
178a0557 364 int c, ret = 0, option_index = 0, retval = 0;
cd60b05a
JG
365 int orig_optopt = optopt, orig_optind = optind;
366 char *default_address, *optstring;
367 const char *config_path = NULL;
368
369 optstring = utils_generate_optstring(long_options,
370 sizeof(long_options) / sizeof(struct option));
371 if (!optstring) {
178a0557 372 retval = -ENOMEM;
cd60b05a
JG
373 goto exit;
374 }
375
376 /* Check for the --config option */
377
378 while ((c = getopt_long(argc, argv, optstring, long_options,
379 &option_index)) != -1) {
380 if (c == '?') {
178a0557 381 retval = -EINVAL;
cd60b05a
JG
382 goto exit;
383 } else if (c != 'f') {
384 continue;
385 }
386
e8fa9fb0
MD
387 if (lttng_is_setuid_setgid()) {
388 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
389 "-f, --config");
390 } else {
391 config_path = utils_expand_path(optarg);
392 if (!config_path) {
393 ERR("Failed to resolve path: %s", optarg);
394 }
cd60b05a
JG
395 }
396 }
397
398 ret = config_get_section_entries(config_path, config_section_name,
399 config_entry_handler, NULL);
400 if (ret) {
401 if (ret > 0) {
402 ERR("Invalid configuration option at line %i", ret);
cd60b05a 403 }
178a0557 404 retval = -1;
cd60b05a
JG
405 goto exit;
406 }
b8aa1682 407
cd60b05a
JG
408 /* Reset getopt's global state */
409 optopt = orig_optopt;
410 optind = orig_optind;
b8aa1682 411 while (1) {
cd60b05a 412 c = getopt_long(argc, argv, optstring, long_options, &option_index);
b8aa1682
JD
413 if (c == -1) {
414 break;
415 }
416
cd60b05a
JG
417 ret = set_option(c, optarg, long_options[option_index].name);
418 if (ret < 0) {
178a0557 419 retval = -1;
b8aa1682
JD
420 goto exit;
421 }
422 }
423
424 /* assign default values */
425 if (control_uri == NULL) {
fa91dc52
MD
426 ret = asprintf(&default_address,
427 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS ":%d",
428 DEFAULT_NETWORK_CONTROL_PORT);
b8aa1682
JD
429 if (ret < 0) {
430 PERROR("asprintf default data address");
178a0557 431 retval = -1;
b8aa1682
JD
432 goto exit;
433 }
434
435 ret = uri_parse(default_address, &control_uri);
436 free(default_address);
437 if (ret < 0) {
438 ERR("Invalid control URI specified");
178a0557 439 retval = -1;
b8aa1682
JD
440 goto exit;
441 }
442 }
443 if (data_uri == NULL) {
fa91dc52
MD
444 ret = asprintf(&default_address,
445 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS ":%d",
446 DEFAULT_NETWORK_DATA_PORT);
b8aa1682
JD
447 if (ret < 0) {
448 PERROR("asprintf default data address");
178a0557 449 retval = -1;
b8aa1682
JD
450 goto exit;
451 }
452
453 ret = uri_parse(default_address, &data_uri);
454 free(default_address);
455 if (ret < 0) {
456 ERR("Invalid data URI specified");
178a0557 457 retval = -1;
b8aa1682
JD
458 goto exit;
459 }
460 }
d3e2ba59 461 if (live_uri == NULL) {
fa91dc52
MD
462 ret = asprintf(&default_address,
463 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS ":%d",
464 DEFAULT_NETWORK_VIEWER_PORT);
d3e2ba59
JD
465 if (ret < 0) {
466 PERROR("asprintf default viewer control address");
178a0557 467 retval = -1;
d3e2ba59
JD
468 goto exit;
469 }
470
471 ret = uri_parse(default_address, &live_uri);
472 free(default_address);
473 if (ret < 0) {
474 ERR("Invalid viewer control URI specified");
178a0557 475 retval = -1;
d3e2ba59
JD
476 goto exit;
477 }
478 }
b8aa1682
JD
479
480exit:
cd60b05a 481 free(optstring);
178a0557 482 return retval;
b8aa1682
JD
483}
484
7591bab1
MD
485static void print_global_objects(void)
486{
487 rcu_register_thread();
488
489 print_viewer_streams();
490 print_relay_streams();
491 print_sessions();
492
493 rcu_unregister_thread();
494}
495
b8aa1682
JD
496/*
497 * Cleanup the daemon
498 */
7591bab1 499static void relayd_cleanup(void)
b8aa1682 500{
7591bab1
MD
501 print_global_objects();
502
b8aa1682
JD
503 DBG("Cleaning up");
504
178a0557
MD
505 if (viewer_streams_ht)
506 lttng_ht_destroy(viewer_streams_ht);
507 if (relay_streams_ht)
508 lttng_ht_destroy(relay_streams_ht);
7591bab1
MD
509 if (sessions_ht)
510 lttng_ht_destroy(sessions_ht);
178a0557 511
095a4ae5
MD
512 /* free the dynamically allocated opt_output_path */
513 free(opt_output_path);
514
a02de639
CB
515 /* Close thread quit pipes */
516 utils_close_pipe(thread_quit_pipe);
517
710c1f73
DG
518 uri_free(control_uri);
519 uri_free(data_uri);
8d5c808e 520 /* Live URI is freed in the live thread. */
cd60b05a
JG
521
522 if (tracing_group_name_override) {
523 free((void *) tracing_group_name);
524 }
b8aa1682
JD
525}
526
527/*
528 * Write to writable pipe used to notify a thread.
529 */
7591bab1 530static int notify_thread_pipe(int wpipe)
b8aa1682 531{
6cd525e8 532 ssize_t ret;
b8aa1682 533
6cd525e8
MD
534 ret = lttng_write(wpipe, "!", 1);
535 if (ret < 1) {
b8aa1682 536 PERROR("write poll pipe");
b4aacfdc 537 goto end;
b8aa1682 538 }
b4aacfdc
MD
539 ret = 0;
540end:
b8aa1682
JD
541 return ret;
542}
543
7591bab1 544static int notify_health_quit_pipe(int *pipe)
65931c8b 545{
6cd525e8 546 ssize_t ret;
65931c8b 547
6cd525e8
MD
548 ret = lttng_write(pipe[1], "4", 1);
549 if (ret < 1) {
65931c8b 550 PERROR("write relay health quit");
b4aacfdc 551 goto end;
65931c8b 552 }
b4aacfdc
MD
553 ret = 0;
554end:
555 return ret;
65931c8b
MD
556}
557
b8aa1682 558/*
b4aacfdc 559 * Stop all relayd and relayd-live threads.
b8aa1682 560 */
b4aacfdc 561int lttng_relay_stop_threads(void)
b8aa1682 562{
b4aacfdc 563 int retval = 0;
b8aa1682
JD
564
565 /* Stopping all threads */
566 DBG("Terminating all threads");
b4aacfdc 567 if (notify_thread_pipe(thread_quit_pipe[1])) {
b8aa1682 568 ERR("write error on thread quit pipe");
b4aacfdc 569 retval = -1;
b8aa1682
JD
570 }
571
b4aacfdc
MD
572 if (notify_health_quit_pipe(health_quit_pipe)) {
573 ERR("write error on health quit pipe");
574 }
65931c8b 575
b8aa1682 576 /* Dispatch thread */
26c9d55e 577 CMM_STORE_SHARED(dispatch_thread_exit, 1);
58eb9381 578 futex_nto1_wake(&relay_conn_queue.futex);
178a0557 579
b4aacfdc 580 if (relayd_live_stop()) {
178a0557 581 ERR("Error stopping live threads");
b4aacfdc 582 retval = -1;
178a0557 583 }
b4aacfdc 584 return retval;
b8aa1682
JD
585}
586
587/*
588 * Signal handler for the daemon
589 *
590 * Simply stop all worker threads, leaving main() return gracefully after
591 * joining all threads and calling cleanup().
592 */
7591bab1 593static void sighandler(int sig)
b8aa1682
JD
594{
595 switch (sig) {
596 case SIGPIPE:
597 DBG("SIGPIPE caught");
598 return;
599 case SIGINT:
600 DBG("SIGINT caught");
b4aacfdc
MD
601 if (lttng_relay_stop_threads()) {
602 ERR("Error stopping threads");
603 }
b8aa1682
JD
604 break;
605 case SIGTERM:
606 DBG("SIGTERM caught");
b4aacfdc
MD
607 if (lttng_relay_stop_threads()) {
608 ERR("Error stopping threads");
609 }
b8aa1682 610 break;
3fd27398
MD
611 case SIGUSR1:
612 CMM_STORE_SHARED(recv_child_signal, 1);
613 break;
b8aa1682
JD
614 default:
615 break;
616 }
617}
618
619/*
620 * Setup signal handler for :
621 * SIGINT, SIGTERM, SIGPIPE
622 */
7591bab1 623static int set_signal_handler(void)
b8aa1682
JD
624{
625 int ret = 0;
626 struct sigaction sa;
627 sigset_t sigset;
628
629 if ((ret = sigemptyset(&sigset)) < 0) {
630 PERROR("sigemptyset");
631 return ret;
632 }
633
634 sa.sa_handler = sighandler;
635 sa.sa_mask = sigset;
636 sa.sa_flags = 0;
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
647 if ((ret = sigaction(SIGPIPE, &sa, NULL)) < 0) {
648 PERROR("sigaction");
649 return ret;
650 }
651
3fd27398
MD
652 if ((ret = sigaction(SIGUSR1, &sa, NULL)) < 0) {
653 PERROR("sigaction");
654 return ret;
655 }
656
657 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
b8aa1682
JD
658
659 return ret;
660}
661
3fd27398
MD
662void lttng_relay_notify_ready(void)
663{
664 /* Notify the parent of the fork() process that we are ready. */
665 if (opt_daemon || opt_background) {
666 if (uatomic_sub_return(&lttng_relay_ready, 1) == 0) {
667 kill(child_ppid, SIGUSR1);
668 }
669 }
670}
671
b8aa1682
JD
672/*
673 * Init thread quit pipe.
674 *
675 * Return -1 on error or 0 if all pipes are created.
676 */
7591bab1 677static int init_thread_quit_pipe(void)
b8aa1682 678{
a02de639 679 int ret;
b8aa1682 680
a02de639 681 ret = utils_create_pipe_cloexec(thread_quit_pipe);
b8aa1682 682
b8aa1682
JD
683 return ret;
684}
685
686/*
687 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
688 */
7591bab1 689static int create_thread_poll_set(struct lttng_poll_event *events, int size)
b8aa1682
JD
690{
691 int ret;
692
693 if (events == NULL || size == 0) {
694 ret = -1;
695 goto error;
696 }
697
698 ret = lttng_poll_create(events, size, LTTNG_CLOEXEC);
699 if (ret < 0) {
700 goto error;
701 }
702
703 /* Add quit pipe */
c7759e6a 704 ret = lttng_poll_add(events, thread_quit_pipe[0], LPOLLIN | LPOLLERR);
b8aa1682
JD
705 if (ret < 0) {
706 goto error;
707 }
708
709 return 0;
710
711error:
712 return ret;
713}
714
715/*
716 * Check if the thread quit pipe was triggered.
717 *
718 * Return 1 if it was triggered else 0;
719 */
7591bab1 720static int check_thread_quit_pipe(int fd, uint32_t events)
b8aa1682
JD
721{
722 if (fd == thread_quit_pipe[0] && (events & LPOLLIN)) {
723 return 1;
724 }
725
726 return 0;
727}
728
729/*
730 * Create and init socket from uri.
731 */
7591bab1 732static struct lttcomm_sock *relay_socket_create(struct lttng_uri *uri)
b8aa1682
JD
733{
734 int ret;
735 struct lttcomm_sock *sock = NULL;
736
737 sock = lttcomm_alloc_sock_from_uri(uri);
738 if (sock == NULL) {
739 ERR("Allocating socket");
740 goto error;
741 }
742
743 ret = lttcomm_create_sock(sock);
744 if (ret < 0) {
745 goto error;
746 }
747 DBG("Listening on sock %d", sock->fd);
748
749 ret = sock->ops->bind(sock);
750 if (ret < 0) {
751 goto error;
752 }
753
754 ret = sock->ops->listen(sock, -1);
755 if (ret < 0) {
756 goto error;
757
758 }
759
760 return sock;
761
762error:
763 if (sock) {
764 lttcomm_destroy_sock(sock);
765 }
766 return NULL;
767}
768
769/*
770 * This thread manages the listening for new connections on the network
771 */
7591bab1 772static void *relay_thread_listener(void *data)
b8aa1682 773{
095a4ae5 774 int i, ret, pollfd, err = -1;
b8aa1682
JD
775 uint32_t revents, nb_fd;
776 struct lttng_poll_event events;
777 struct lttcomm_sock *control_sock, *data_sock;
778
b8aa1682
JD
779 DBG("[thread] Relay listener started");
780
55706a7d
MD
781 health_register(health_relayd, HEALTH_RELAYD_TYPE_LISTENER);
782
f385ae0a
MD
783 health_code_update();
784
7591bab1 785 control_sock = relay_socket_create(control_uri);
b8aa1682 786 if (!control_sock) {
095a4ae5 787 goto error_sock_control;
b8aa1682
JD
788 }
789
7591bab1 790 data_sock = relay_socket_create(data_uri);
b8aa1682 791 if (!data_sock) {
095a4ae5 792 goto error_sock_relay;
b8aa1682
JD
793 }
794
795 /*
7591bab1
MD
796 * Pass 3 as size here for the thread quit pipe, control and
797 * data socket.
b8aa1682
JD
798 */
799 ret = create_thread_poll_set(&events, 3);
800 if (ret < 0) {
801 goto error_create_poll;
802 }
803
804 /* Add the control socket */
805 ret = lttng_poll_add(&events, control_sock->fd, LPOLLIN | LPOLLRDHUP);
806 if (ret < 0) {
807 goto error_poll_add;
808 }
809
810 /* Add the data socket */
811 ret = lttng_poll_add(&events, data_sock->fd, LPOLLIN | LPOLLRDHUP);
812 if (ret < 0) {
813 goto error_poll_add;
814 }
815
3fd27398
MD
816 lttng_relay_notify_ready();
817
9b5e0863
MD
818 if (testpoint(relayd_thread_listener)) {
819 goto error_testpoint;
820 }
821
b8aa1682 822 while (1) {
f385ae0a
MD
823 health_code_update();
824
b8aa1682
JD
825 DBG("Listener accepting connections");
826
b8aa1682 827restart:
f385ae0a 828 health_poll_entry();
b8aa1682 829 ret = lttng_poll_wait(&events, -1);
f385ae0a 830 health_poll_exit();
b8aa1682
JD
831 if (ret < 0) {
832 /*
833 * Restart interrupted system call.
834 */
835 if (errno == EINTR) {
836 goto restart;
837 }
838 goto error;
839 }
840
0d9c5d77
DG
841 nb_fd = ret;
842
b8aa1682
JD
843 DBG("Relay new connection received");
844 for (i = 0; i < nb_fd; i++) {
f385ae0a
MD
845 health_code_update();
846
b8aa1682
JD
847 /* Fetch once the poll data */
848 revents = LTTNG_POLL_GETEV(&events, i);
849 pollfd = LTTNG_POLL_GETFD(&events, i);
850
fd20dac9 851 if (!revents) {
7591bab1
MD
852 /*
853 * No activity for this FD (poll
854 * implementation).
855 */
fd20dac9
MD
856 continue;
857 }
858
b8aa1682
JD
859 /* Thread quit pipe has been closed. Killing thread. */
860 ret = check_thread_quit_pipe(pollfd, revents);
861 if (ret) {
095a4ae5
MD
862 err = 0;
863 goto exit;
b8aa1682
JD
864 }
865
866 if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
867 ERR("socket poll error");
868 goto error;
869 } else if (revents & LPOLLIN) {
4b7f17b2 870 /*
7591bab1
MD
871 * A new connection is requested, therefore a
872 * sessiond/consumerd connection is allocated in
873 * this thread, enqueued to a global queue and
874 * dequeued (and freed) in the worker thread.
4b7f17b2 875 */
58eb9381
DG
876 int val = 1;
877 struct relay_connection *new_conn;
4b7f17b2 878 struct lttcomm_sock *newsock;
7591bab1 879 enum connection_type type;
b8aa1682
JD
880
881 if (pollfd == data_sock->fd) {
7591bab1 882 type = RELAY_DATA;
b8aa1682 883 newsock = data_sock->ops->accept(data_sock);
58eb9381
DG
884 DBG("Relay data connection accepted, socket %d",
885 newsock->fd);
4b7f17b2
MD
886 } else {
887 assert(pollfd == control_sock->fd);
7591bab1 888 type = RELAY_CONTROL;
b8aa1682 889 newsock = control_sock->ops->accept(control_sock);
58eb9381
DG
890 DBG("Relay control connection accepted, socket %d",
891 newsock->fd);
b8aa1682 892 }
58eb9381
DG
893 if (!newsock) {
894 PERROR("accepting sock");
58eb9381
DG
895 goto error;
896 }
897
898 ret = setsockopt(newsock->fd, SOL_SOCKET, SO_REUSEADDR, &val,
899 sizeof(val));
b8aa1682
JD
900 if (ret < 0) {
901 PERROR("setsockopt inet");
4b7f17b2 902 lttcomm_destroy_sock(newsock);
b8aa1682
JD
903 goto error;
904 }
7591bab1
MD
905 new_conn = connection_create(newsock, type);
906 if (!new_conn) {
907 lttcomm_destroy_sock(newsock);
908 goto error;
909 }
58eb9381
DG
910
911 /* Enqueue request for the dispatcher thread. */
8bdee6e2
SM
912 cds_wfcq_enqueue(&relay_conn_queue.head, &relay_conn_queue.tail,
913 &new_conn->qnode);
b8aa1682
JD
914
915 /*
7591bab1
MD
916 * Wake the dispatch queue futex.
917 * Implicit memory barrier with the
918 * exchange in cds_wfcq_enqueue.
b8aa1682 919 */
58eb9381 920 futex_nto1_wake(&relay_conn_queue.futex);
b8aa1682
JD
921 }
922 }
923 }
924
095a4ae5 925exit:
b8aa1682
JD
926error:
927error_poll_add:
9b5e0863 928error_testpoint:
b8aa1682
JD
929 lttng_poll_clean(&events);
930error_create_poll:
095a4ae5
MD
931 if (data_sock->fd >= 0) {
932 ret = data_sock->ops->close(data_sock);
b8aa1682
JD
933 if (ret) {
934 PERROR("close");
935 }
b8aa1682 936 }
095a4ae5
MD
937 lttcomm_destroy_sock(data_sock);
938error_sock_relay:
939 if (control_sock->fd >= 0) {
940 ret = control_sock->ops->close(control_sock);
b8aa1682
JD
941 if (ret) {
942 PERROR("close");
943 }
b8aa1682 944 }
095a4ae5
MD
945 lttcomm_destroy_sock(control_sock);
946error_sock_control:
947 if (err) {
f385ae0a
MD
948 health_error();
949 ERR("Health error occurred in %s", __func__);
095a4ae5 950 }
55706a7d 951 health_unregister(health_relayd);
b8aa1682 952 DBG("Relay listener thread cleanup complete");
b4aacfdc 953 lttng_relay_stop_threads();
b8aa1682
JD
954 return NULL;
955}
956
957/*
958 * This thread manages the dispatching of the requests to worker threads
959 */
7591bab1 960static void *relay_thread_dispatcher(void *data)
b8aa1682 961{
6cd525e8
MD
962 int err = -1;
963 ssize_t ret;
8bdee6e2 964 struct cds_wfcq_node *node;
58eb9381 965 struct relay_connection *new_conn = NULL;
b8aa1682
JD
966
967 DBG("[thread] Relay dispatcher started");
968
55706a7d
MD
969 health_register(health_relayd, HEALTH_RELAYD_TYPE_DISPATCHER);
970
9b5e0863
MD
971 if (testpoint(relayd_thread_dispatcher)) {
972 goto error_testpoint;
973 }
974
f385ae0a
MD
975 health_code_update();
976
26c9d55e 977 while (!CMM_LOAD_SHARED(dispatch_thread_exit)) {
f385ae0a
MD
978 health_code_update();
979
b8aa1682 980 /* Atomically prepare the queue futex */
58eb9381 981 futex_nto1_prepare(&relay_conn_queue.futex);
b8aa1682
JD
982
983 do {
f385ae0a
MD
984 health_code_update();
985
b8aa1682 986 /* Dequeue commands */
8bdee6e2
SM
987 node = cds_wfcq_dequeue_blocking(&relay_conn_queue.head,
988 &relay_conn_queue.tail);
b8aa1682
JD
989 if (node == NULL) {
990 DBG("Woken up but nothing in the relay command queue");
991 /* Continue thread execution */
992 break;
993 }
58eb9381 994 new_conn = caa_container_of(node, struct relay_connection, qnode);
b8aa1682 995
58eb9381 996 DBG("Dispatching request waiting on sock %d", new_conn->sock->fd);
b8aa1682
JD
997
998 /*
7591bab1
MD
999 * Inform worker thread of the new request. This
1000 * call is blocking so we can be assured that
1001 * the data will be read at some point in time
1002 * or wait to the end of the world :)
b8aa1682 1003 */
58eb9381
DG
1004 ret = lttng_write(relay_conn_pipe[1], &new_conn, sizeof(new_conn));
1005 if (ret < 0) {
1006 PERROR("write connection pipe");
7591bab1 1007 connection_put(new_conn);
b8aa1682
JD
1008 goto error;
1009 }
1010 } while (node != NULL);
1011
1012 /* Futex wait on queue. Blocking call on futex() */
f385ae0a 1013 health_poll_entry();
58eb9381 1014 futex_nto1_wait(&relay_conn_queue.futex);
f385ae0a 1015 health_poll_exit();
b8aa1682
JD
1016 }
1017
f385ae0a
MD
1018 /* Normal exit, no error */
1019 err = 0;
1020
b8aa1682 1021error:
9b5e0863 1022error_testpoint:
f385ae0a
MD
1023 if (err) {
1024 health_error();
1025 ERR("Health error occurred in %s", __func__);
1026 }
55706a7d 1027 health_unregister(health_relayd);
b8aa1682 1028 DBG("Dispatch thread dying");
b4aacfdc 1029 lttng_relay_stop_threads();
b8aa1682
JD
1030 return NULL;
1031}
1032
b8aa1682 1033/*
7591bab1 1034 * Set index data from the control port to a given index object.
b8aa1682 1035 */
7591bab1 1036static int set_index_control_data(struct relay_index *index,
1c20f0e2
JD
1037 struct lttcomm_relayd_index *data)
1038{
7591bab1 1039 struct ctf_packet_index index_data;
1c20f0e2
JD
1040
1041 /*
7591bab1
MD
1042 * The index on disk is encoded in big endian, so we don't need
1043 * to convert the data received on the network. The data_offset
1044 * value is NEVER modified here and is updated by the data
1045 * thread.
1c20f0e2 1046 */
7591bab1
MD
1047 index_data.packet_size = data->packet_size;
1048 index_data.content_size = data->content_size;
1049 index_data.timestamp_begin = data->timestamp_begin;
1050 index_data.timestamp_end = data->timestamp_end;
1051 index_data.events_discarded = data->events_discarded;
1052 index_data.stream_id = data->stream_id;
1053 return relay_index_set_data(index, &index_data);
1c20f0e2
JD
1054}
1055
c5b6f4f0
DG
1056/*
1057 * Handle the RELAYD_CREATE_SESSION command.
1058 *
1059 * On success, send back the session id or else return a negative value.
1060 */
7591bab1 1061static int relay_create_session(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1062 struct relay_connection *conn)
c5b6f4f0
DG
1063{
1064 int ret = 0, send_ret;
1065 struct relay_session *session;
1066 struct lttcomm_relayd_status_session reply;
7591bab1
MD
1067 char session_name[NAME_MAX];
1068 char hostname[HOST_NAME_MAX];
1069 uint32_t live_timer = 0;
1070 bool snapshot = false;
c5b6f4f0 1071
7591bab1
MD
1072 memset(session_name, 0, NAME_MAX);
1073 memset(hostname, 0, HOST_NAME_MAX);
c5b6f4f0
DG
1074
1075 memset(&reply, 0, sizeof(reply));
1076
58eb9381 1077 switch (conn->minor) {
2a174661
DG
1078 case 1:
1079 case 2:
1080 case 3:
1081 break;
1082 case 4: /* LTTng sessiond 2.4 */
1083 default:
7591bab1
MD
1084 ret = cmd_create_session_2_4(conn, session_name,
1085 hostname, &live_timer, &snapshot);
1086 }
1087 if (ret < 0) {
1088 goto send_reply;
d3e2ba59
JD
1089 }
1090
7591bab1
MD
1091 session = session_create(session_name, hostname, live_timer,
1092 snapshot, conn->major, conn->minor);
1093 if (!session) {
1094 ret = -1;
1095 goto send_reply;
1096 }
1097 assert(!conn->session);
1098 conn->session = session;
c5b6f4f0
DG
1099 DBG("Created session %" PRIu64, session->id);
1100
7591bab1
MD
1101 reply.session_id = htobe64(session->id);
1102
1103send_reply:
c5b6f4f0
DG
1104 if (ret < 0) {
1105 reply.ret_code = htobe32(LTTNG_ERR_FATAL);
1106 } else {
1107 reply.ret_code = htobe32(LTTNG_OK);
1108 }
1109
58eb9381 1110 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
c5b6f4f0
DG
1111 if (send_ret < 0) {
1112 ERR("Relayd sending session id");
4169f5ad 1113 ret = send_ret;
c5b6f4f0
DG
1114 }
1115
1116 return ret;
1117}
1118
a4baae1b
JD
1119/*
1120 * When we have received all the streams and the metadata for a channel,
1121 * we make them visible to the viewer threads.
1122 */
7591bab1 1123static void publish_connection_local_streams(struct relay_connection *conn)
a4baae1b 1124{
7591bab1
MD
1125 struct relay_stream *stream;
1126 struct relay_session *session = conn->session;
a4baae1b 1127
7591bab1
MD
1128 /*
1129 * We publish all streams belonging to a session atomically wrt
1130 * session lock.
1131 */
1132 pthread_mutex_lock(&session->lock);
1133 rcu_read_lock();
1134 cds_list_for_each_entry_rcu(stream, &session->recv_list,
1135 recv_node) {
1136 stream_publish(stream);
a4baae1b 1137 }
7591bab1 1138 rcu_read_unlock();
a4baae1b 1139
7591bab1
MD
1140 /*
1141 * Inform the viewer that there are new streams in the session.
1142 */
1143 if (session->viewer_attached) {
1144 uatomic_set(&session->new_streams, 1);
1145 }
1146 pthread_mutex_unlock(&session->lock);
a4baae1b
JD
1147}
1148
b8aa1682
JD
1149/*
1150 * relay_add_stream: allocate a new stream for a session
1151 */
7591bab1 1152static int relay_add_stream(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1153 struct relay_connection *conn)
b8aa1682 1154{
7591bab1
MD
1155 int ret;
1156 ssize_t send_ret;
58eb9381 1157 struct relay_session *session = conn->session;
b8aa1682
JD
1158 struct relay_stream *stream = NULL;
1159 struct lttcomm_relayd_status_stream reply;
4030a636 1160 struct ctf_trace *trace = NULL;
7591bab1
MD
1161 uint64_t stream_handle = -1ULL;
1162 char *path_name = NULL, *channel_name = NULL;
1163 uint64_t tracefile_size = 0, tracefile_count = 0;
b8aa1682 1164
58eb9381 1165 if (!session || conn->version_check_done == 0) {
b8aa1682
JD
1166 ERR("Trying to add a stream before version check");
1167 ret = -1;
1168 goto end_no_session;
1169 }
1170
7591bab1
MD
1171 switch (session->minor) {
1172 case 1: /* LTTng sessiond 2.1. Allocates path_name and channel_name. */
1173 ret = cmd_recv_stream_2_1(conn, &path_name,
1174 &channel_name);
0f907de1 1175 break;
7591bab1 1176 case 2: /* LTTng sessiond 2.2. Allocates path_name and channel_name. */
0f907de1 1177 default:
7591bab1
MD
1178 ret = cmd_recv_stream_2_2(conn, &path_name,
1179 &channel_name, &tracefile_size, &tracefile_count);
0f907de1
JD
1180 break;
1181 }
1182 if (ret < 0) {
7591bab1 1183 goto send_reply;
b8aa1682
JD
1184 }
1185
7591bab1 1186 trace = ctf_trace_get_by_path_or_create(session, path_name);
2a174661 1187 if (!trace) {
7591bab1 1188 goto send_reply;
2a174661 1189 }
7591bab1 1190 /* This stream here has one reference on the trace. */
2a174661 1191
7591bab1
MD
1192 pthread_mutex_lock(&last_relay_stream_id_lock);
1193 stream_handle = ++last_relay_stream_id;
1194 pthread_mutex_unlock(&last_relay_stream_id_lock);
d3e2ba59 1195
7591bab1
MD
1196 /* We pass ownership of path_name and channel_name. */
1197 stream = stream_create(trace, stream_handle, path_name,
1198 channel_name, tracefile_size, tracefile_count);
1199 path_name = NULL;
1200 channel_name = NULL;
a4baae1b 1201
2a174661 1202 /*
7591bab1
MD
1203 * Streams are the owners of their trace. Reference to trace is
1204 * kept within stream_create().
2a174661 1205 */
7591bab1 1206 ctf_trace_put(trace);
d3e2ba59 1207
7591bab1 1208send_reply:
53efb85a 1209 memset(&reply, 0, sizeof(reply));
7591bab1
MD
1210 reply.handle = htobe64(stream_handle);
1211 if (!stream) {
f73fabfd 1212 reply.ret_code = htobe32(LTTNG_ERR_UNK);
b8aa1682 1213 } else {
f73fabfd 1214 reply.ret_code = htobe32(LTTNG_OK);
b8aa1682 1215 }
5af40280 1216
58eb9381 1217 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
b8aa1682
JD
1218 sizeof(struct lttcomm_relayd_status_stream), 0);
1219 if (send_ret < 0) {
1220 ERR("Relay sending stream id");
7591bab1 1221 ret = (int) send_ret;
b8aa1682
JD
1222 }
1223
1224end_no_session:
7591bab1
MD
1225 free(path_name);
1226 free(channel_name);
0f907de1 1227 return ret;
b8aa1682
JD
1228}
1229
173af62f
DG
1230/*
1231 * relay_close_stream: close a specific stream
1232 */
7591bab1 1233static int relay_close_stream(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1234 struct relay_connection *conn)
173af62f 1235{
94d49140 1236 int ret, send_ret;
58eb9381 1237 struct relay_session *session = conn->session;
173af62f
DG
1238 struct lttcomm_relayd_close_stream stream_info;
1239 struct lttcomm_relayd_generic_reply reply;
1240 struct relay_stream *stream;
173af62f
DG
1241
1242 DBG("Close stream received");
1243
58eb9381 1244 if (!session || conn->version_check_done == 0) {
173af62f
DG
1245 ERR("Trying to close a stream before version check");
1246 ret = -1;
1247 goto end_no_session;
1248 }
1249
58eb9381 1250 ret = conn->sock->ops->recvmsg(conn->sock, &stream_info,
7c5aef62 1251 sizeof(struct lttcomm_relayd_close_stream), 0);
173af62f 1252 if (ret < sizeof(struct lttcomm_relayd_close_stream)) {
a6cd2b97
DG
1253 if (ret == 0) {
1254 /* Orderly shutdown. Not necessary to print an error. */
58eb9381 1255 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
a6cd2b97
DG
1256 } else {
1257 ERR("Relay didn't receive valid add_stream struct size : %d", ret);
1258 }
173af62f
DG
1259 ret = -1;
1260 goto end_no_session;
1261 }
1262
7591bab1 1263 stream = stream_get_by_id(be64toh(stream_info.stream_id));
173af62f
DG
1264 if (!stream) {
1265 ret = -1;
7591bab1 1266 goto end;
173af62f 1267 }
7591bab1
MD
1268 pthread_mutex_lock(&stream->lock);
1269 stream->closed = true;
8e2583a4 1270 stream->last_net_seq_num = be64toh(stream_info.last_net_seq_num);
7591bab1
MD
1271 if (stream->is_metadata) {
1272 struct relay_viewer_stream *vstream;
173af62f 1273
7591bab1
MD
1274 vstream = viewer_stream_get_by_id(stream->stream_handle);
1275 if (vstream) {
1276 if (vstream->metadata_sent == stream->metadata_received) {
1277 /*
1278 * Since all the metadata has been sent to the
1279 * viewer and that we have a request to close
1280 * its stream, we can safely teardown the
1281 * corresponding metadata viewer stream.
1282 */
1283 viewer_stream_put(vstream);
1284 }
1285 /* Put local reference. */
1286 viewer_stream_put(vstream);
1287 }
1288 }
1289 pthread_mutex_unlock(&stream->lock);
1290 stream_put(stream);
173af62f 1291
7591bab1 1292end:
53efb85a 1293 memset(&reply, 0, sizeof(reply));
173af62f 1294 if (ret < 0) {
f73fabfd 1295 reply.ret_code = htobe32(LTTNG_ERR_UNK);
173af62f 1296 } else {
f73fabfd 1297 reply.ret_code = htobe32(LTTNG_OK);
173af62f 1298 }
58eb9381 1299 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
173af62f
DG
1300 sizeof(struct lttcomm_relayd_generic_reply), 0);
1301 if (send_ret < 0) {
1302 ERR("Relay sending stream id");
4169f5ad 1303 ret = send_ret;
173af62f
DG
1304 }
1305
1306end_no_session:
1307 return ret;
1308}
1309
b8aa1682
JD
1310/*
1311 * relay_unknown_command: send -1 if received unknown command
1312 */
7591bab1 1313static void relay_unknown_command(struct relay_connection *conn)
b8aa1682
JD
1314{
1315 struct lttcomm_relayd_generic_reply reply;
1316 int ret;
1317
53efb85a 1318 memset(&reply, 0, sizeof(reply));
f73fabfd 1319 reply.ret_code = htobe32(LTTNG_ERR_UNK);
58eb9381 1320 ret = conn->sock->ops->sendmsg(conn->sock, &reply,
b8aa1682
JD
1321 sizeof(struct lttcomm_relayd_generic_reply), 0);
1322 if (ret < 0) {
1323 ERR("Relay sending unknown command");
1324 }
1325}
1326
1327/*
1328 * relay_start: send an acknowledgment to the client to tell if we are
1329 * ready to receive data. We are ready if a session is established.
1330 */
7591bab1 1331static int relay_start(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1332 struct relay_connection *conn)
b8aa1682 1333{
f73fabfd 1334 int ret = htobe32(LTTNG_OK);
b8aa1682 1335 struct lttcomm_relayd_generic_reply reply;
58eb9381 1336 struct relay_session *session = conn->session;
b8aa1682
JD
1337
1338 if (!session) {
1339 DBG("Trying to start the streaming without a session established");
f73fabfd 1340 ret = htobe32(LTTNG_ERR_UNK);
b8aa1682
JD
1341 }
1342
53efb85a 1343 memset(&reply, 0, sizeof(reply));
b8aa1682 1344 reply.ret_code = ret;
58eb9381 1345 ret = conn->sock->ops->sendmsg(conn->sock, &reply,
b8aa1682
JD
1346 sizeof(struct lttcomm_relayd_generic_reply), 0);
1347 if (ret < 0) {
1348 ERR("Relay sending start ack");
1349 }
1350
1351 return ret;
1352}
1353
1d4dfdef
DG
1354/*
1355 * Append padding to the file pointed by the file descriptor fd.
1356 */
1357static int write_padding_to_file(int fd, uint32_t size)
1358{
6cd525e8 1359 ssize_t ret = 0;
1d4dfdef
DG
1360 char *zeros;
1361
1362 if (size == 0) {
1363 goto end;
1364 }
1365
1366 zeros = zmalloc(size);
1367 if (zeros == NULL) {
1368 PERROR("zmalloc zeros for padding");
1369 ret = -1;
1370 goto end;
1371 }
1372
6cd525e8
MD
1373 ret = lttng_write(fd, zeros, size);
1374 if (ret < size) {
1d4dfdef
DG
1375 PERROR("write padding to file");
1376 }
1377
e986c7a1
DG
1378 free(zeros);
1379
1d4dfdef
DG
1380end:
1381 return ret;
1382}
1383
b8aa1682 1384/*
7591bab1 1385 * relay_recv_metadata: receive the metadata for the session.
b8aa1682 1386 */
7591bab1 1387static int relay_recv_metadata(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1388 struct relay_connection *conn)
b8aa1682 1389{
f73fabfd 1390 int ret = htobe32(LTTNG_OK);
6cd525e8 1391 ssize_t size_ret;
58eb9381 1392 struct relay_session *session = conn->session;
b8aa1682
JD
1393 struct lttcomm_relayd_metadata_payload *metadata_struct;
1394 struct relay_stream *metadata_stream;
1395 uint64_t data_size, payload_size;
1396
1397 if (!session) {
1398 ERR("Metadata sent before version check");
1399 ret = -1;
1400 goto end;
1401 }
1402
f6416125
MD
1403 data_size = payload_size = be64toh(recv_hdr->data_size);
1404 if (data_size < sizeof(struct lttcomm_relayd_metadata_payload)) {
1405 ERR("Incorrect data size");
1406 ret = -1;
1407 goto end;
1408 }
1409 payload_size -= sizeof(struct lttcomm_relayd_metadata_payload);
1410
b8aa1682 1411 if (data_buffer_size < data_size) {
d7b3776f 1412 /* In case the realloc fails, we can free the memory */
c617c0c6
MD
1413 char *tmp_data_ptr;
1414
1415 tmp_data_ptr = realloc(data_buffer, data_size);
1416 if (!tmp_data_ptr) {
b8aa1682 1417 ERR("Allocating data buffer");
c617c0c6 1418 free(data_buffer);
b8aa1682
JD
1419 ret = -1;
1420 goto end;
1421 }
c617c0c6 1422 data_buffer = tmp_data_ptr;
b8aa1682
JD
1423 data_buffer_size = data_size;
1424 }
1425 memset(data_buffer, 0, data_size);
77c7c900 1426 DBG2("Relay receiving metadata, waiting for %" PRIu64 " bytes", data_size);
58eb9381 1427 ret = conn->sock->ops->recvmsg(conn->sock, data_buffer, data_size, 0);
b8aa1682 1428 if (ret < 0 || ret != data_size) {
a6cd2b97
DG
1429 if (ret == 0) {
1430 /* Orderly shutdown. Not necessary to print an error. */
58eb9381 1431 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
a6cd2b97
DG
1432 } else {
1433 ERR("Relay didn't receive the whole metadata");
1434 }
b8aa1682 1435 ret = -1;
b8aa1682
JD
1436 goto end;
1437 }
1438 metadata_struct = (struct lttcomm_relayd_metadata_payload *) data_buffer;
9d1bbf21 1439
7591bab1 1440 metadata_stream = stream_get_by_id(be64toh(metadata_struct->stream_id));
b8aa1682
JD
1441 if (!metadata_stream) {
1442 ret = -1;
7591bab1 1443 goto end;
b8aa1682
JD
1444 }
1445
7591bab1
MD
1446 pthread_mutex_lock(&metadata_stream->lock);
1447
1448 size_ret = lttng_write(metadata_stream->stream_fd->fd, metadata_struct->payload,
6cd525e8
MD
1449 payload_size);
1450 if (size_ret < payload_size) {
b8aa1682
JD
1451 ERR("Relay error writing metadata on file");
1452 ret = -1;
7591bab1 1453 goto end_put;
b8aa1682 1454 }
1d4dfdef 1455
7591bab1 1456 ret = write_padding_to_file(metadata_stream->stream_fd->fd,
1d4dfdef
DG
1457 be32toh(metadata_struct->padding_size));
1458 if (ret < 0) {
7591bab1 1459 goto end_put;
1d4dfdef 1460 }
2a174661 1461
7591bab1 1462 metadata_stream->metadata_received +=
d3e2ba59 1463 payload_size + be32toh(metadata_struct->padding_size);
7591bab1
MD
1464 DBG2("Relay metadata written. Updated metadata_received %" PRIu64,
1465 metadata_stream->metadata_received);
1d4dfdef 1466
7591bab1
MD
1467end_put:
1468 pthread_mutex_unlock(&metadata_stream->lock);
1469 stream_put(metadata_stream);
b8aa1682
JD
1470
1471end:
1472 return ret;
1473}
1474
1475/*
1476 * relay_send_version: send relayd version number
1477 */
7591bab1 1478static int relay_send_version(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1479 struct relay_connection *conn)
b8aa1682 1480{
7f51dcba 1481 int ret;
092b6259 1482 struct lttcomm_relayd_version reply, msg;
b8aa1682 1483
58eb9381 1484 conn->version_check_done = 1;
b8aa1682 1485
092b6259 1486 /* Get version from the other side. */
58eb9381 1487 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
092b6259 1488 if (ret < 0 || ret != sizeof(msg)) {
a6cd2b97
DG
1489 if (ret == 0) {
1490 /* Orderly shutdown. Not necessary to print an error. */
58eb9381 1491 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
a6cd2b97
DG
1492 } else {
1493 ERR("Relay failed to receive the version values.");
1494 }
092b6259 1495 ret = -1;
092b6259
DG
1496 goto end;
1497 }
1498
53efb85a 1499 memset(&reply, 0, sizeof(reply));
d83a952c
MD
1500 reply.major = RELAYD_VERSION_COMM_MAJOR;
1501 reply.minor = RELAYD_VERSION_COMM_MINOR;
d4519fa3
JD
1502
1503 /* Major versions must be the same */
1504 if (reply.major != be32toh(msg.major)) {
6151a90f
JD
1505 DBG("Incompatible major versions (%u vs %u), deleting session",
1506 reply.major, be32toh(msg.major));
7591bab1 1507 connection_put(conn);
d4519fa3
JD
1508 ret = 0;
1509 goto end;
1510 }
1511
58eb9381 1512 conn->major = reply.major;
0f907de1
JD
1513 /* We adapt to the lowest compatible version */
1514 if (reply.minor <= be32toh(msg.minor)) {
58eb9381 1515 conn->minor = reply.minor;
0f907de1 1516 } else {
58eb9381 1517 conn->minor = be32toh(msg.minor);
0f907de1
JD
1518 }
1519
6151a90f
JD
1520 reply.major = htobe32(reply.major);
1521 reply.minor = htobe32(reply.minor);
58eb9381 1522 ret = conn->sock->ops->sendmsg(conn->sock, &reply,
6151a90f
JD
1523 sizeof(struct lttcomm_relayd_version), 0);
1524 if (ret < 0) {
1525 ERR("Relay sending version");
1526 }
1527
58eb9381
DG
1528 DBG("Version check done using protocol %u.%u", conn->major,
1529 conn->minor);
b8aa1682
JD
1530
1531end:
1532 return ret;
1533}
1534
c8f59ee5 1535/*
6d805429 1536 * Check for data pending for a given stream id from the session daemon.
c8f59ee5 1537 */
7591bab1 1538static int relay_data_pending(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1539 struct relay_connection *conn)
c8f59ee5 1540{
58eb9381 1541 struct relay_session *session = conn->session;
6d805429 1542 struct lttcomm_relayd_data_pending msg;
c8f59ee5
DG
1543 struct lttcomm_relayd_generic_reply reply;
1544 struct relay_stream *stream;
1545 int ret;
c8f59ee5
DG
1546 uint64_t last_net_seq_num, stream_id;
1547
6d805429 1548 DBG("Data pending command received");
c8f59ee5 1549
58eb9381 1550 if (!session || conn->version_check_done == 0) {
c8f59ee5
DG
1551 ERR("Trying to check for data before version check");
1552 ret = -1;
1553 goto end_no_session;
1554 }
1555
58eb9381 1556 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
c8f59ee5 1557 if (ret < sizeof(msg)) {
a6cd2b97
DG
1558 if (ret == 0) {
1559 /* Orderly shutdown. Not necessary to print an error. */
58eb9381 1560 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
a6cd2b97
DG
1561 } else {
1562 ERR("Relay didn't receive valid data_pending struct size : %d",
1563 ret);
1564 }
c8f59ee5
DG
1565 ret = -1;
1566 goto end_no_session;
1567 }
1568
1569 stream_id = be64toh(msg.stream_id);
1570 last_net_seq_num = be64toh(msg.last_net_seq_num);
1571
7591bab1 1572 stream = stream_get_by_id(stream_id);
de91f48a 1573 if (stream == NULL) {
c8f59ee5 1574 ret = -1;
7591bab1 1575 goto end;
c8f59ee5
DG
1576 }
1577
7591bab1
MD
1578 pthread_mutex_lock(&stream->lock);
1579
6d805429 1580 DBG("Data pending for stream id %" PRIu64 " prev_seq %" PRIu64
c8f59ee5
DG
1581 " and last_seq %" PRIu64, stream_id, stream->prev_seq,
1582 last_net_seq_num);
1583
33832e64 1584 /* Avoid wrapping issue */
39df6d9f 1585 if (((int64_t) (stream->prev_seq - last_net_seq_num)) >= 0) {
6d805429 1586 /* Data has in fact been written and is NOT pending */
c8f59ee5 1587 ret = 0;
6d805429
DG
1588 } else {
1589 /* Data still being streamed thus pending */
1590 ret = 1;
c8f59ee5
DG
1591 }
1592
7591bab1
MD
1593 stream->data_pending_check_done = true;
1594 pthread_mutex_unlock(&stream->lock);
f7079f67 1595
7591bab1
MD
1596 stream_put(stream);
1597end:
c8f59ee5 1598
53efb85a 1599 memset(&reply, 0, sizeof(reply));
c8f59ee5 1600 reply.ret_code = htobe32(ret);
58eb9381 1601 ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
c8f59ee5 1602 if (ret < 0) {
6d805429 1603 ERR("Relay data pending ret code failed");
c8f59ee5
DG
1604 }
1605
1606end_no_session:
1607 return ret;
1608}
1609
1610/*
1611 * Wait for the control socket to reach a quiescent state.
1612 *
7591bab1
MD
1613 * Note that for now, when receiving this command from the session
1614 * daemon, this means that every subsequent commands or data received on
1615 * the control socket has been handled. So, this is why we simply return
1616 * OK here.
c8f59ee5 1617 */
7591bab1 1618static int relay_quiescent_control(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1619 struct relay_connection *conn)
c8f59ee5
DG
1620{
1621 int ret;
ad7051c0
DG
1622 uint64_t stream_id;
1623 struct relay_stream *stream;
ad7051c0 1624 struct lttcomm_relayd_quiescent_control msg;
c8f59ee5
DG
1625 struct lttcomm_relayd_generic_reply reply;
1626
1627 DBG("Checking quiescent state on control socket");
1628
58eb9381 1629 if (!conn->session || conn->version_check_done == 0) {
ad7051c0
DG
1630 ERR("Trying to check for data before version check");
1631 ret = -1;
1632 goto end_no_session;
1633 }
1634
58eb9381 1635 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
ad7051c0 1636 if (ret < sizeof(msg)) {
a6cd2b97
DG
1637 if (ret == 0) {
1638 /* Orderly shutdown. Not necessary to print an error. */
58eb9381 1639 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
a6cd2b97
DG
1640 } else {
1641 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1642 ret);
1643 }
ad7051c0
DG
1644 ret = -1;
1645 goto end_no_session;
1646 }
1647
1648 stream_id = be64toh(msg.stream_id);
7591bab1
MD
1649 stream = stream_get_by_id(stream_id);
1650 if (!stream) {
1651 goto reply;
1652 }
1653 pthread_mutex_lock(&stream->lock);
1654 stream->data_pending_check_done = true;
1655 pthread_mutex_unlock(&stream->lock);
1656 DBG("Relay quiescent control pending flag set to %" PRIu64, stream_id);
1657 stream_put(stream);
1658reply:
53efb85a 1659 memset(&reply, 0, sizeof(reply));
c8f59ee5 1660 reply.ret_code = htobe32(LTTNG_OK);
58eb9381 1661 ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
c8f59ee5 1662 if (ret < 0) {
6d805429 1663 ERR("Relay data quiescent control ret code failed");
c8f59ee5
DG
1664 }
1665
ad7051c0 1666end_no_session:
c8f59ee5
DG
1667 return ret;
1668}
1669
f7079f67 1670/*
7591bab1
MD
1671 * Initialize a data pending command. This means that a consumer is about
1672 * to ask for data pending for each stream it holds. Simply iterate over
1673 * all streams of a session and set the data_pending_check_done flag.
f7079f67
DG
1674 *
1675 * This command returns to the client a LTTNG_OK code.
1676 */
7591bab1 1677static int relay_begin_data_pending(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1678 struct relay_connection *conn)
f7079f67
DG
1679{
1680 int ret;
1681 struct lttng_ht_iter iter;
1682 struct lttcomm_relayd_begin_data_pending msg;
1683 struct lttcomm_relayd_generic_reply reply;
1684 struct relay_stream *stream;
1685 uint64_t session_id;
1686
1687 assert(recv_hdr);
58eb9381 1688 assert(conn);
f7079f67
DG
1689
1690 DBG("Init streams for data pending");
1691
58eb9381 1692 if (!conn->session || conn->version_check_done == 0) {
f7079f67
DG
1693 ERR("Trying to check for data before version check");
1694 ret = -1;
1695 goto end_no_session;
1696 }
1697
58eb9381 1698 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
f7079f67 1699 if (ret < sizeof(msg)) {
a6cd2b97
DG
1700 if (ret == 0) {
1701 /* Orderly shutdown. Not necessary to print an error. */
58eb9381 1702 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
a6cd2b97
DG
1703 } else {
1704 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1705 ret);
1706 }
f7079f67
DG
1707 ret = -1;
1708 goto end_no_session;
1709 }
1710
1711 session_id = be64toh(msg.session_id);
1712
1713 /*
7591bab1
MD
1714 * Iterate over all streams to set the begin data pending flag.
1715 * For now, the streams are indexed by stream handle so we have
1716 * to iterate over all streams to find the one associated with
1717 * the right session_id.
f7079f67
DG
1718 */
1719 rcu_read_lock();
d3e2ba59 1720 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2a174661 1721 node.node) {
7591bab1
MD
1722 if (!stream_get(stream)) {
1723 continue;
1724 }
1725 if (stream->trace->session->id == session_id) {
1726 pthread_mutex_lock(&stream->lock);
1727 stream->data_pending_check_done = false;
1728 pthread_mutex_unlock(&stream->lock);
f7079f67
DG
1729 DBG("Set begin data pending flag to stream %" PRIu64,
1730 stream->stream_handle);
1731 }
7591bab1 1732 stream_put(stream);
f7079f67
DG
1733 }
1734 rcu_read_unlock();
1735
53efb85a 1736 memset(&reply, 0, sizeof(reply));
f7079f67
DG
1737 /* All good, send back reply. */
1738 reply.ret_code = htobe32(LTTNG_OK);
1739
58eb9381 1740 ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
f7079f67
DG
1741 if (ret < 0) {
1742 ERR("Relay begin data pending send reply failed");
1743 }
1744
1745end_no_session:
1746 return ret;
1747}
1748
1749/*
7591bab1
MD
1750 * End data pending command. This will check, for a given session id, if
1751 * each stream associated with it has its data_pending_check_done flag
1752 * set. If not, this means that the client lost track of the stream but
1753 * the data is still being streamed on our side. In this case, we inform
1754 * the client that data is in flight.
f7079f67
DG
1755 *
1756 * Return to the client if there is data in flight or not with a ret_code.
1757 */
7591bab1 1758static int relay_end_data_pending(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1759 struct relay_connection *conn)
f7079f67
DG
1760{
1761 int ret;
1762 struct lttng_ht_iter iter;
1763 struct lttcomm_relayd_end_data_pending msg;
1764 struct lttcomm_relayd_generic_reply reply;
1765 struct relay_stream *stream;
1766 uint64_t session_id;
1767 uint32_t is_data_inflight = 0;
1768
f7079f67
DG
1769 DBG("End data pending command");
1770
58eb9381 1771 if (!conn->session || conn->version_check_done == 0) {
f7079f67
DG
1772 ERR("Trying to check for data before version check");
1773 ret = -1;
1774 goto end_no_session;
1775 }
1776
58eb9381 1777 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
f7079f67 1778 if (ret < sizeof(msg)) {
a6cd2b97
DG
1779 if (ret == 0) {
1780 /* Orderly shutdown. Not necessary to print an error. */
58eb9381 1781 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
a6cd2b97
DG
1782 } else {
1783 ERR("Relay didn't receive valid end data_pending struct size: %d",
1784 ret);
1785 }
f7079f67
DG
1786 ret = -1;
1787 goto end_no_session;
1788 }
1789
1790 session_id = be64toh(msg.session_id);
1791
7591bab1
MD
1792 /*
1793 * Iterate over all streams to see if the begin data pending
1794 * flag is set.
1795 */
f7079f67 1796 rcu_read_lock();
d3e2ba59 1797 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2a174661 1798 node.node) {
7591bab1
MD
1799 if (!stream_get(stream)) {
1800 continue;
1801 }
1802 if (stream->trace->session->id != session_id) {
1803 stream_put(stream);
1804 continue;
1805 }
1806 pthread_mutex_lock(&stream->lock);
1807 if (!stream->data_pending_check_done) {
1808 if (!stream->closed || !(((int64_t) (stream->prev_seq - stream->last_net_seq_num)) >= 0)) {
1809 is_data_inflight = 1;
1810 DBG("Data is still in flight for stream %" PRIu64,
1811 stream->stream_handle);
1812 pthread_mutex_unlock(&stream->lock);
1813 stream_put(stream);
1814 break;
1815 }
f7079f67 1816 }
7591bab1
MD
1817 pthread_mutex_unlock(&stream->lock);
1818 stream_put(stream);
f7079f67
DG
1819 }
1820 rcu_read_unlock();
1821
53efb85a 1822 memset(&reply, 0, sizeof(reply));
f7079f67
DG
1823 /* All good, send back reply. */
1824 reply.ret_code = htobe32(is_data_inflight);
1825
58eb9381 1826 ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
f7079f67
DG
1827 if (ret < 0) {
1828 ERR("Relay end data pending send reply failed");
1829 }
1830
1831end_no_session:
1832 return ret;
1833}
1834
1c20f0e2
JD
1835/*
1836 * Receive an index for a specific stream.
1837 *
1838 * Return 0 on success else a negative value.
1839 */
7591bab1 1840static int relay_recv_index(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1841 struct relay_connection *conn)
1c20f0e2 1842{
7591bab1 1843 int ret, send_ret;
58eb9381 1844 struct relay_session *session = conn->session;
1c20f0e2 1845 struct lttcomm_relayd_index index_info;
7591bab1 1846 struct relay_index *index;
1c20f0e2
JD
1847 struct lttcomm_relayd_generic_reply reply;
1848 struct relay_stream *stream;
1849 uint64_t net_seq_num;
1850
58eb9381 1851 assert(conn);
1c20f0e2
JD
1852
1853 DBG("Relay receiving index");
1854
58eb9381 1855 if (!session || conn->version_check_done == 0) {
1c20f0e2
JD
1856 ERR("Trying to close a stream before version check");
1857 ret = -1;
1858 goto end_no_session;
1859 }
1860
58eb9381 1861 ret = conn->sock->ops->recvmsg(conn->sock, &index_info,
1c20f0e2
JD
1862 sizeof(index_info), 0);
1863 if (ret < sizeof(index_info)) {
1864 if (ret == 0) {
1865 /* Orderly shutdown. Not necessary to print an error. */
58eb9381 1866 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1c20f0e2
JD
1867 } else {
1868 ERR("Relay didn't receive valid index struct size : %d", ret);
1869 }
1870 ret = -1;
1871 goto end_no_session;
1872 }
1873
1874 net_seq_num = be64toh(index_info.net_seq_num);
1875
7591bab1 1876 stream = stream_get_by_id(be64toh(index_info.relay_stream_id));
1c20f0e2 1877 if (!stream) {
7591bab1 1878 ERR("stream_get_by_id not found");
1c20f0e2 1879 ret = -1;
7591bab1 1880 goto end;
1c20f0e2 1881 }
7591bab1 1882 pthread_mutex_lock(&stream->lock);
1c20f0e2 1883
d3e2ba59
JD
1884 /* Live beacon handling */
1885 if (index_info.packet_size == 0) {
7591bab1
MD
1886 DBG("Received live beacon for stream %" PRIu64,
1887 stream->stream_handle);
d3e2ba59
JD
1888
1889 /*
7591bab1
MD
1890 * Only flag a stream inactive when it has already
1891 * received data and no indexes are in flight.
d3e2ba59 1892 */
7591bab1
MD
1893 if (stream->total_index_received > 0
1894 && stream->indexes_in_flight == 0) {
1895 stream->beacon_ts_end =
1896 be64toh(index_info.timestamp_end);
d3e2ba59
JD
1897 }
1898 ret = 0;
7591bab1 1899 goto end_stream_put;
d3e2ba59
JD
1900 } else {
1901 stream->beacon_ts_end = -1ULL;
1902 }
1903
528f2ffa
JD
1904 if (stream->ctf_stream_id == -1ULL) {
1905 stream->ctf_stream_id = be64toh(index_info.stream_id);
1906 }
7591bab1
MD
1907 index = relay_index_get_by_id_or_create(stream, net_seq_num);
1908 if (!index) {
1909 ret = -1;
1910 ERR("relay_index_get_by_id_or_create index NULL");
1911 goto end_stream_put;
1c20f0e2 1912 }
7591bab1
MD
1913 if (set_index_control_data(index, &index_info)) {
1914 ERR("set_index_control_data error");
1915 relay_index_put(index);
1916 ret = -1;
1917 goto end_stream_put;
1918 }
1919 ret = relay_index_try_flush(index);
1920 if (ret == 0) {
d3e2ba59 1921 stream->total_index_received++;
7591bab1
MD
1922 } else if (ret > 0) {
1923 /* no flush. */
1924 ret = 0;
1925 } else {
1926 ERR("relay_index_try_flush error %d", ret);
1927 relay_index_put(index);
1928 ret = -1;
1c20f0e2
JD
1929 }
1930
7591bab1
MD
1931end_stream_put:
1932 pthread_mutex_unlock(&stream->lock);
1933 stream_put(stream);
1934
1935end:
1c20f0e2 1936
53efb85a 1937 memset(&reply, 0, sizeof(reply));
1c20f0e2
JD
1938 if (ret < 0) {
1939 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1940 } else {
1941 reply.ret_code = htobe32(LTTNG_OK);
1942 }
58eb9381 1943 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1c20f0e2
JD
1944 if (send_ret < 0) {
1945 ERR("Relay sending close index id reply");
1946 ret = send_ret;
1947 }
1948
1949end_no_session:
1950 return ret;
1951}
1952
a4baae1b
JD
1953/*
1954 * Receive the streams_sent message.
1955 *
1956 * Return 0 on success else a negative value.
1957 */
7591bab1 1958static int relay_streams_sent(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1959 struct relay_connection *conn)
a4baae1b
JD
1960{
1961 int ret, send_ret;
1962 struct lttcomm_relayd_generic_reply reply;
1963
58eb9381 1964 assert(conn);
a4baae1b
JD
1965
1966 DBG("Relay receiving streams_sent");
1967
58eb9381 1968 if (!conn->session || conn->version_check_done == 0) {
a4baae1b
JD
1969 ERR("Trying to close a stream before version check");
1970 ret = -1;
1971 goto end_no_session;
1972 }
1973
1974 /*
7591bab1
MD
1975 * Publish every pending stream in the connection recv list which are
1976 * now ready to be used by the viewer.
4a9daf17 1977 */
7591bab1 1978 publish_connection_local_streams(conn);
4a9daf17 1979
53efb85a 1980 memset(&reply, 0, sizeof(reply));
a4baae1b 1981 reply.ret_code = htobe32(LTTNG_OK);
58eb9381 1982 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
a4baae1b
JD
1983 if (send_ret < 0) {
1984 ERR("Relay sending sent_stream reply");
1985 ret = send_ret;
1986 } else {
1987 /* Success. */
1988 ret = 0;
1989 }
1990
1991end_no_session:
1992 return ret;
1993}
1994
b8aa1682 1995/*
d3e2ba59 1996 * Process the commands received on the control socket
b8aa1682 1997 */
7591bab1 1998static int relay_process_control(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1999 struct relay_connection *conn)
b8aa1682
JD
2000{
2001 int ret = 0;
2002
2003 switch (be32toh(recv_hdr->cmd)) {
b8aa1682 2004 case RELAYD_CREATE_SESSION:
58eb9381 2005 ret = relay_create_session(recv_hdr, conn);
b8aa1682 2006 break;
b8aa1682 2007 case RELAYD_ADD_STREAM:
58eb9381 2008 ret = relay_add_stream(recv_hdr, conn);
b8aa1682
JD
2009 break;
2010 case RELAYD_START_DATA:
58eb9381 2011 ret = relay_start(recv_hdr, conn);
b8aa1682
JD
2012 break;
2013 case RELAYD_SEND_METADATA:
58eb9381 2014 ret = relay_recv_metadata(recv_hdr, conn);
b8aa1682
JD
2015 break;
2016 case RELAYD_VERSION:
58eb9381 2017 ret = relay_send_version(recv_hdr, conn);
b8aa1682 2018 break;
173af62f 2019 case RELAYD_CLOSE_STREAM:
58eb9381 2020 ret = relay_close_stream(recv_hdr, conn);
173af62f 2021 break;
6d805429 2022 case RELAYD_DATA_PENDING:
58eb9381 2023 ret = relay_data_pending(recv_hdr, conn);
c8f59ee5
DG
2024 break;
2025 case RELAYD_QUIESCENT_CONTROL:
58eb9381 2026 ret = relay_quiescent_control(recv_hdr, conn);
c8f59ee5 2027 break;
f7079f67 2028 case RELAYD_BEGIN_DATA_PENDING:
58eb9381 2029 ret = relay_begin_data_pending(recv_hdr, conn);
f7079f67
DG
2030 break;
2031 case RELAYD_END_DATA_PENDING:
58eb9381 2032 ret = relay_end_data_pending(recv_hdr, conn);
f7079f67 2033 break;
1c20f0e2 2034 case RELAYD_SEND_INDEX:
58eb9381 2035 ret = relay_recv_index(recv_hdr, conn);
1c20f0e2 2036 break;
a4baae1b 2037 case RELAYD_STREAMS_SENT:
58eb9381 2038 ret = relay_streams_sent(recv_hdr, conn);
a4baae1b 2039 break;
b8aa1682
JD
2040 case RELAYD_UPDATE_SYNC_INFO:
2041 default:
2042 ERR("Received unknown command (%u)", be32toh(recv_hdr->cmd));
58eb9381 2043 relay_unknown_command(conn);
b8aa1682
JD
2044 ret = -1;
2045 goto end;
2046 }
2047
2048end:
2049 return ret;
2050}
2051
7d2f7452
DG
2052/*
2053 * Handle index for a data stream.
2054 *
7591bab1 2055 * Called with the stream lock held.
7d2f7452
DG
2056 *
2057 * Return 0 on success else a negative value.
2058 */
2059static int handle_index_data(struct relay_stream *stream, uint64_t net_seq_num,
2060 int rotate_index)
2061{
7591bab1
MD
2062 int ret = 0;
2063 uint64_t data_offset;
2064 struct relay_index *index;
7d2f7452 2065
7d2f7452
DG
2066 /* Get data offset because we are about to update the index. */
2067 data_offset = htobe64(stream->tracefile_size_current);
2068
7591bab1
MD
2069 DBG("handle_index_data: stream %" PRIu64 " data offset %" PRIu64,
2070 stream->stream_handle, stream->tracefile_size_current);
2071
7d2f7452 2072 /*
7591bab1
MD
2073 * Lookup for an existing index for that stream id/sequence
2074 * number. If it exists, the control thread has already received the
2075 * data for it, thus we need to write it to disk.
7d2f7452 2076 */
7591bab1 2077 index = relay_index_get_by_id_or_create(stream, net_seq_num);
7d2f7452 2078 if (!index) {
7591bab1
MD
2079 ret = -1;
2080 goto end;
7d2f7452
DG
2081 }
2082
7591bab1
MD
2083 if (rotate_index || !stream->index_fd) {
2084 int fd;
2085
2086 /* Put ref on previous index_fd. */
2087 if (stream->index_fd) {
2088 stream_fd_put(stream->index_fd);
2089 stream->index_fd = NULL;
7d2f7452 2090 }
7d2f7452 2091
7591bab1
MD
2092 fd = index_create_file(stream->path_name, stream->channel_name,
2093 -1, -1, stream->tracefile_size,
2094 stream->current_tracefile_id);
2095 if (fd < 0) {
2096 ret = -1;
2097 /* Put self-ref for this index due to error. */
2098 relay_index_put(index);
2099 goto end;
2100 }
2101 stream->index_fd = stream_fd_create(fd);
2102 if (!stream->index_fd) {
2103 ret = -1;
2104 if (close(fd)) {
2105 PERROR("Error closing FD %d", fd);
2106 }
2107 /* Put self-ref for this index due to error. */
2108 relay_index_put(index);
2109 /* Will put the local ref. */
2110 goto end;
7d2f7452 2111 }
7d2f7452
DG
2112 }
2113
7591bab1
MD
2114 if (relay_index_set_fd(index, stream->index_fd, data_offset)) {
2115 ret = -1;
2116 /* Put self-ref for this index due to error. */
2117 relay_index_put(index);
2118 goto end;
7d2f7452
DG
2119 }
2120
7591bab1
MD
2121 ret = relay_index_try_flush(index);
2122 if (ret == 0) {
2123 stream->total_index_received++;
2124 } else if (ret > 0) {
2125 /* No flush. */
2126 ret = 0;
2127 } else {
2128 /* Put self-ref for this index due to error. */
2129 relay_index_put(index);
2130 ret = -1;
2131 }
2132end:
7d2f7452
DG
2133 return ret;
2134}
2135
b8aa1682
JD
2136/*
2137 * relay_process_data: Process the data received on the data socket
2138 */
7591bab1 2139static int relay_process_data(struct relay_connection *conn)
b8aa1682 2140{
7d2f7452 2141 int ret = 0, rotate_index = 0;
6cd525e8 2142 ssize_t size_ret;
b8aa1682
JD
2143 struct relay_stream *stream;
2144 struct lttcomm_relayd_data_hdr data_hdr;
7d2f7452 2145 uint64_t stream_id;
173af62f 2146 uint64_t net_seq_num;
b8aa1682 2147 uint32_t data_size;
2a174661 2148 struct relay_session *session;
c0bae11d 2149 bool new_stream = false;
b8aa1682 2150
58eb9381 2151 ret = conn->sock->ops->recvmsg(conn->sock, &data_hdr,
7c5aef62 2152 sizeof(struct lttcomm_relayd_data_hdr), 0);
b8aa1682 2153 if (ret <= 0) {
a6cd2b97
DG
2154 if (ret == 0) {
2155 /* Orderly shutdown. Not necessary to print an error. */
58eb9381 2156 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
a6cd2b97 2157 } else {
58eb9381 2158 ERR("Unable to receive data header on sock %d", conn->sock->fd);
a6cd2b97 2159 }
b8aa1682
JD
2160 ret = -1;
2161 goto end;
2162 }
2163
2164 stream_id = be64toh(data_hdr.stream_id);
7591bab1 2165 stream = stream_get_by_id(stream_id);
b8aa1682
JD
2166 if (!stream) {
2167 ret = -1;
7591bab1 2168 goto end;
b8aa1682 2169 }
7591bab1 2170 session = stream->trace->session;
b8aa1682
JD
2171 data_size = be32toh(data_hdr.data_size);
2172 if (data_buffer_size < data_size) {
c617c0c6
MD
2173 char *tmp_data_ptr;
2174
2175 tmp_data_ptr = realloc(data_buffer, data_size);
2176 if (!tmp_data_ptr) {
b8aa1682 2177 ERR("Allocating data buffer");
c617c0c6 2178 free(data_buffer);
b8aa1682 2179 ret = -1;
7591bab1 2180 goto end_stream_put;
b8aa1682 2181 }
c617c0c6 2182 data_buffer = tmp_data_ptr;
b8aa1682
JD
2183 data_buffer_size = data_size;
2184 }
2185 memset(data_buffer, 0, data_size);
2186
173af62f
DG
2187 net_seq_num = be64toh(data_hdr.net_seq_num);
2188
77c7c900 2189 DBG3("Receiving data of size %u for stream id %" PRIu64 " seqnum %" PRIu64,
173af62f 2190 data_size, stream_id, net_seq_num);
58eb9381 2191 ret = conn->sock->ops->recvmsg(conn->sock, data_buffer, data_size, 0);
b8aa1682 2192 if (ret <= 0) {
a6cd2b97
DG
2193 if (ret == 0) {
2194 /* Orderly shutdown. Not necessary to print an error. */
58eb9381 2195 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
a6cd2b97 2196 }
b8aa1682 2197 ret = -1;
7591bab1 2198 goto end_stream_put;
b8aa1682
JD
2199 }
2200
7591bab1
MD
2201 pthread_mutex_lock(&stream->lock);
2202
1c20f0e2 2203 /* Check if a rotation is needed. */
0f907de1
JD
2204 if (stream->tracefile_size > 0 &&
2205 (stream->tracefile_size_current + data_size) >
2206 stream->tracefile_size) {
6b6b9a5a
JD
2207 uint64_t new_id;
2208
7591bab1 2209 new_id = (stream->current_tracefile_id + 1) %
6b6b9a5a
JD
2210 stream->tracefile_count;
2211 /*
7591bab1
MD
2212 * Move viewer oldest available data position forward if
2213 * we are overwriting a tracefile.
6b6b9a5a 2214 */
7591bab1 2215 if (new_id == stream->oldest_tracefile_id) {
6b6b9a5a
JD
2216 stream->oldest_tracefile_id =
2217 (stream->oldest_tracefile_id + 1) %
2218 stream->tracefile_count;
2219 }
7591bab1
MD
2220 ret = utils_rotate_stream_file(stream->path_name,
2221 stream->channel_name, stream->tracefile_size,
2222 stream->tracefile_count, -1,
2223 -1, stream->stream_fd->fd,
2224 &stream->current_tracefile_id,
2225 &stream->stream_fd->fd);
0f907de1 2226 if (ret < 0) {
1c20f0e2 2227 ERR("Rotating stream output file");
7591bab1
MD
2228 goto end_stream_unlock;
2229 }
2230 stream->current_tracefile_seq++;
2231 if (stream->current_tracefile_seq
2232 - stream->oldest_tracefile_seq >=
2233 stream->tracefile_count) {
2234 stream->oldest_tracefile_seq++;
0f907de1 2235 }
7591bab1
MD
2236 /*
2237 * Reset current size because we just performed a stream
2238 * rotation.
2239 */
a6976990 2240 stream->tracefile_size_current = 0;
1c20f0e2
JD
2241 rotate_index = 1;
2242 }
2243
1c20f0e2 2244 /*
7591bab1
MD
2245 * Index are handled in protocol version 2.4 and above. Also,
2246 * snapshot and index are NOT supported.
1c20f0e2 2247 */
2a174661 2248 if (session->minor >= 4 && !session->snapshot) {
7d2f7452 2249 ret = handle_index_data(stream, net_seq_num, rotate_index);
1c20f0e2 2250 if (ret < 0) {
7591bab1 2251 goto end_stream_unlock;
1c20f0e2 2252 }
1c20f0e2
JD
2253 }
2254
7d2f7452 2255 /* Write data to stream output fd. */
7591bab1 2256 size_ret = lttng_write(stream->stream_fd->fd, data_buffer, data_size);
6cd525e8 2257 if (size_ret < data_size) {
b8aa1682
JD
2258 ERR("Relay error writing data to file");
2259 ret = -1;
7591bab1 2260 goto end_stream_unlock;
b8aa1682 2261 }
1d4dfdef 2262
7591bab1
MD
2263 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64,
2264 size_ret, stream->stream_handle);
5ab7344e 2265
7591bab1
MD
2266 ret = write_padding_to_file(stream->stream_fd->fd,
2267 be32toh(data_hdr.padding_size));
1d4dfdef 2268 if (ret < 0) {
7591bab1 2269 goto end_stream_unlock;
1d4dfdef 2270 }
7591bab1
MD
2271 stream->tracefile_size_current +=
2272 data_size + be32toh(data_hdr.padding_size);
c0bae11d
MD
2273 if (stream->prev_seq == -1ULL) {
2274 new_stream = true;
2275 }
2276
173af62f
DG
2277 stream->prev_seq = net_seq_num;
2278
7591bab1
MD
2279end_stream_unlock:
2280 pthread_mutex_unlock(&stream->lock);
c0bae11d
MD
2281 if (new_stream) {
2282 pthread_mutex_lock(&session->lock);
2283 uatomic_set(&session->new_streams, 1);
2284 pthread_mutex_unlock(&session->lock);
2285 }
7591bab1
MD
2286end_stream_put:
2287 stream_put(stream);
b8aa1682
JD
2288end:
2289 return ret;
2290}
2291
7591bab1 2292static void cleanup_connection_pollfd(struct lttng_poll_event *events, int pollfd)
b8aa1682
JD
2293{
2294 int ret;
2295
58eb9381 2296 (void) lttng_poll_del(events, pollfd);
b8aa1682
JD
2297
2298 ret = close(pollfd);
2299 if (ret < 0) {
2300 ERR("Closing pollfd %d", pollfd);
2301 }
2302}
2303
7591bab1
MD
2304static void relay_thread_close_connection(struct lttng_poll_event *events,
2305 int pollfd, struct relay_connection *conn)
9d1bbf21 2306{
7591bab1 2307 const char *type_str;
2a174661 2308
7591bab1
MD
2309 switch (conn->type) {
2310 case RELAY_DATA:
2311 type_str = "Data";
2312 break;
2313 case RELAY_CONTROL:
2314 type_str = "Control";
2315 break;
2316 case RELAY_VIEWER_COMMAND:
2317 type_str = "Viewer Command";
2318 break;
2319 case RELAY_VIEWER_NOTIFICATION:
2320 type_str = "Viewer Notification";
2321 break;
2322 default:
2323 type_str = "Unknown";
9d1bbf21 2324 }
7591bab1
MD
2325 cleanup_connection_pollfd(events, pollfd);
2326 connection_put(conn);
2327 DBG("%s connection closed with %d", type_str, pollfd);
b8aa1682
JD
2328}
2329
2330/*
2331 * This thread does the actual work
2332 */
7591bab1 2333static void *relay_thread_worker(void *data)
b8aa1682 2334{
beaad64c
DG
2335 int ret, err = -1, last_seen_data_fd = -1;
2336 uint32_t nb_fd;
b8aa1682
JD
2337 struct lttng_poll_event events;
2338 struct lttng_ht *relay_connections_ht;
b8aa1682 2339 struct lttng_ht_iter iter;
b8aa1682 2340 struct lttcomm_relayd_hdr recv_hdr;
90e7d72f 2341 struct relay_connection *destroy_conn = NULL;
b8aa1682
JD
2342
2343 DBG("[thread] Relay worker started");
2344
9d1bbf21
MD
2345 rcu_register_thread();
2346
55706a7d
MD
2347 health_register(health_relayd, HEALTH_RELAYD_TYPE_WORKER);
2348
9b5e0863
MD
2349 if (testpoint(relayd_thread_worker)) {
2350 goto error_testpoint;
2351 }
2352
f385ae0a
MD
2353 health_code_update();
2354
b8aa1682
JD
2355 /* table of connections indexed on socket */
2356 relay_connections_ht = lttng_ht_new(0, LTTNG_HT_TYPE_ULONG);
095a4ae5
MD
2357 if (!relay_connections_ht) {
2358 goto relay_connections_ht_error;
2359 }
b8aa1682 2360
b8aa1682
JD
2361 ret = create_thread_poll_set(&events, 2);
2362 if (ret < 0) {
2363 goto error_poll_create;
2364 }
2365
58eb9381 2366 ret = lttng_poll_add(&events, relay_conn_pipe[0], LPOLLIN | LPOLLRDHUP);
b8aa1682
JD
2367 if (ret < 0) {
2368 goto error;
2369 }
2370
beaad64c 2371restart:
b8aa1682 2372 while (1) {
beaad64c
DG
2373 int idx = -1, i, seen_control = 0, last_notdel_data_fd = -1;
2374
f385ae0a
MD
2375 health_code_update();
2376
b8aa1682 2377 /* Infinite blocking call, waiting for transmission */
87c1611d 2378 DBG3("Relayd worker thread polling...");
f385ae0a 2379 health_poll_entry();
b8aa1682 2380 ret = lttng_poll_wait(&events, -1);
f385ae0a 2381 health_poll_exit();
b8aa1682
JD
2382 if (ret < 0) {
2383 /*
2384 * Restart interrupted system call.
2385 */
2386 if (errno == EINTR) {
2387 goto restart;
2388 }
2389 goto error;
2390 }
2391
0d9c5d77
DG
2392 nb_fd = ret;
2393
beaad64c 2394 /*
7591bab1
MD
2395 * Process control. The control connection is
2396 * prioritized so we don't starve it with high
2397 * throughput tracing data on the data connection.
beaad64c 2398 */
b8aa1682
JD
2399 for (i = 0; i < nb_fd; i++) {
2400 /* Fetch once the poll data */
beaad64c
DG
2401 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
2402 int pollfd = LTTNG_POLL_GETFD(&events, i);
b8aa1682 2403
f385ae0a
MD
2404 health_code_update();
2405
fd20dac9 2406 if (!revents) {
7591bab1
MD
2407 /*
2408 * No activity for this FD (poll
2409 * implementation).
2410 */
fd20dac9
MD
2411 continue;
2412 }
2413
b8aa1682
JD
2414 /* Thread quit pipe has been closed. Killing thread. */
2415 ret = check_thread_quit_pipe(pollfd, revents);
2416 if (ret) {
095a4ae5
MD
2417 err = 0;
2418 goto exit;
b8aa1682
JD
2419 }
2420
58eb9381
DG
2421 /* Inspect the relay conn pipe for new connection */
2422 if (pollfd == relay_conn_pipe[0]) {
b8aa1682 2423 if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
58eb9381 2424 ERR("Relay connection pipe error");
b8aa1682
JD
2425 goto error;
2426 } else if (revents & LPOLLIN) {
90e7d72f
JG
2427 struct relay_connection *conn;
2428
58eb9381 2429 ret = lttng_read(relay_conn_pipe[0], &conn, sizeof(conn));
b8aa1682
JD
2430 if (ret < 0) {
2431 goto error;
2432 }
58eb9381
DG
2433 lttng_poll_add(&events, conn->sock->fd,
2434 LPOLLIN | LPOLLRDHUP);
7591bab1 2435 connection_ht_add(relay_connections_ht, conn);
58eb9381 2436 DBG("Connection socket %d added", conn->sock->fd);
b8aa1682 2437 }
58eb9381 2438 } else {
90e7d72f
JG
2439 struct relay_connection *ctrl_conn;
2440
7591bab1 2441 ctrl_conn = connection_get_by_sock(relay_connections_ht, pollfd);
58eb9381 2442 /* If not found, there is a synchronization issue. */
90e7d72f 2443 assert(ctrl_conn);
58eb9381
DG
2444
2445 if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
7591bab1 2446 relay_thread_close_connection(&events, pollfd, ctrl_conn);
beaad64c
DG
2447 if (last_seen_data_fd == pollfd) {
2448 last_seen_data_fd = last_notdel_data_fd;
2449 }
b8aa1682 2450 } else if (revents & LPOLLIN) {
90e7d72f
JG
2451 if (ctrl_conn->type == RELAY_CONTROL) {
2452 ret = ctrl_conn->sock->ops->recvmsg(ctrl_conn->sock, &recv_hdr,
58eb9381 2453 sizeof(recv_hdr), 0);
b8aa1682 2454 if (ret <= 0) {
58eb9381 2455 /* Connection closed */
7591bab1
MD
2456 relay_thread_close_connection(&events, pollfd,
2457 ctrl_conn);
b8aa1682 2458 } else {
90e7d72f 2459 ret = relay_process_control(&recv_hdr, ctrl_conn);
b8aa1682 2460 if (ret < 0) {
beaad64c 2461 /* Clear the session on error. */
7591bab1
MD
2462 relay_thread_close_connection(&events, pollfd,
2463 ctrl_conn);
b8aa1682 2464 }
beaad64c 2465 seen_control = 1;
b8aa1682 2466 }
beaad64c
DG
2467 } else {
2468 /*
2469 * Flag the last seen data fd not deleted. It will be
2470 * used as the last seen fd if any fd gets deleted in
2471 * this first loop.
2472 */
2473 last_notdel_data_fd = pollfd;
2474 }
58eb9381
DG
2475 } else {
2476 ERR("Unknown poll events %u for sock %d", revents, pollfd);
beaad64c 2477 }
7591bab1 2478 connection_put(ctrl_conn);
beaad64c
DG
2479 }
2480 }
2481
2482 /*
2483 * The last loop handled a control request, go back to poll to make
2484 * sure we prioritise the control socket.
2485 */
2486 if (seen_control) {
2487 continue;
2488 }
2489
2490 if (last_seen_data_fd >= 0) {
2491 for (i = 0; i < nb_fd; i++) {
2492 int pollfd = LTTNG_POLL_GETFD(&events, i);
f385ae0a
MD
2493
2494 health_code_update();
2495
beaad64c
DG
2496 if (last_seen_data_fd == pollfd) {
2497 idx = i;
2498 break;
2499 }
2500 }
2501 }
2502
2503 /* Process data connection. */
2504 for (i = idx + 1; i < nb_fd; i++) {
2505 /* Fetch the poll data. */
2506 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
2507 int pollfd = LTTNG_POLL_GETFD(&events, i);
90e7d72f 2508 struct relay_connection *data_conn;
beaad64c 2509
f385ae0a
MD
2510 health_code_update();
2511
fd20dac9
MD
2512 if (!revents) {
2513 /* No activity for this FD (poll implementation). */
2514 continue;
2515 }
2516
beaad64c 2517 /* Skip the command pipe. It's handled in the first loop. */
58eb9381 2518 if (pollfd == relay_conn_pipe[0]) {
beaad64c
DG
2519 continue;
2520 }
2521
7591bab1 2522 data_conn = connection_get_by_sock(relay_connections_ht, pollfd);
90e7d72f 2523 if (!data_conn) {
fd20dac9 2524 /* Skip it. Might be removed before. */
fd20dac9
MD
2525 continue;
2526 }
2527
2528 if (revents & LPOLLIN) {
90e7d72f 2529 if (data_conn->type != RELAY_DATA) {
7591bab1 2530 goto put_connection;
beaad64c 2531 }
beaad64c 2532
90e7d72f 2533 ret = relay_process_data(data_conn);
fd20dac9
MD
2534 /* Connection closed */
2535 if (ret < 0) {
7591bab1
MD
2536 relay_thread_close_connection(&events, pollfd,
2537 data_conn);
fd20dac9
MD
2538 /*
2539 * Every goto restart call sets the last seen fd where
2540 * here we don't really care since we gracefully
2541 * continue the loop after the connection is deleted.
2542 */
2543 } else {
2544 /* Keep last seen port. */
2545 last_seen_data_fd = pollfd;
7591bab1 2546 connection_put(data_conn);
fd20dac9 2547 goto restart;
b8aa1682
JD
2548 }
2549 }
7591bab1
MD
2550 put_connection:
2551 connection_put(data_conn);
b8aa1682 2552 }
beaad64c 2553 last_seen_data_fd = -1;
b8aa1682
JD
2554 }
2555
f385ae0a
MD
2556 /* Normal exit, no error */
2557 ret = 0;
2558
095a4ae5 2559exit:
b8aa1682 2560error:
58eb9381 2561 /* Cleanup reamaining connection object. */
9d1bbf21 2562 rcu_read_lock();
90e7d72f
JG
2563 cds_lfht_for_each_entry(relay_connections_ht->ht, &iter.iter,
2564 destroy_conn,
58eb9381 2565 sock_n.node) {
f385ae0a 2566 health_code_update();
7591bab1
MD
2567 /*
2568 * No need to grab another ref, because we own
2569 * destroy_conn.
2570 */
2571 relay_thread_close_connection(&events, destroy_conn->sock->fd,
2572 destroy_conn);
b8aa1682 2573 }
94d49140 2574 rcu_read_unlock();
7591bab1
MD
2575
2576 lttng_poll_clean(&events);
7d2f7452 2577error_poll_create:
b8aa1682 2578 lttng_ht_destroy(relay_connections_ht);
095a4ae5 2579relay_connections_ht_error:
58eb9381
DG
2580 /* Close relay conn pipes */
2581 utils_close_pipe(relay_conn_pipe);
095a4ae5
MD
2582 if (err) {
2583 DBG("Thread exited with error");
2584 }
b8aa1682 2585 DBG("Worker thread cleanup complete");
095a4ae5 2586 free(data_buffer);
9b5e0863 2587error_testpoint:
f385ae0a
MD
2588 if (err) {
2589 health_error();
2590 ERR("Health error occurred in %s", __func__);
2591 }
2592 health_unregister(health_relayd);
9d1bbf21 2593 rcu_unregister_thread();
b4aacfdc 2594 lttng_relay_stop_threads();
b8aa1682
JD
2595 return NULL;
2596}
2597
2598/*
2599 * Create the relay command pipe to wake thread_manage_apps.
2600 * Closed in cleanup().
2601 */
58eb9381 2602static int create_relay_conn_pipe(void)
b8aa1682 2603{
a02de639 2604 int ret;
b8aa1682 2605
58eb9381 2606 ret = utils_create_pipe_cloexec(relay_conn_pipe);
b8aa1682 2607
b8aa1682
JD
2608 return ret;
2609}
2610
2611/*
2612 * main
2613 */
2614int main(int argc, char **argv)
2615{
178a0557 2616 int ret = 0, retval = 0;
b8aa1682
JD
2617 void *status;
2618
b8aa1682
JD
2619 /* Parse arguments */
2620 progname = argv[0];
178a0557
MD
2621 if (set_options(argc, argv)) {
2622 retval = -1;
2623 goto exit_options;
b8aa1682
JD
2624 }
2625
178a0557
MD
2626 if (set_signal_handler()) {
2627 retval = -1;
2628 goto exit_options;
b8aa1682
JD
2629 }
2630
4d513a50
DG
2631 /* Try to create directory if -o, --output is specified. */
2632 if (opt_output_path) {
994fa64f
DG
2633 if (*opt_output_path != '/') {
2634 ERR("Please specify an absolute path for -o, --output PATH");
178a0557
MD
2635 retval = -1;
2636 goto exit_options;
994fa64f
DG
2637 }
2638
d77dded2
JG
2639 ret = utils_mkdir_recursive(opt_output_path, S_IRWXU | S_IRWXG,
2640 -1, -1);
4d513a50
DG
2641 if (ret < 0) {
2642 ERR("Unable to create %s", opt_output_path);
178a0557
MD
2643 retval = -1;
2644 goto exit_options;
4d513a50
DG
2645 }
2646 }
2647
b8aa1682 2648 /* Daemonize */
b5218ffb 2649 if (opt_daemon || opt_background) {
3fd27398
MD
2650 int i;
2651
2652 ret = lttng_daemonize(&child_ppid, &recv_child_signal,
2653 !opt_background);
b8aa1682 2654 if (ret < 0) {
178a0557
MD
2655 retval = -1;
2656 goto exit_options;
b8aa1682 2657 }
3fd27398
MD
2658
2659 /*
2660 * We are in the child. Make sure all other file
2661 * descriptors are closed, in case we are called with
2662 * more opened file descriptors than the standard ones.
2663 */
2664 for (i = 3; i < sysconf(_SC_OPEN_MAX); i++) {
2665 (void) close(i);
2666 }
2667 }
2668
178a0557
MD
2669
2670 /* Initialize thread health monitoring */
2671 health_relayd = health_app_create(NR_HEALTH_RELAYD_TYPES);
2672 if (!health_relayd) {
2673 PERROR("health_app_create error");
2674 retval = -1;
2675 goto exit_health_app_create;
2676 }
2677
3fd27398 2678 /* Create thread quit pipe */
178a0557
MD
2679 if (init_thread_quit_pipe()) {
2680 retval = -1;
2681 goto exit_init_data;
b8aa1682
JD
2682 }
2683
1c20f0e2 2684 /* Check if daemon is UID = 0 */
7591bab1 2685 if (!getuid()) {
8d5c808e 2686 if (control_uri->port < 1024 || data_uri->port < 1024 || live_uri->port < 1024) {
b8aa1682 2687 ERR("Need to be root to use ports < 1024");
178a0557
MD
2688 retval = -1;
2689 goto exit_init_data;
b8aa1682
JD
2690 }
2691 }
2692
2693 /* Setup the thread apps communication pipe. */
178a0557
MD
2694 if (create_relay_conn_pipe()) {
2695 retval = -1;
2696 goto exit_init_data;
b8aa1682
JD
2697 }
2698
2699 /* Init relay command queue. */
8bdee6e2 2700 cds_wfcq_init(&relay_conn_queue.head, &relay_conn_queue.tail);
b8aa1682
JD
2701
2702 /* Set up max poll set size */
25b397f9
MD
2703 if (lttng_poll_set_max_size()) {
2704 retval = -1;
2705 goto exit_init_data;
2706 }
b8aa1682 2707
554831e7
MD
2708 /* Initialize communication library */
2709 lttcomm_init();
87e45c13 2710 lttcomm_inet_init();
554831e7 2711
d3e2ba59 2712 /* tables of sessions indexed by session ID */
7591bab1
MD
2713 sessions_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
2714 if (!sessions_ht) {
178a0557
MD
2715 retval = -1;
2716 goto exit_init_data;
d3e2ba59
JD
2717 }
2718
2719 /* tables of streams indexed by stream ID */
2a174661 2720 relay_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
d3e2ba59 2721 if (!relay_streams_ht) {
178a0557
MD
2722 retval = -1;
2723 goto exit_init_data;
d3e2ba59
JD
2724 }
2725
2726 /* tables of streams indexed by stream ID */
92c6ca54
DG
2727 viewer_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
2728 if (!viewer_streams_ht) {
178a0557
MD
2729 retval = -1;
2730 goto exit_init_data;
55706a7d
MD
2731 }
2732
65931c8b 2733 ret = utils_create_pipe(health_quit_pipe);
178a0557
MD
2734 if (ret) {
2735 retval = -1;
2736 goto exit_health_quit_pipe;
65931c8b
MD
2737 }
2738
2739 /* Create thread to manage the client socket */
2740 ret = pthread_create(&health_thread, NULL,
2741 thread_manage_health, (void *) NULL);
178a0557
MD
2742 if (ret) {
2743 errno = ret;
65931c8b 2744 PERROR("pthread_create health");
178a0557
MD
2745 retval = -1;
2746 goto exit_health_thread;
65931c8b
MD
2747 }
2748
b8aa1682
JD
2749 /* Setup the dispatcher thread */
2750 ret = pthread_create(&dispatcher_thread, NULL,
2751 relay_thread_dispatcher, (void *) NULL);
178a0557
MD
2752 if (ret) {
2753 errno = ret;
b8aa1682 2754 PERROR("pthread_create dispatcher");
178a0557
MD
2755 retval = -1;
2756 goto exit_dispatcher_thread;
b8aa1682
JD
2757 }
2758
2759 /* Setup the worker thread */
2760 ret = pthread_create(&worker_thread, NULL,
7591bab1 2761 relay_thread_worker, NULL);
178a0557
MD
2762 if (ret) {
2763 errno = ret;
b8aa1682 2764 PERROR("pthread_create worker");
178a0557
MD
2765 retval = -1;
2766 goto exit_worker_thread;
b8aa1682
JD
2767 }
2768
2769 /* Setup the listener thread */
2770 ret = pthread_create(&listener_thread, NULL,
2771 relay_thread_listener, (void *) NULL);
178a0557
MD
2772 if (ret) {
2773 errno = ret;
b8aa1682 2774 PERROR("pthread_create listener");
178a0557
MD
2775 retval = -1;
2776 goto exit_listener_thread;
b8aa1682
JD
2777 }
2778
7591bab1 2779 ret = relayd_live_create(live_uri);
178a0557 2780 if (ret) {
d3e2ba59 2781 ERR("Starting live viewer threads");
178a0557 2782 retval = -1;
50138f51 2783 goto exit_live;
d3e2ba59
JD
2784 }
2785
178a0557
MD
2786 /*
2787 * This is where we start awaiting program completion (e.g. through
2788 * signal that asks threads to teardown).
2789 */
2790
2791 ret = relayd_live_join();
2792 if (ret) {
2793 retval = -1;
2794 }
50138f51 2795exit_live:
178a0557 2796
b8aa1682 2797 ret = pthread_join(listener_thread, &status);
178a0557
MD
2798 if (ret) {
2799 errno = ret;
2800 PERROR("pthread_join listener_thread");
2801 retval = -1;
b8aa1682
JD
2802 }
2803
178a0557 2804exit_listener_thread:
b8aa1682 2805 ret = pthread_join(worker_thread, &status);
178a0557
MD
2806 if (ret) {
2807 errno = ret;
2808 PERROR("pthread_join worker_thread");
2809 retval = -1;
b8aa1682
JD
2810 }
2811
178a0557 2812exit_worker_thread:
b8aa1682 2813 ret = pthread_join(dispatcher_thread, &status);
178a0557
MD
2814 if (ret) {
2815 errno = ret;
2816 PERROR("pthread_join dispatcher_thread");
2817 retval = -1;
b8aa1682 2818 }
178a0557 2819exit_dispatcher_thread:
42415026 2820
65931c8b 2821 ret = pthread_join(health_thread, &status);
178a0557
MD
2822 if (ret) {
2823 errno = ret;
2824 PERROR("pthread_join health_thread");
2825 retval = -1;
65931c8b 2826 }
178a0557 2827exit_health_thread:
65931c8b 2828
65931c8b 2829 utils_close_pipe(health_quit_pipe);
178a0557 2830exit_health_quit_pipe:
65931c8b 2831
178a0557 2832exit_init_data:
55706a7d 2833 health_app_destroy(health_relayd);
55706a7d 2834exit_health_app_create:
178a0557 2835exit_options:
7591bab1
MD
2836 relayd_cleanup();
2837
2838 /* Ensure all prior call_rcu are done. */
2839 rcu_barrier();
d3e2ba59 2840
178a0557 2841 if (!retval) {
b8aa1682 2842 exit(EXIT_SUCCESS);
178a0557
MD
2843 } else {
2844 exit(EXIT_FAILURE);
b8aa1682 2845 }
b8aa1682 2846}
This page took 0.342211 seconds and 4 git commands to generate.