Fix: double put on error path
[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>
f40ef1d5 57#include <common/config/session-config.h>
7591bab1 58#include <urcu/rculist.h>
b8aa1682 59
0f907de1 60#include "cmd.h"
d3e2ba59 61#include "ctf-trace.h"
1c20f0e2 62#include "index.h"
0f907de1 63#include "utils.h"
b8aa1682 64#include "lttng-relayd.h"
d3e2ba59 65#include "live.h"
55706a7d 66#include "health-relayd.h"
9b5e0863 67#include "testpoint.h"
2f8f53af 68#include "viewer-stream.h"
2a174661
DG
69#include "session.h"
70#include "stream.h"
58eb9381 71#include "connection.h"
a44ca2ca 72#include "tracefile-array.h"
8af38ec0 73#include "tcp_keep_alive.h"
b8aa1682 74
4fc83d94
PP
75static const char *help_msg =
76#ifdef LTTNG_EMBED_HELP
77#include <lttng-relayd.8.h>
78#else
79NULL
80#endif
81;
82
b8aa1682 83/* command line options */
0f907de1 84char *opt_output_path;
b5218ffb 85static int opt_daemon, opt_background;
3fd27398
MD
86
87/*
88 * We need to wait for listener and live listener threads, as well as
89 * health check thread, before being ready to signal readiness.
90 */
91#define NR_LTTNG_RELAY_READY 3
92static int lttng_relay_ready = NR_LTTNG_RELAY_READY;
0848dba7
MD
93
94/* Size of receive buffer. */
95#define RECV_DATA_BUFFER_SIZE 65536
96
3fd27398
MD
97static int recv_child_signal; /* Set to 1 when a SIGUSR1 signal is received. */
98static pid_t child_ppid; /* Internal parent PID use with daemonize. */
99
095a4ae5
MD
100static struct lttng_uri *control_uri;
101static struct lttng_uri *data_uri;
d3e2ba59 102static struct lttng_uri *live_uri;
b8aa1682
JD
103
104const char *progname;
b8aa1682 105
65931c8b 106const char *tracing_group_name = DEFAULT_TRACING_GROUP;
cd60b05a
JG
107static int tracing_group_name_override;
108
109const char * const config_section_name = "relayd";
65931c8b 110
b8aa1682
JD
111/*
112 * Quit pipe for all threads. This permits a single cancellation point
113 * for all threads when receiving an event on the pipe.
114 */
0b242f62 115int thread_quit_pipe[2] = { -1, -1 };
b8aa1682
JD
116
117/*
118 * This pipe is used to inform the worker thread that a command is queued and
119 * ready to be processed.
120 */
58eb9381 121static int relay_conn_pipe[2] = { -1, -1 };
b8aa1682 122
26c9d55e 123/* Shared between threads */
b8aa1682
JD
124static int dispatch_thread_exit;
125
126static pthread_t listener_thread;
127static pthread_t dispatcher_thread;
128static pthread_t worker_thread;
65931c8b 129static pthread_t health_thread;
b8aa1682 130
7591bab1
MD
131/*
132 * last_relay_stream_id_lock protects last_relay_stream_id increment
133 * atomicity on 32-bit architectures.
134 */
135static pthread_mutex_t last_relay_stream_id_lock = PTHREAD_MUTEX_INITIALIZER;
095a4ae5 136static uint64_t last_relay_stream_id;
b8aa1682
JD
137
138/*
139 * Relay command queue.
140 *
141 * The relay_thread_listener and relay_thread_dispatcher communicate with this
142 * queue.
143 */
58eb9381 144static struct relay_conn_queue relay_conn_queue;
b8aa1682
JD
145
146/* buffer allocated at startup, used to store the trace data */
095a4ae5
MD
147static char *data_buffer;
148static unsigned int data_buffer_size;
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) {
e6c533d6 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 }
8af38ec0
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
5f7d3a72 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
5f7d3a72
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 /*
7591bab1
MD
1061 * The index on disk is encoded in big endian, so we don't need
1062 * to convert the data received on the network. The data_offset
1063 * value is NEVER modified here and is updated by the data
1064 * thread.
1c20f0e2 1065 */
7591bab1
MD
1066 index_data.packet_size = data->packet_size;
1067 index_data.content_size = data->content_size;
1068 index_data.timestamp_begin = data->timestamp_begin;
1069 index_data.timestamp_end = data->timestamp_end;
1070 index_data.events_discarded = data->events_discarded;
1071 index_data.stream_id = data->stream_id;
234cd636
JD
1072
1073 if (conn->minor >= 8) {
1074 index->index_data.stream_instance_id = data->stream_instance_id;
1075 index->index_data.packet_seq_num = data->packet_seq_num;
1076 }
1077
7591bab1 1078 return relay_index_set_data(index, &index_data);
1c20f0e2
JD
1079}
1080
c5b6f4f0
DG
1081/*
1082 * Handle the RELAYD_CREATE_SESSION command.
1083 *
1084 * On success, send back the session id or else return a negative value.
1085 */
7591bab1 1086static int relay_create_session(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1087 struct relay_connection *conn)
c5b6f4f0
DG
1088{
1089 int ret = 0, send_ret;
1090 struct relay_session *session;
1091 struct lttcomm_relayd_status_session reply;
36d2e35d 1092 char session_name[LTTNG_NAME_MAX];
9cf3eb20 1093 char hostname[LTTNG_HOST_NAME_MAX];
7591bab1
MD
1094 uint32_t live_timer = 0;
1095 bool snapshot = false;
c5b6f4f0 1096
36d2e35d 1097 memset(session_name, 0, LTTNG_NAME_MAX);
9cf3eb20 1098 memset(hostname, 0, LTTNG_HOST_NAME_MAX);
c5b6f4f0
DG
1099
1100 memset(&reply, 0, sizeof(reply));
1101
58eb9381 1102 switch (conn->minor) {
2a174661
DG
1103 case 1:
1104 case 2:
1105 case 3:
1106 break;
1107 case 4: /* LTTng sessiond 2.4 */
1108 default:
7591bab1
MD
1109 ret = cmd_create_session_2_4(conn, session_name,
1110 hostname, &live_timer, &snapshot);
1111 }
1112 if (ret < 0) {
1113 goto send_reply;
d3e2ba59
JD
1114 }
1115
7591bab1
MD
1116 session = session_create(session_name, hostname, live_timer,
1117 snapshot, conn->major, conn->minor);
1118 if (!session) {
1119 ret = -1;
1120 goto send_reply;
1121 }
1122 assert(!conn->session);
1123 conn->session = session;
c5b6f4f0
DG
1124 DBG("Created session %" PRIu64, session->id);
1125
7591bab1
MD
1126 reply.session_id = htobe64(session->id);
1127
1128send_reply:
c5b6f4f0
DG
1129 if (ret < 0) {
1130 reply.ret_code = htobe32(LTTNG_ERR_FATAL);
1131 } else {
1132 reply.ret_code = htobe32(LTTNG_OK);
1133 }
1134
58eb9381 1135 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
c5b6f4f0
DG
1136 if (send_ret < 0) {
1137 ERR("Relayd sending session id");
4169f5ad 1138 ret = send_ret;
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 */
7591bab1 1177static int relay_add_stream(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1178 struct relay_connection *conn)
b8aa1682 1179{
7591bab1
MD
1180 int ret;
1181 ssize_t send_ret;
58eb9381 1182 struct relay_session *session = conn->session;
b8aa1682
JD
1183 struct relay_stream *stream = NULL;
1184 struct lttcomm_relayd_status_stream reply;
4030a636 1185 struct ctf_trace *trace = NULL;
7591bab1
MD
1186 uint64_t stream_handle = -1ULL;
1187 char *path_name = NULL, *channel_name = NULL;
1188 uint64_t tracefile_size = 0, tracefile_count = 0;
b8aa1682 1189
58eb9381 1190 if (!session || conn->version_check_done == 0) {
b8aa1682
JD
1191 ERR("Trying to add a stream before version check");
1192 ret = -1;
1193 goto end_no_session;
1194 }
1195
7591bab1
MD
1196 switch (session->minor) {
1197 case 1: /* LTTng sessiond 2.1. Allocates path_name and channel_name. */
1198 ret = cmd_recv_stream_2_1(conn, &path_name,
1199 &channel_name);
0f907de1 1200 break;
7591bab1 1201 case 2: /* LTTng sessiond 2.2. Allocates path_name and channel_name. */
0f907de1 1202 default:
7591bab1
MD
1203 ret = cmd_recv_stream_2_2(conn, &path_name,
1204 &channel_name, &tracefile_size, &tracefile_count);
0f907de1
JD
1205 break;
1206 }
1207 if (ret < 0) {
7591bab1 1208 goto send_reply;
b8aa1682
JD
1209 }
1210
7591bab1 1211 trace = ctf_trace_get_by_path_or_create(session, path_name);
2a174661 1212 if (!trace) {
7591bab1 1213 goto send_reply;
2a174661 1214 }
7591bab1 1215 /* This stream here has one reference on the trace. */
2a174661 1216
7591bab1
MD
1217 pthread_mutex_lock(&last_relay_stream_id_lock);
1218 stream_handle = ++last_relay_stream_id;
1219 pthread_mutex_unlock(&last_relay_stream_id_lock);
d3e2ba59 1220
7591bab1
MD
1221 /* We pass ownership of path_name and channel_name. */
1222 stream = stream_create(trace, stream_handle, path_name,
1223 channel_name, tracefile_size, tracefile_count);
1224 path_name = NULL;
1225 channel_name = NULL;
a4baae1b 1226
2a174661 1227 /*
7591bab1
MD
1228 * Streams are the owners of their trace. Reference to trace is
1229 * kept within stream_create().
2a174661 1230 */
7591bab1 1231 ctf_trace_put(trace);
d3e2ba59 1232
7591bab1 1233send_reply:
53efb85a 1234 memset(&reply, 0, sizeof(reply));
7591bab1
MD
1235 reply.handle = htobe64(stream_handle);
1236 if (!stream) {
f73fabfd 1237 reply.ret_code = htobe32(LTTNG_ERR_UNK);
b8aa1682 1238 } else {
f73fabfd 1239 reply.ret_code = htobe32(LTTNG_OK);
b8aa1682 1240 }
5af40280 1241
58eb9381 1242 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
b8aa1682
JD
1243 sizeof(struct lttcomm_relayd_status_stream), 0);
1244 if (send_ret < 0) {
1245 ERR("Relay sending stream id");
7591bab1 1246 ret = (int) send_ret;
b8aa1682
JD
1247 }
1248
1249end_no_session:
7591bab1
MD
1250 free(path_name);
1251 free(channel_name);
0f907de1 1252 return ret;
b8aa1682
JD
1253}
1254
173af62f
DG
1255/*
1256 * relay_close_stream: close a specific stream
1257 */
7591bab1 1258static int relay_close_stream(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1259 struct relay_connection *conn)
173af62f 1260{
94d49140 1261 int ret, send_ret;
58eb9381 1262 struct relay_session *session = conn->session;
173af62f
DG
1263 struct lttcomm_relayd_close_stream stream_info;
1264 struct lttcomm_relayd_generic_reply reply;
1265 struct relay_stream *stream;
173af62f
DG
1266
1267 DBG("Close stream received");
1268
58eb9381 1269 if (!session || conn->version_check_done == 0) {
173af62f
DG
1270 ERR("Trying to close a stream before version check");
1271 ret = -1;
1272 goto end_no_session;
1273 }
1274
58eb9381 1275 ret = conn->sock->ops->recvmsg(conn->sock, &stream_info,
7c5aef62 1276 sizeof(struct lttcomm_relayd_close_stream), 0);
173af62f 1277 if (ret < sizeof(struct lttcomm_relayd_close_stream)) {
a6cd2b97
DG
1278 if (ret == 0) {
1279 /* Orderly shutdown. Not necessary to print an error. */
58eb9381 1280 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
a6cd2b97
DG
1281 } else {
1282 ERR("Relay didn't receive valid add_stream struct size : %d", ret);
1283 }
173af62f
DG
1284 ret = -1;
1285 goto end_no_session;
1286 }
1287
7591bab1 1288 stream = stream_get_by_id(be64toh(stream_info.stream_id));
173af62f
DG
1289 if (!stream) {
1290 ret = -1;
7591bab1 1291 goto end;
173af62f 1292 }
77f7bd85
MD
1293
1294 /*
1295 * Set last_net_seq_num before the close flag. Required by data
1296 * pending check.
1297 */
7591bab1 1298 pthread_mutex_lock(&stream->lock);
8e2583a4 1299 stream->last_net_seq_num = be64toh(stream_info.last_net_seq_num);
77f7bd85
MD
1300 pthread_mutex_unlock(&stream->lock);
1301
bda7c7b9
JG
1302 /*
1303 * This is one of the conditions which may trigger a stream close
1304 * with the others being:
1305 * 1) A close command is received for a stream
1306 * 2) The control connection owning the stream is closed
1307 * 3) We have received all of the stream's data _after_ a close
1308 * request.
1309 */
1310 try_stream_close(stream);
7591bab1
MD
1311 if (stream->is_metadata) {
1312 struct relay_viewer_stream *vstream;
173af62f 1313
7591bab1
MD
1314 vstream = viewer_stream_get_by_id(stream->stream_handle);
1315 if (vstream) {
1316 if (vstream->metadata_sent == stream->metadata_received) {
1317 /*
1318 * Since all the metadata has been sent to the
1319 * viewer and that we have a request to close
1320 * its stream, we can safely teardown the
1321 * corresponding metadata viewer stream.
1322 */
1323 viewer_stream_put(vstream);
1324 }
1325 /* Put local reference. */
1326 viewer_stream_put(vstream);
1327 }
1328 }
7591bab1 1329 stream_put(stream);
173af62f 1330
7591bab1 1331end:
53efb85a 1332 memset(&reply, 0, sizeof(reply));
173af62f 1333 if (ret < 0) {
f73fabfd 1334 reply.ret_code = htobe32(LTTNG_ERR_UNK);
173af62f 1335 } else {
f73fabfd 1336 reply.ret_code = htobe32(LTTNG_OK);
173af62f 1337 }
58eb9381 1338 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
173af62f
DG
1339 sizeof(struct lttcomm_relayd_generic_reply), 0);
1340 if (send_ret < 0) {
1341 ERR("Relay sending stream id");
4169f5ad 1342 ret = send_ret;
173af62f
DG
1343 }
1344
1345end_no_session:
1346 return ret;
1347}
1348
93ec662e
JD
1349/*
1350 * relay_reset_metadata: reset a metadata stream
1351 */
1352static
1353int relay_reset_metadata(struct lttcomm_relayd_hdr *recv_hdr,
1354 struct relay_connection *conn)
1355{
1356 int ret, send_ret;
1357 struct relay_session *session = conn->session;
1358 struct lttcomm_relayd_reset_metadata stream_info;
1359 struct lttcomm_relayd_generic_reply reply;
1360 struct relay_stream *stream;
1361
1362 DBG("Reset metadata received");
1363
1364 if (!session || conn->version_check_done == 0) {
1365 ERR("Trying to reset a metadata stream before version check");
1366 ret = -1;
1367 goto end_no_session;
1368 }
1369
1370 ret = conn->sock->ops->recvmsg(conn->sock, &stream_info,
1371 sizeof(struct lttcomm_relayd_reset_metadata), 0);
1372 if (ret < sizeof(struct lttcomm_relayd_reset_metadata)) {
1373 if (ret == 0) {
1374 /* Orderly shutdown. Not necessary to print an error. */
1375 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1376 } else {
1377 ERR("Relay didn't receive valid reset_metadata struct "
1378 "size : %d", ret);
1379 }
1380 ret = -1;
1381 goto end_no_session;
1382 }
1383 DBG("Update metadata to version %" PRIu64, be64toh(stream_info.version));
1384
1385 /* Unsupported for live sessions for now. */
1386 if (session->live_timer != 0) {
1387 ret = -1;
1388 goto end;
1389 }
1390
1391 stream = stream_get_by_id(be64toh(stream_info.stream_id));
1392 if (!stream) {
1393 ret = -1;
1394 goto end;
1395 }
1396 pthread_mutex_lock(&stream->lock);
1397 if (!stream->is_metadata) {
1398 ret = -1;
1399 goto end_unlock;
1400 }
1401
1402 ret = utils_rotate_stream_file(stream->path_name, stream->channel_name,
1403 0, 0, -1, -1, stream->stream_fd->fd, NULL,
1404 &stream->stream_fd->fd);
1405 if (ret < 0) {
1406 ERR("Failed to rotate metadata file %s of channel %s",
1407 stream->path_name, stream->channel_name);
1408 goto end_unlock;
1409 }
1410
1411end_unlock:
1412 pthread_mutex_unlock(&stream->lock);
1413 stream_put(stream);
1414
1415end:
1416 memset(&reply, 0, sizeof(reply));
1417 if (ret < 0) {
1418 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1419 } else {
1420 reply.ret_code = htobe32(LTTNG_OK);
1421 }
1422 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1423 sizeof(struct lttcomm_relayd_generic_reply), 0);
1424 if (send_ret < 0) {
1425 ERR("Relay sending reset metadata reply");
1426 ret = send_ret;
1427 }
1428
1429end_no_session:
1430 return ret;
1431}
1432
b8aa1682
JD
1433/*
1434 * relay_unknown_command: send -1 if received unknown command
1435 */
7591bab1 1436static void relay_unknown_command(struct relay_connection *conn)
b8aa1682
JD
1437{
1438 struct lttcomm_relayd_generic_reply reply;
1439 int ret;
1440
53efb85a 1441 memset(&reply, 0, sizeof(reply));
f73fabfd 1442 reply.ret_code = htobe32(LTTNG_ERR_UNK);
58eb9381 1443 ret = conn->sock->ops->sendmsg(conn->sock, &reply,
b8aa1682
JD
1444 sizeof(struct lttcomm_relayd_generic_reply), 0);
1445 if (ret < 0) {
1446 ERR("Relay sending unknown command");
1447 }
1448}
1449
1450/*
1451 * relay_start: send an acknowledgment to the client to tell if we are
1452 * ready to receive data. We are ready if a session is established.
1453 */
7591bab1 1454static int relay_start(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1455 struct relay_connection *conn)
b8aa1682 1456{
f73fabfd 1457 int ret = htobe32(LTTNG_OK);
b8aa1682 1458 struct lttcomm_relayd_generic_reply reply;
58eb9381 1459 struct relay_session *session = conn->session;
b8aa1682
JD
1460
1461 if (!session) {
1462 DBG("Trying to start the streaming without a session established");
f73fabfd 1463 ret = htobe32(LTTNG_ERR_UNK);
b8aa1682
JD
1464 }
1465
53efb85a 1466 memset(&reply, 0, sizeof(reply));
b8aa1682 1467 reply.ret_code = ret;
58eb9381 1468 ret = conn->sock->ops->sendmsg(conn->sock, &reply,
b8aa1682
JD
1469 sizeof(struct lttcomm_relayd_generic_reply), 0);
1470 if (ret < 0) {
1471 ERR("Relay sending start ack");
1472 }
1473
1474 return ret;
1475}
1476
1d4dfdef
DG
1477/*
1478 * Append padding to the file pointed by the file descriptor fd.
1479 */
1480static int write_padding_to_file(int fd, uint32_t size)
1481{
6cd525e8 1482 ssize_t ret = 0;
1d4dfdef
DG
1483 char *zeros;
1484
1485 if (size == 0) {
1486 goto end;
1487 }
1488
1489 zeros = zmalloc(size);
1490 if (zeros == NULL) {
1491 PERROR("zmalloc zeros for padding");
1492 ret = -1;
1493 goto end;
1494 }
1495
6cd525e8
MD
1496 ret = lttng_write(fd, zeros, size);
1497 if (ret < size) {
1d4dfdef
DG
1498 PERROR("write padding to file");
1499 }
1500
e986c7a1
DG
1501 free(zeros);
1502
1d4dfdef
DG
1503end:
1504 return ret;
1505}
1506
b8aa1682 1507/*
7591bab1 1508 * relay_recv_metadata: receive the metadata for the session.
b8aa1682 1509 */
7591bab1 1510static int relay_recv_metadata(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1511 struct relay_connection *conn)
b8aa1682 1512{
32d1569c 1513 int ret = 0;
6cd525e8 1514 ssize_t size_ret;
58eb9381 1515 struct relay_session *session = conn->session;
b8aa1682
JD
1516 struct lttcomm_relayd_metadata_payload *metadata_struct;
1517 struct relay_stream *metadata_stream;
1518 uint64_t data_size, payload_size;
1519
1520 if (!session) {
1521 ERR("Metadata sent before version check");
1522 ret = -1;
1523 goto end;
1524 }
1525
f6416125
MD
1526 data_size = payload_size = be64toh(recv_hdr->data_size);
1527 if (data_size < sizeof(struct lttcomm_relayd_metadata_payload)) {
1528 ERR("Incorrect data size");
1529 ret = -1;
1530 goto end;
1531 }
1532 payload_size -= sizeof(struct lttcomm_relayd_metadata_payload);
1533
b8aa1682 1534 if (data_buffer_size < data_size) {
d7b3776f 1535 /* In case the realloc fails, we can free the memory */
c617c0c6
MD
1536 char *tmp_data_ptr;
1537
1538 tmp_data_ptr = realloc(data_buffer, data_size);
1539 if (!tmp_data_ptr) {
b8aa1682 1540 ERR("Allocating data buffer");
c617c0c6 1541 free(data_buffer);
b8aa1682
JD
1542 ret = -1;
1543 goto end;
1544 }
c617c0c6 1545 data_buffer = tmp_data_ptr;
b8aa1682
JD
1546 data_buffer_size = data_size;
1547 }
1548 memset(data_buffer, 0, data_size);
77c7c900 1549 DBG2("Relay receiving metadata, waiting for %" PRIu64 " bytes", data_size);
32d1569c
JG
1550 size_ret = conn->sock->ops->recvmsg(conn->sock, data_buffer, data_size, 0);
1551 if (size_ret < 0 || size_ret != data_size) {
1552 if (size_ret == 0) {
a6cd2b97 1553 /* Orderly shutdown. Not necessary to print an error. */
58eb9381 1554 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
a6cd2b97
DG
1555 } else {
1556 ERR("Relay didn't receive the whole metadata");
1557 }
b8aa1682 1558 ret = -1;
b8aa1682
JD
1559 goto end;
1560 }
1561 metadata_struct = (struct lttcomm_relayd_metadata_payload *) data_buffer;
9d1bbf21 1562
7591bab1 1563 metadata_stream = stream_get_by_id(be64toh(metadata_struct->stream_id));
b8aa1682
JD
1564 if (!metadata_stream) {
1565 ret = -1;
7591bab1 1566 goto end;
b8aa1682
JD
1567 }
1568
7591bab1
MD
1569 pthread_mutex_lock(&metadata_stream->lock);
1570
1571 size_ret = lttng_write(metadata_stream->stream_fd->fd, metadata_struct->payload,
6cd525e8
MD
1572 payload_size);
1573 if (size_ret < payload_size) {
b8aa1682
JD
1574 ERR("Relay error writing metadata on file");
1575 ret = -1;
7591bab1 1576 goto end_put;
b8aa1682 1577 }
1d4dfdef 1578
32d1569c 1579 size_ret = write_padding_to_file(metadata_stream->stream_fd->fd,
1d4dfdef 1580 be32toh(metadata_struct->padding_size));
32d1569c 1581 if (size_ret < 0) {
7591bab1 1582 goto end_put;
1d4dfdef 1583 }
2a174661 1584
7591bab1 1585 metadata_stream->metadata_received +=
d3e2ba59 1586 payload_size + be32toh(metadata_struct->padding_size);
7591bab1
MD
1587 DBG2("Relay metadata written. Updated metadata_received %" PRIu64,
1588 metadata_stream->metadata_received);
1d4dfdef 1589
7591bab1
MD
1590end_put:
1591 pthread_mutex_unlock(&metadata_stream->lock);
1592 stream_put(metadata_stream);
b8aa1682
JD
1593end:
1594 return ret;
1595}
1596
1597/*
1598 * relay_send_version: send relayd version number
1599 */
7591bab1 1600static int relay_send_version(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1601 struct relay_connection *conn)
b8aa1682 1602{
7f51dcba 1603 int ret;
092b6259 1604 struct lttcomm_relayd_version reply, msg;
b28f7baa 1605 bool compatible = true;
b8aa1682 1606
58eb9381 1607 conn->version_check_done = 1;
b8aa1682 1608
092b6259 1609 /* Get version from the other side. */
58eb9381 1610 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
092b6259 1611 if (ret < 0 || ret != sizeof(msg)) {
a6cd2b97
DG
1612 if (ret == 0) {
1613 /* Orderly shutdown. Not necessary to print an error. */
58eb9381 1614 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
a6cd2b97
DG
1615 } else {
1616 ERR("Relay failed to receive the version values.");
1617 }
092b6259 1618 ret = -1;
092b6259
DG
1619 goto end;
1620 }
1621
53efb85a 1622 memset(&reply, 0, sizeof(reply));
d83a952c
MD
1623 reply.major = RELAYD_VERSION_COMM_MAJOR;
1624 reply.minor = RELAYD_VERSION_COMM_MINOR;
d4519fa3
JD
1625
1626 /* Major versions must be the same */
1627 if (reply.major != be32toh(msg.major)) {
6151a90f
JD
1628 DBG("Incompatible major versions (%u vs %u), deleting session",
1629 reply.major, be32toh(msg.major));
b28f7baa 1630 compatible = false;
d4519fa3
JD
1631 }
1632
58eb9381 1633 conn->major = reply.major;
0f907de1
JD
1634 /* We adapt to the lowest compatible version */
1635 if (reply.minor <= be32toh(msg.minor)) {
58eb9381 1636 conn->minor = reply.minor;
0f907de1 1637 } else {
58eb9381 1638 conn->minor = be32toh(msg.minor);
0f907de1
JD
1639 }
1640
6151a90f
JD
1641 reply.major = htobe32(reply.major);
1642 reply.minor = htobe32(reply.minor);
58eb9381 1643 ret = conn->sock->ops->sendmsg(conn->sock, &reply,
6151a90f
JD
1644 sizeof(struct lttcomm_relayd_version), 0);
1645 if (ret < 0) {
1646 ERR("Relay sending version");
1647 }
1648
b28f7baa
JD
1649 if (!compatible) {
1650 ret = -1;
1651 goto end;
1652 }
1653
58eb9381
DG
1654 DBG("Version check done using protocol %u.%u", conn->major,
1655 conn->minor);
b8aa1682
JD
1656
1657end:
1658 return ret;
1659}
1660
c8f59ee5 1661/*
6d805429 1662 * Check for data pending for a given stream id from the session daemon.
c8f59ee5 1663 */
7591bab1 1664static int relay_data_pending(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1665 struct relay_connection *conn)
c8f59ee5 1666{
58eb9381 1667 struct relay_session *session = conn->session;
6d805429 1668 struct lttcomm_relayd_data_pending msg;
c8f59ee5
DG
1669 struct lttcomm_relayd_generic_reply reply;
1670 struct relay_stream *stream;
1671 int ret;
c8f59ee5
DG
1672 uint64_t last_net_seq_num, stream_id;
1673
6d805429 1674 DBG("Data pending command received");
c8f59ee5 1675
58eb9381 1676 if (!session || conn->version_check_done == 0) {
c8f59ee5
DG
1677 ERR("Trying to check for data before version check");
1678 ret = -1;
1679 goto end_no_session;
1680 }
1681
58eb9381 1682 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
c8f59ee5 1683 if (ret < sizeof(msg)) {
a6cd2b97
DG
1684 if (ret == 0) {
1685 /* Orderly shutdown. Not necessary to print an error. */
58eb9381 1686 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
a6cd2b97
DG
1687 } else {
1688 ERR("Relay didn't receive valid data_pending struct size : %d",
1689 ret);
1690 }
c8f59ee5
DG
1691 ret = -1;
1692 goto end_no_session;
1693 }
1694
1695 stream_id = be64toh(msg.stream_id);
1696 last_net_seq_num = be64toh(msg.last_net_seq_num);
1697
7591bab1 1698 stream = stream_get_by_id(stream_id);
de91f48a 1699 if (stream == NULL) {
c8f59ee5 1700 ret = -1;
7591bab1 1701 goto end;
c8f59ee5
DG
1702 }
1703
7591bab1
MD
1704 pthread_mutex_lock(&stream->lock);
1705
6d805429 1706 DBG("Data pending for stream id %" PRIu64 " prev_seq %" PRIu64
c8f59ee5
DG
1707 " and last_seq %" PRIu64, stream_id, stream->prev_seq,
1708 last_net_seq_num);
1709
33832e64 1710 /* Avoid wrapping issue */
39df6d9f 1711 if (((int64_t) (stream->prev_seq - last_net_seq_num)) >= 0) {
6d805429 1712 /* Data has in fact been written and is NOT pending */
c8f59ee5 1713 ret = 0;
6d805429
DG
1714 } else {
1715 /* Data still being streamed thus pending */
1716 ret = 1;
c8f59ee5
DG
1717 }
1718
7591bab1
MD
1719 stream->data_pending_check_done = true;
1720 pthread_mutex_unlock(&stream->lock);
f7079f67 1721
7591bab1
MD
1722 stream_put(stream);
1723end:
c8f59ee5 1724
53efb85a 1725 memset(&reply, 0, sizeof(reply));
c8f59ee5 1726 reply.ret_code = htobe32(ret);
58eb9381 1727 ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
c8f59ee5 1728 if (ret < 0) {
6d805429 1729 ERR("Relay data pending ret code failed");
c8f59ee5
DG
1730 }
1731
1732end_no_session:
1733 return ret;
1734}
1735
1736/*
1737 * Wait for the control socket to reach a quiescent state.
1738 *
7591bab1
MD
1739 * Note that for now, when receiving this command from the session
1740 * daemon, this means that every subsequent commands or data received on
1741 * the control socket has been handled. So, this is why we simply return
1742 * OK here.
c8f59ee5 1743 */
7591bab1 1744static int relay_quiescent_control(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1745 struct relay_connection *conn)
c8f59ee5
DG
1746{
1747 int ret;
ad7051c0
DG
1748 uint64_t stream_id;
1749 struct relay_stream *stream;
ad7051c0 1750 struct lttcomm_relayd_quiescent_control msg;
c8f59ee5
DG
1751 struct lttcomm_relayd_generic_reply reply;
1752
1753 DBG("Checking quiescent state on control socket");
1754
58eb9381 1755 if (!conn->session || conn->version_check_done == 0) {
ad7051c0
DG
1756 ERR("Trying to check for data before version check");
1757 ret = -1;
1758 goto end_no_session;
1759 }
1760
58eb9381 1761 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
ad7051c0 1762 if (ret < sizeof(msg)) {
a6cd2b97
DG
1763 if (ret == 0) {
1764 /* Orderly shutdown. Not necessary to print an error. */
58eb9381 1765 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
a6cd2b97
DG
1766 } else {
1767 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1768 ret);
1769 }
ad7051c0
DG
1770 ret = -1;
1771 goto end_no_session;
1772 }
1773
1774 stream_id = be64toh(msg.stream_id);
7591bab1
MD
1775 stream = stream_get_by_id(stream_id);
1776 if (!stream) {
1777 goto reply;
1778 }
1779 pthread_mutex_lock(&stream->lock);
1780 stream->data_pending_check_done = true;
1781 pthread_mutex_unlock(&stream->lock);
1782 DBG("Relay quiescent control pending flag set to %" PRIu64, stream_id);
1783 stream_put(stream);
1784reply:
53efb85a 1785 memset(&reply, 0, sizeof(reply));
c8f59ee5 1786 reply.ret_code = htobe32(LTTNG_OK);
58eb9381 1787 ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
c8f59ee5 1788 if (ret < 0) {
6d805429 1789 ERR("Relay data quiescent control ret code failed");
c8f59ee5
DG
1790 }
1791
ad7051c0 1792end_no_session:
c8f59ee5
DG
1793 return ret;
1794}
1795
f7079f67 1796/*
7591bab1
MD
1797 * Initialize a data pending command. This means that a consumer is about
1798 * to ask for data pending for each stream it holds. Simply iterate over
1799 * all streams of a session and set the data_pending_check_done flag.
f7079f67
DG
1800 *
1801 * This command returns to the client a LTTNG_OK code.
1802 */
7591bab1 1803static int relay_begin_data_pending(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1804 struct relay_connection *conn)
f7079f67
DG
1805{
1806 int ret;
1807 struct lttng_ht_iter iter;
1808 struct lttcomm_relayd_begin_data_pending msg;
1809 struct lttcomm_relayd_generic_reply reply;
1810 struct relay_stream *stream;
1811 uint64_t session_id;
1812
1813 assert(recv_hdr);
58eb9381 1814 assert(conn);
f7079f67
DG
1815
1816 DBG("Init streams for data pending");
1817
58eb9381 1818 if (!conn->session || conn->version_check_done == 0) {
f7079f67
DG
1819 ERR("Trying to check for data before version check");
1820 ret = -1;
1821 goto end_no_session;
1822 }
1823
58eb9381 1824 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
f7079f67 1825 if (ret < sizeof(msg)) {
a6cd2b97
DG
1826 if (ret == 0) {
1827 /* Orderly shutdown. Not necessary to print an error. */
58eb9381 1828 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
a6cd2b97
DG
1829 } else {
1830 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1831 ret);
1832 }
f7079f67
DG
1833 ret = -1;
1834 goto end_no_session;
1835 }
1836
1837 session_id = be64toh(msg.session_id);
1838
1839 /*
7591bab1
MD
1840 * Iterate over all streams to set the begin data pending flag.
1841 * For now, the streams are indexed by stream handle so we have
1842 * to iterate over all streams to find the one associated with
1843 * the right session_id.
f7079f67
DG
1844 */
1845 rcu_read_lock();
d3e2ba59 1846 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2a174661 1847 node.node) {
7591bab1
MD
1848 if (!stream_get(stream)) {
1849 continue;
1850 }
1851 if (stream->trace->session->id == session_id) {
1852 pthread_mutex_lock(&stream->lock);
1853 stream->data_pending_check_done = false;
1854 pthread_mutex_unlock(&stream->lock);
f7079f67
DG
1855 DBG("Set begin data pending flag to stream %" PRIu64,
1856 stream->stream_handle);
1857 }
7591bab1 1858 stream_put(stream);
f7079f67
DG
1859 }
1860 rcu_read_unlock();
1861
53efb85a 1862 memset(&reply, 0, sizeof(reply));
f7079f67
DG
1863 /* All good, send back reply. */
1864 reply.ret_code = htobe32(LTTNG_OK);
1865
58eb9381 1866 ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
f7079f67
DG
1867 if (ret < 0) {
1868 ERR("Relay begin data pending send reply failed");
1869 }
1870
1871end_no_session:
1872 return ret;
1873}
1874
1875/*
7591bab1
MD
1876 * End data pending command. This will check, for a given session id, if
1877 * each stream associated with it has its data_pending_check_done flag
1878 * set. If not, this means that the client lost track of the stream but
1879 * the data is still being streamed on our side. In this case, we inform
1880 * the client that data is in flight.
f7079f67
DG
1881 *
1882 * Return to the client if there is data in flight or not with a ret_code.
1883 */
7591bab1 1884static int relay_end_data_pending(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1885 struct relay_connection *conn)
f7079f67
DG
1886{
1887 int ret;
1888 struct lttng_ht_iter iter;
1889 struct lttcomm_relayd_end_data_pending msg;
1890 struct lttcomm_relayd_generic_reply reply;
1891 struct relay_stream *stream;
1892 uint64_t session_id;
1893 uint32_t is_data_inflight = 0;
1894
f7079f67
DG
1895 DBG("End data pending command");
1896
58eb9381 1897 if (!conn->session || conn->version_check_done == 0) {
f7079f67
DG
1898 ERR("Trying to check for data before version check");
1899 ret = -1;
1900 goto end_no_session;
1901 }
1902
58eb9381 1903 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
f7079f67 1904 if (ret < sizeof(msg)) {
a6cd2b97
DG
1905 if (ret == 0) {
1906 /* Orderly shutdown. Not necessary to print an error. */
58eb9381 1907 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
a6cd2b97
DG
1908 } else {
1909 ERR("Relay didn't receive valid end data_pending struct size: %d",
1910 ret);
1911 }
f7079f67
DG
1912 ret = -1;
1913 goto end_no_session;
1914 }
1915
1916 session_id = be64toh(msg.session_id);
1917
7591bab1
MD
1918 /*
1919 * Iterate over all streams to see if the begin data pending
1920 * flag is set.
1921 */
f7079f67 1922 rcu_read_lock();
d3e2ba59 1923 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2a174661 1924 node.node) {
7591bab1
MD
1925 if (!stream_get(stream)) {
1926 continue;
1927 }
1928 if (stream->trace->session->id != session_id) {
1929 stream_put(stream);
1930 continue;
1931 }
1932 pthread_mutex_lock(&stream->lock);
1933 if (!stream->data_pending_check_done) {
1934 if (!stream->closed || !(((int64_t) (stream->prev_seq - stream->last_net_seq_num)) >= 0)) {
1935 is_data_inflight = 1;
1936 DBG("Data is still in flight for stream %" PRIu64,
1937 stream->stream_handle);
1938 pthread_mutex_unlock(&stream->lock);
1939 stream_put(stream);
1940 break;
1941 }
f7079f67 1942 }
7591bab1
MD
1943 pthread_mutex_unlock(&stream->lock);
1944 stream_put(stream);
f7079f67
DG
1945 }
1946 rcu_read_unlock();
1947
53efb85a 1948 memset(&reply, 0, sizeof(reply));
f7079f67
DG
1949 /* All good, send back reply. */
1950 reply.ret_code = htobe32(is_data_inflight);
1951
58eb9381 1952 ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
f7079f67
DG
1953 if (ret < 0) {
1954 ERR("Relay end data pending send reply failed");
1955 }
1956
1957end_no_session:
1958 return ret;
1959}
1960
1c20f0e2
JD
1961/*
1962 * Receive an index for a specific stream.
1963 *
1964 * Return 0 on success else a negative value.
1965 */
7591bab1 1966static int relay_recv_index(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1967 struct relay_connection *conn)
1c20f0e2 1968{
7591bab1 1969 int ret, send_ret;
58eb9381 1970 struct relay_session *session = conn->session;
1c20f0e2 1971 struct lttcomm_relayd_index index_info;
7591bab1 1972 struct relay_index *index;
1c20f0e2
JD
1973 struct lttcomm_relayd_generic_reply reply;
1974 struct relay_stream *stream;
1975 uint64_t net_seq_num;
f8f3885c 1976 size_t msg_len;
1c20f0e2 1977
58eb9381 1978 assert(conn);
1c20f0e2
JD
1979
1980 DBG("Relay receiving index");
1981
58eb9381 1982 if (!session || conn->version_check_done == 0) {
1c20f0e2
JD
1983 ERR("Trying to close a stream before version check");
1984 ret = -1;
1985 goto end_no_session;
1986 }
1987
f8f3885c
MD
1988 msg_len = lttcomm_relayd_index_len(
1989 lttng_to_index_major(conn->major, conn->minor),
1990 lttng_to_index_minor(conn->major, conn->minor));
58eb9381 1991 ret = conn->sock->ops->recvmsg(conn->sock, &index_info,
f8f3885c
MD
1992 msg_len, 0);
1993 if (ret < msg_len) {
1c20f0e2
JD
1994 if (ret == 0) {
1995 /* Orderly shutdown. Not necessary to print an error. */
58eb9381 1996 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1c20f0e2
JD
1997 } else {
1998 ERR("Relay didn't receive valid index struct size : %d", ret);
1999 }
2000 ret = -1;
2001 goto end_no_session;
2002 }
2003
2004 net_seq_num = be64toh(index_info.net_seq_num);
2005
7591bab1 2006 stream = stream_get_by_id(be64toh(index_info.relay_stream_id));
1c20f0e2 2007 if (!stream) {
7591bab1 2008 ERR("stream_get_by_id not found");
1c20f0e2 2009 ret = -1;
7591bab1 2010 goto end;
1c20f0e2 2011 }
7591bab1 2012 pthread_mutex_lock(&stream->lock);
1c20f0e2 2013
d3e2ba59
JD
2014 /* Live beacon handling */
2015 if (index_info.packet_size == 0) {
7591bab1
MD
2016 DBG("Received live beacon for stream %" PRIu64,
2017 stream->stream_handle);
d3e2ba59
JD
2018
2019 /*
7591bab1
MD
2020 * Only flag a stream inactive when it has already
2021 * received data and no indexes are in flight.
d3e2ba59 2022 */
a44ca2ca 2023 if (stream->index_received_seqcount > 0
7591bab1
MD
2024 && stream->indexes_in_flight == 0) {
2025 stream->beacon_ts_end =
2026 be64toh(index_info.timestamp_end);
d3e2ba59
JD
2027 }
2028 ret = 0;
7591bab1 2029 goto end_stream_put;
d3e2ba59
JD
2030 } else {
2031 stream->beacon_ts_end = -1ULL;
2032 }
2033
528f2ffa
JD
2034 if (stream->ctf_stream_id == -1ULL) {
2035 stream->ctf_stream_id = be64toh(index_info.stream_id);
2036 }
7591bab1
MD
2037 index = relay_index_get_by_id_or_create(stream, net_seq_num);
2038 if (!index) {
2039 ret = -1;
2040 ERR("relay_index_get_by_id_or_create index NULL");
2041 goto end_stream_put;
1c20f0e2 2042 }
234cd636 2043 if (set_index_control_data(index, &index_info, conn)) {
7591bab1
MD
2044 ERR("set_index_control_data error");
2045 relay_index_put(index);
2046 ret = -1;
2047 goto end_stream_put;
2048 }
2049 ret = relay_index_try_flush(index);
2050 if (ret == 0) {
a44ca2ca
MD
2051 tracefile_array_commit_seq(stream->tfa);
2052 stream->index_received_seqcount++;
7591bab1
MD
2053 } else if (ret > 0) {
2054 /* no flush. */
2055 ret = 0;
2056 } else {
a86c0657
JR
2057 /*
2058 * ret < 0
2059 *
2060 * relay_index_try_flush is responsible for the self-reference
2061 * put of the index object on error.
2062 */
7591bab1 2063 ERR("relay_index_try_flush error %d", ret);
7591bab1 2064 ret = -1;
1c20f0e2
JD
2065 }
2066
7591bab1
MD
2067end_stream_put:
2068 pthread_mutex_unlock(&stream->lock);
2069 stream_put(stream);
2070
2071end:
1c20f0e2 2072
53efb85a 2073 memset(&reply, 0, sizeof(reply));
1c20f0e2
JD
2074 if (ret < 0) {
2075 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2076 } else {
2077 reply.ret_code = htobe32(LTTNG_OK);
2078 }
58eb9381 2079 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1c20f0e2
JD
2080 if (send_ret < 0) {
2081 ERR("Relay sending close index id reply");
2082 ret = send_ret;
2083 }
2084
2085end_no_session:
2086 return ret;
2087}
2088
a4baae1b
JD
2089/*
2090 * Receive the streams_sent message.
2091 *
2092 * Return 0 on success else a negative value.
2093 */
7591bab1 2094static int relay_streams_sent(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 2095 struct relay_connection *conn)
a4baae1b
JD
2096{
2097 int ret, send_ret;
2098 struct lttcomm_relayd_generic_reply reply;
2099
58eb9381 2100 assert(conn);
a4baae1b
JD
2101
2102 DBG("Relay receiving streams_sent");
2103
58eb9381 2104 if (!conn->session || conn->version_check_done == 0) {
a4baae1b
JD
2105 ERR("Trying to close a stream before version check");
2106 ret = -1;
2107 goto end_no_session;
2108 }
2109
2110 /*
7591bab1
MD
2111 * Publish every pending stream in the connection recv list which are
2112 * now ready to be used by the viewer.
4a9daf17 2113 */
7591bab1 2114 publish_connection_local_streams(conn);
4a9daf17 2115
53efb85a 2116 memset(&reply, 0, sizeof(reply));
a4baae1b 2117 reply.ret_code = htobe32(LTTNG_OK);
58eb9381 2118 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
a4baae1b
JD
2119 if (send_ret < 0) {
2120 ERR("Relay sending sent_stream reply");
2121 ret = send_ret;
2122 } else {
2123 /* Success. */
2124 ret = 0;
2125 }
2126
2127end_no_session:
2128 return ret;
2129}
2130
b8aa1682 2131/*
d3e2ba59 2132 * Process the commands received on the control socket
b8aa1682 2133 */
7591bab1 2134static int relay_process_control(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 2135 struct relay_connection *conn)
b8aa1682
JD
2136{
2137 int ret = 0;
2138
2139 switch (be32toh(recv_hdr->cmd)) {
b8aa1682 2140 case RELAYD_CREATE_SESSION:
58eb9381 2141 ret = relay_create_session(recv_hdr, conn);
b8aa1682 2142 break;
b8aa1682 2143 case RELAYD_ADD_STREAM:
58eb9381 2144 ret = relay_add_stream(recv_hdr, conn);
b8aa1682
JD
2145 break;
2146 case RELAYD_START_DATA:
58eb9381 2147 ret = relay_start(recv_hdr, conn);
b8aa1682
JD
2148 break;
2149 case RELAYD_SEND_METADATA:
58eb9381 2150 ret = relay_recv_metadata(recv_hdr, conn);
b8aa1682
JD
2151 break;
2152 case RELAYD_VERSION:
58eb9381 2153 ret = relay_send_version(recv_hdr, conn);
b8aa1682 2154 break;
173af62f 2155 case RELAYD_CLOSE_STREAM:
58eb9381 2156 ret = relay_close_stream(recv_hdr, conn);
173af62f 2157 break;
6d805429 2158 case RELAYD_DATA_PENDING:
58eb9381 2159 ret = relay_data_pending(recv_hdr, conn);
c8f59ee5
DG
2160 break;
2161 case RELAYD_QUIESCENT_CONTROL:
58eb9381 2162 ret = relay_quiescent_control(recv_hdr, conn);
c8f59ee5 2163 break;
f7079f67 2164 case RELAYD_BEGIN_DATA_PENDING:
58eb9381 2165 ret = relay_begin_data_pending(recv_hdr, conn);
f7079f67
DG
2166 break;
2167 case RELAYD_END_DATA_PENDING:
58eb9381 2168 ret = relay_end_data_pending(recv_hdr, conn);
f7079f67 2169 break;
1c20f0e2 2170 case RELAYD_SEND_INDEX:
58eb9381 2171 ret = relay_recv_index(recv_hdr, conn);
1c20f0e2 2172 break;
a4baae1b 2173 case RELAYD_STREAMS_SENT:
58eb9381 2174 ret = relay_streams_sent(recv_hdr, conn);
a4baae1b 2175 break;
93ec662e
JD
2176 case RELAYD_RESET_METADATA:
2177 ret = relay_reset_metadata(recv_hdr, conn);
2178 break;
b8aa1682
JD
2179 case RELAYD_UPDATE_SYNC_INFO:
2180 default:
2181 ERR("Received unknown command (%u)", be32toh(recv_hdr->cmd));
58eb9381 2182 relay_unknown_command(conn);
b8aa1682
JD
2183 ret = -1;
2184 goto end;
2185 }
2186
2187end:
2188 return ret;
2189}
2190
7d2f7452
DG
2191/*
2192 * Handle index for a data stream.
2193 *
7591bab1 2194 * Called with the stream lock held.
7d2f7452
DG
2195 *
2196 * Return 0 on success else a negative value.
2197 */
2198static int handle_index_data(struct relay_stream *stream, uint64_t net_seq_num,
2199 int rotate_index)
2200{
7591bab1
MD
2201 int ret = 0;
2202 uint64_t data_offset;
2203 struct relay_index *index;
7d2f7452 2204
7d2f7452
DG
2205 /* Get data offset because we are about to update the index. */
2206 data_offset = htobe64(stream->tracefile_size_current);
2207
65d66b19
MD
2208 DBG("handle_index_data: stream %" PRIu64 " net_seq_num %" PRIu64 " data offset %" PRIu64,
2209 stream->stream_handle, net_seq_num, stream->tracefile_size_current);
7591bab1 2210
7d2f7452 2211 /*
7591bab1
MD
2212 * Lookup for an existing index for that stream id/sequence
2213 * number. If it exists, the control thread has already received the
2214 * data for it, thus we need to write it to disk.
7d2f7452 2215 */
7591bab1 2216 index = relay_index_get_by_id_or_create(stream, net_seq_num);
7d2f7452 2217 if (!index) {
7591bab1
MD
2218 ret = -1;
2219 goto end;
7d2f7452
DG
2220 }
2221
f8f3885c
MD
2222 if (rotate_index || !stream->index_file) {
2223 uint32_t major, minor;
7591bab1 2224
f8f3885c
MD
2225 /* Put ref on previous index_file. */
2226 if (stream->index_file) {
2227 lttng_index_file_put(stream->index_file);
2228 stream->index_file = NULL;
7d2f7452 2229 }
f8f3885c
MD
2230 major = stream->trace->session->major;
2231 minor = stream->trace->session->minor;
2232 stream->index_file = lttng_index_file_create(stream->path_name,
2233 stream->channel_name,
7591bab1 2234 -1, -1, stream->tracefile_size,
f8f3885c
MD
2235 tracefile_array_get_file_index_head(stream->tfa),
2236 lttng_to_index_major(major, minor),
2237 lttng_to_index_minor(major, minor));
2238 if (!stream->index_file) {
7591bab1
MD
2239 ret = -1;
2240 /* Put self-ref for this index due to error. */
2241 relay_index_put(index);
f8f3885c 2242 index = NULL;
7591bab1 2243 goto end;
7d2f7452 2244 }
7d2f7452
DG
2245 }
2246
f8f3885c 2247 if (relay_index_set_file(index, stream->index_file, data_offset)) {
7591bab1
MD
2248 ret = -1;
2249 /* Put self-ref for this index due to error. */
2250 relay_index_put(index);
f8f3885c 2251 index = NULL;
7591bab1 2252 goto end;
7d2f7452
DG
2253 }
2254
7591bab1
MD
2255 ret = relay_index_try_flush(index);
2256 if (ret == 0) {
a44ca2ca
MD
2257 tracefile_array_commit_seq(stream->tfa);
2258 stream->index_received_seqcount++;
7591bab1
MD
2259 } else if (ret > 0) {
2260 /* No flush. */
2261 ret = 0;
2262 } else {
a86c0657
JR
2263 /*
2264 * ret < 0
2265 *
2266 * relay_index_try_flush is responsible for the self-reference
2267 * put of the index object on error.
2268 */
2269 ERR("relay_index_try_flush error %d", ret);
7591bab1
MD
2270 ret = -1;
2271 }
2272end:
7d2f7452
DG
2273 return ret;
2274}
2275
b8aa1682
JD
2276/*
2277 * relay_process_data: Process the data received on the data socket
2278 */
7591bab1 2279static int relay_process_data(struct relay_connection *conn)
b8aa1682 2280{
7d2f7452 2281 int ret = 0, rotate_index = 0;
6cd525e8 2282 ssize_t size_ret;
b8aa1682
JD
2283 struct relay_stream *stream;
2284 struct lttcomm_relayd_data_hdr data_hdr;
7d2f7452 2285 uint64_t stream_id;
173af62f 2286 uint64_t net_seq_num;
b8aa1682 2287 uint32_t data_size;
2a174661 2288 struct relay_session *session;
bda7c7b9 2289 bool new_stream = false, close_requested = false;
0848dba7
MD
2290 size_t chunk_size = RECV_DATA_BUFFER_SIZE;
2291 size_t recv_off = 0;
2292 char data_buffer[chunk_size];
b8aa1682 2293
58eb9381 2294 ret = conn->sock->ops->recvmsg(conn->sock, &data_hdr,
7c5aef62 2295 sizeof(struct lttcomm_relayd_data_hdr), 0);
b8aa1682 2296 if (ret <= 0) {
a6cd2b97
DG
2297 if (ret == 0) {
2298 /* Orderly shutdown. Not necessary to print an error. */
58eb9381 2299 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
a6cd2b97 2300 } else {
58eb9381 2301 ERR("Unable to receive data header on sock %d", conn->sock->fd);
a6cd2b97 2302 }
b8aa1682
JD
2303 ret = -1;
2304 goto end;
2305 }
2306
2307 stream_id = be64toh(data_hdr.stream_id);
7591bab1 2308 stream = stream_get_by_id(stream_id);
b8aa1682 2309 if (!stream) {
65d66b19 2310 ERR("relay_process_data: Cannot find stream %" PRIu64, stream_id);
b8aa1682 2311 ret = -1;
7591bab1 2312 goto end;
b8aa1682 2313 }
7591bab1 2314 session = stream->trace->session;
b8aa1682 2315 data_size = be32toh(data_hdr.data_size);
b8aa1682 2316
173af62f
DG
2317 net_seq_num = be64toh(data_hdr.net_seq_num);
2318
77c7c900 2319 DBG3("Receiving data of size %u for stream id %" PRIu64 " seqnum %" PRIu64,
173af62f 2320 data_size, stream_id, net_seq_num);
b8aa1682 2321
7591bab1
MD
2322 pthread_mutex_lock(&stream->lock);
2323
1c20f0e2 2324 /* Check if a rotation is needed. */
0f907de1
JD
2325 if (stream->tracefile_size > 0 &&
2326 (stream->tracefile_size_current + data_size) >
2327 stream->tracefile_size) {
a44ca2ca
MD
2328 uint64_t old_id, new_id;
2329
2330 old_id = tracefile_array_get_file_index_head(stream->tfa);
2331 tracefile_array_file_rotate(stream->tfa);
2332
2333 /* new_id is updated by utils_rotate_stream_file. */
2334 new_id = old_id;
6b6b9a5a 2335
7591bab1
MD
2336 ret = utils_rotate_stream_file(stream->path_name,
2337 stream->channel_name, stream->tracefile_size,
2338 stream->tracefile_count, -1,
2339 -1, stream->stream_fd->fd,
a44ca2ca 2340 &new_id, &stream->stream_fd->fd);
0f907de1 2341 if (ret < 0) {
1c20f0e2 2342 ERR("Rotating stream output file");
7591bab1
MD
2343 goto end_stream_unlock;
2344 }
7591bab1
MD
2345 /*
2346 * Reset current size because we just performed a stream
2347 * rotation.
2348 */
a6976990 2349 stream->tracefile_size_current = 0;
1c20f0e2
JD
2350 rotate_index = 1;
2351 }
2352
1c20f0e2 2353 /*
7591bab1
MD
2354 * Index are handled in protocol version 2.4 and above. Also,
2355 * snapshot and index are NOT supported.
1c20f0e2 2356 */
2a174661 2357 if (session->minor >= 4 && !session->snapshot) {
7d2f7452 2358 ret = handle_index_data(stream, net_seq_num, rotate_index);
1c20f0e2 2359 if (ret < 0) {
65d66b19
MD
2360 ERR("handle_index_data: fail stream %" PRIu64 " net_seq_num %" PRIu64 " ret %d",
2361 stream->stream_handle, net_seq_num, ret);
7591bab1 2362 goto end_stream_unlock;
1c20f0e2 2363 }
1c20f0e2
JD
2364 }
2365
0848dba7
MD
2366 for (recv_off = 0; recv_off < data_size; recv_off += chunk_size) {
2367 size_t recv_size = min(data_size - recv_off, chunk_size);
1d4dfdef 2368
0848dba7
MD
2369 ret = conn->sock->ops->recvmsg(conn->sock, data_buffer, recv_size, 0);
2370 if (ret <= 0) {
2371 if (ret == 0) {
2372 /* Orderly shutdown. Not necessary to print an error. */
2373 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
2374 } else {
2375 ERR("Socket %d error %d", conn->sock->fd, ret);
2376 }
2377 ret = -1;
2378 goto end_stream_unlock;
2379 }
2380
2381 /* Write data to stream output fd. */
2382 size_ret = lttng_write(stream->stream_fd->fd, data_buffer,
2383 recv_size);
2384 if (size_ret < recv_size) {
2385 ERR("Relay error writing data to file");
2386 ret = -1;
2387 goto end_stream_unlock;
2388 }
2389
2390 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64,
2391 size_ret, stream->stream_handle);
2392 }
5ab7344e 2393
7591bab1
MD
2394 ret = write_padding_to_file(stream->stream_fd->fd,
2395 be32toh(data_hdr.padding_size));
1d4dfdef 2396 if (ret < 0) {
65d66b19
MD
2397 ERR("write_padding_to_file: fail stream %" PRIu64 " net_seq_num %" PRIu64 " ret %d",
2398 stream->stream_handle, net_seq_num, ret);
7591bab1 2399 goto end_stream_unlock;
1d4dfdef 2400 }
7591bab1
MD
2401 stream->tracefile_size_current +=
2402 data_size + be32toh(data_hdr.padding_size);
c0bae11d
MD
2403 if (stream->prev_seq == -1ULL) {
2404 new_stream = true;
2405 }
2406
173af62f
DG
2407 stream->prev_seq = net_seq_num;
2408
7591bab1 2409end_stream_unlock:
bda7c7b9 2410 close_requested = stream->close_requested;
7591bab1 2411 pthread_mutex_unlock(&stream->lock);
bda7c7b9
JG
2412 if (close_requested) {
2413 try_stream_close(stream);
2414 }
2415
c0bae11d
MD
2416 if (new_stream) {
2417 pthread_mutex_lock(&session->lock);
2418 uatomic_set(&session->new_streams, 1);
2419 pthread_mutex_unlock(&session->lock);
2420 }
7591bab1 2421 stream_put(stream);
b8aa1682
JD
2422end:
2423 return ret;
2424}
2425
7591bab1 2426static void cleanup_connection_pollfd(struct lttng_poll_event *events, int pollfd)
b8aa1682
JD
2427{
2428 int ret;
2429
58eb9381 2430 (void) lttng_poll_del(events, pollfd);
b8aa1682
JD
2431
2432 ret = close(pollfd);
2433 if (ret < 0) {
2434 ERR("Closing pollfd %d", pollfd);
2435 }
2436}
2437
7591bab1
MD
2438static void relay_thread_close_connection(struct lttng_poll_event *events,
2439 int pollfd, struct relay_connection *conn)
9d1bbf21 2440{
7591bab1 2441 const char *type_str;
2a174661 2442
7591bab1
MD
2443 switch (conn->type) {
2444 case RELAY_DATA:
2445 type_str = "Data";
2446 break;
2447 case RELAY_CONTROL:
2448 type_str = "Control";
2449 break;
2450 case RELAY_VIEWER_COMMAND:
2451 type_str = "Viewer Command";
2452 break;
2453 case RELAY_VIEWER_NOTIFICATION:
2454 type_str = "Viewer Notification";
2455 break;
2456 default:
2457 type_str = "Unknown";
9d1bbf21 2458 }
7591bab1
MD
2459 cleanup_connection_pollfd(events, pollfd);
2460 connection_put(conn);
2461 DBG("%s connection closed with %d", type_str, pollfd);
b8aa1682
JD
2462}
2463
2464/*
2465 * This thread does the actual work
2466 */
7591bab1 2467static void *relay_thread_worker(void *data)
b8aa1682 2468{
beaad64c
DG
2469 int ret, err = -1, last_seen_data_fd = -1;
2470 uint32_t nb_fd;
b8aa1682
JD
2471 struct lttng_poll_event events;
2472 struct lttng_ht *relay_connections_ht;
b8aa1682 2473 struct lttng_ht_iter iter;
b8aa1682 2474 struct lttcomm_relayd_hdr recv_hdr;
90e7d72f 2475 struct relay_connection *destroy_conn = NULL;
b8aa1682
JD
2476
2477 DBG("[thread] Relay worker started");
2478
9d1bbf21
MD
2479 rcu_register_thread();
2480
55706a7d
MD
2481 health_register(health_relayd, HEALTH_RELAYD_TYPE_WORKER);
2482
9b5e0863
MD
2483 if (testpoint(relayd_thread_worker)) {
2484 goto error_testpoint;
2485 }
2486
f385ae0a
MD
2487 health_code_update();
2488
b8aa1682
JD
2489 /* table of connections indexed on socket */
2490 relay_connections_ht = lttng_ht_new(0, LTTNG_HT_TYPE_ULONG);
095a4ae5
MD
2491 if (!relay_connections_ht) {
2492 goto relay_connections_ht_error;
2493 }
b8aa1682 2494
b8aa1682
JD
2495 ret = create_thread_poll_set(&events, 2);
2496 if (ret < 0) {
2497 goto error_poll_create;
2498 }
2499
58eb9381 2500 ret = lttng_poll_add(&events, relay_conn_pipe[0], LPOLLIN | LPOLLRDHUP);
b8aa1682
JD
2501 if (ret < 0) {
2502 goto error;
2503 }
2504
beaad64c 2505restart:
b8aa1682 2506 while (1) {
beaad64c
DG
2507 int idx = -1, i, seen_control = 0, last_notdel_data_fd = -1;
2508
f385ae0a
MD
2509 health_code_update();
2510
b8aa1682 2511 /* Infinite blocking call, waiting for transmission */
87c1611d 2512 DBG3("Relayd worker thread polling...");
f385ae0a 2513 health_poll_entry();
b8aa1682 2514 ret = lttng_poll_wait(&events, -1);
f385ae0a 2515 health_poll_exit();
b8aa1682
JD
2516 if (ret < 0) {
2517 /*
2518 * Restart interrupted system call.
2519 */
2520 if (errno == EINTR) {
2521 goto restart;
2522 }
2523 goto error;
2524 }
2525
0d9c5d77
DG
2526 nb_fd = ret;
2527
beaad64c 2528 /*
7591bab1
MD
2529 * Process control. The control connection is
2530 * prioritized so we don't starve it with high
2531 * throughput tracing data on the data connection.
beaad64c 2532 */
b8aa1682
JD
2533 for (i = 0; i < nb_fd; i++) {
2534 /* Fetch once the poll data */
beaad64c
DG
2535 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
2536 int pollfd = LTTNG_POLL_GETFD(&events, i);
b8aa1682 2537
f385ae0a
MD
2538 health_code_update();
2539
fd20dac9 2540 if (!revents) {
7591bab1
MD
2541 /*
2542 * No activity for this FD (poll
2543 * implementation).
2544 */
fd20dac9
MD
2545 continue;
2546 }
2547
b8aa1682
JD
2548 /* Thread quit pipe has been closed. Killing thread. */
2549 ret = check_thread_quit_pipe(pollfd, revents);
2550 if (ret) {
095a4ae5
MD
2551 err = 0;
2552 goto exit;
b8aa1682
JD
2553 }
2554
58eb9381
DG
2555 /* Inspect the relay conn pipe for new connection */
2556 if (pollfd == relay_conn_pipe[0]) {
03e43155 2557 if (revents & LPOLLIN) {
90e7d72f
JG
2558 struct relay_connection *conn;
2559
58eb9381 2560 ret = lttng_read(relay_conn_pipe[0], &conn, sizeof(conn));
b8aa1682
JD
2561 if (ret < 0) {
2562 goto error;
2563 }
58eb9381
DG
2564 lttng_poll_add(&events, conn->sock->fd,
2565 LPOLLIN | LPOLLRDHUP);
7591bab1 2566 connection_ht_add(relay_connections_ht, conn);
58eb9381 2567 DBG("Connection socket %d added", conn->sock->fd);
03e43155
MD
2568 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2569 ERR("Relay connection pipe error");
2570 goto error;
2571 } else {
2572 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
2573 goto error;
b8aa1682 2574 }
58eb9381 2575 } else {
90e7d72f
JG
2576 struct relay_connection *ctrl_conn;
2577
7591bab1 2578 ctrl_conn = connection_get_by_sock(relay_connections_ht, pollfd);
58eb9381 2579 /* If not found, there is a synchronization issue. */
90e7d72f 2580 assert(ctrl_conn);
58eb9381 2581
03e43155
MD
2582 if (ctrl_conn->type == RELAY_DATA) {
2583 if (revents & LPOLLIN) {
beaad64c
DG
2584 /*
2585 * Flag the last seen data fd not deleted. It will be
2586 * used as the last seen fd if any fd gets deleted in
2587 * this first loop.
2588 */
2589 last_notdel_data_fd = pollfd;
2590 }
03e43155
MD
2591 goto put_ctrl_connection;
2592 }
2593 assert(ctrl_conn->type == RELAY_CONTROL);
2594
2595 if (revents & LPOLLIN) {
2596 ret = ctrl_conn->sock->ops->recvmsg(ctrl_conn->sock,
2597 &recv_hdr, sizeof(recv_hdr), 0);
2598 if (ret <= 0) {
2599 /* Connection closed */
2600 relay_thread_close_connection(&events, pollfd,
2601 ctrl_conn);
2602 } else {
2603 ret = relay_process_control(&recv_hdr, ctrl_conn);
2604 if (ret < 0) {
2605 /* Clear the session on error. */
2606 relay_thread_close_connection(&events,
2607 pollfd, ctrl_conn);
2608 }
2609 seen_control = 1;
2610 }
2611 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2612 relay_thread_close_connection(&events,
2613 pollfd, ctrl_conn);
2614 if (last_seen_data_fd == pollfd) {
2615 last_seen_data_fd = last_notdel_data_fd;
2616 }
58eb9381 2617 } else {
03e43155
MD
2618 ERR("Unexpected poll events %u for control sock %d",
2619 revents, pollfd);
2620 connection_put(ctrl_conn);
2621 goto error;
beaad64c 2622 }
03e43155 2623 put_ctrl_connection:
7591bab1 2624 connection_put(ctrl_conn);
beaad64c
DG
2625 }
2626 }
2627
2628 /*
2629 * The last loop handled a control request, go back to poll to make
2630 * sure we prioritise the control socket.
2631 */
2632 if (seen_control) {
2633 continue;
2634 }
2635
2636 if (last_seen_data_fd >= 0) {
2637 for (i = 0; i < nb_fd; i++) {
2638 int pollfd = LTTNG_POLL_GETFD(&events, i);
f385ae0a
MD
2639
2640 health_code_update();
2641
beaad64c
DG
2642 if (last_seen_data_fd == pollfd) {
2643 idx = i;
2644 break;
2645 }
2646 }
2647 }
2648
2649 /* Process data connection. */
2650 for (i = idx + 1; i < nb_fd; i++) {
2651 /* Fetch the poll data. */
2652 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
2653 int pollfd = LTTNG_POLL_GETFD(&events, i);
90e7d72f 2654 struct relay_connection *data_conn;
beaad64c 2655
f385ae0a
MD
2656 health_code_update();
2657
fd20dac9
MD
2658 if (!revents) {
2659 /* No activity for this FD (poll implementation). */
2660 continue;
2661 }
2662
beaad64c 2663 /* Skip the command pipe. It's handled in the first loop. */
58eb9381 2664 if (pollfd == relay_conn_pipe[0]) {
beaad64c
DG
2665 continue;
2666 }
2667
7591bab1 2668 data_conn = connection_get_by_sock(relay_connections_ht, pollfd);
90e7d72f 2669 if (!data_conn) {
fd20dac9 2670 /* Skip it. Might be removed before. */
fd20dac9
MD
2671 continue;
2672 }
03e43155
MD
2673 if (data_conn->type == RELAY_CONTROL) {
2674 goto put_data_connection;
2675 }
2676 assert(data_conn->type == RELAY_DATA);
fd20dac9
MD
2677
2678 if (revents & LPOLLIN) {
90e7d72f 2679 ret = relay_process_data(data_conn);
fd20dac9
MD
2680 /* Connection closed */
2681 if (ret < 0) {
7591bab1 2682 relay_thread_close_connection(&events, pollfd,
03e43155 2683 data_conn);
fd20dac9
MD
2684 /*
2685 * Every goto restart call sets the last seen fd where
2686 * here we don't really care since we gracefully
2687 * continue the loop after the connection is deleted.
2688 */
2689 } else {
2690 /* Keep last seen port. */
2691 last_seen_data_fd = pollfd;
7591bab1 2692 connection_put(data_conn);
fd20dac9 2693 goto restart;
b8aa1682 2694 }
03e43155
MD
2695 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2696 relay_thread_close_connection(&events, pollfd,
2697 data_conn);
2698 } else {
2699 ERR("Unknown poll events %u for data sock %d",
2700 revents, pollfd);
b8aa1682 2701 }
03e43155 2702 put_data_connection:
7591bab1 2703 connection_put(data_conn);
b8aa1682 2704 }
beaad64c 2705 last_seen_data_fd = -1;
b8aa1682
JD
2706 }
2707
f385ae0a
MD
2708 /* Normal exit, no error */
2709 ret = 0;
2710
095a4ae5 2711exit:
b8aa1682 2712error:
58eb9381 2713 /* Cleanup reamaining connection object. */
9d1bbf21 2714 rcu_read_lock();
90e7d72f
JG
2715 cds_lfht_for_each_entry(relay_connections_ht->ht, &iter.iter,
2716 destroy_conn,
58eb9381 2717 sock_n.node) {
f385ae0a 2718 health_code_update();
98ba050e
JR
2719
2720 if (session_abort(destroy_conn->session)) {
2721 assert(0);
2722 }
2723
7591bab1
MD
2724 /*
2725 * No need to grab another ref, because we own
2726 * destroy_conn.
2727 */
2728 relay_thread_close_connection(&events, destroy_conn->sock->fd,
2729 destroy_conn);
b8aa1682 2730 }
94d49140 2731 rcu_read_unlock();
7591bab1
MD
2732
2733 lttng_poll_clean(&events);
7d2f7452 2734error_poll_create:
b8aa1682 2735 lttng_ht_destroy(relay_connections_ht);
095a4ae5 2736relay_connections_ht_error:
58eb9381
DG
2737 /* Close relay conn pipes */
2738 utils_close_pipe(relay_conn_pipe);
095a4ae5
MD
2739 if (err) {
2740 DBG("Thread exited with error");
2741 }
b8aa1682 2742 DBG("Worker thread cleanup complete");
9b5e0863 2743error_testpoint:
f385ae0a
MD
2744 if (err) {
2745 health_error();
2746 ERR("Health error occurred in %s", __func__);
2747 }
2748 health_unregister(health_relayd);
9d1bbf21 2749 rcu_unregister_thread();
b4aacfdc 2750 lttng_relay_stop_threads();
b8aa1682
JD
2751 return NULL;
2752}
2753
2754/*
2755 * Create the relay command pipe to wake thread_manage_apps.
2756 * Closed in cleanup().
2757 */
58eb9381 2758static int create_relay_conn_pipe(void)
b8aa1682 2759{
a02de639 2760 int ret;
b8aa1682 2761
58eb9381 2762 ret = utils_create_pipe_cloexec(relay_conn_pipe);
b8aa1682 2763
b8aa1682
JD
2764 return ret;
2765}
2766
2767/*
2768 * main
2769 */
2770int main(int argc, char **argv)
2771{
178a0557 2772 int ret = 0, retval = 0;
b8aa1682
JD
2773 void *status;
2774
b8aa1682
JD
2775 /* Parse arguments */
2776 progname = argv[0];
178a0557
MD
2777 if (set_options(argc, argv)) {
2778 retval = -1;
2779 goto exit_options;
b8aa1682
JD
2780 }
2781
178a0557
MD
2782 if (set_signal_handler()) {
2783 retval = -1;
2784 goto exit_options;
b8aa1682
JD
2785 }
2786
4d513a50
DG
2787 /* Try to create directory if -o, --output is specified. */
2788 if (opt_output_path) {
994fa64f
DG
2789 if (*opt_output_path != '/') {
2790 ERR("Please specify an absolute path for -o, --output PATH");
178a0557
MD
2791 retval = -1;
2792 goto exit_options;
994fa64f
DG
2793 }
2794
d77dded2
JG
2795 ret = utils_mkdir_recursive(opt_output_path, S_IRWXU | S_IRWXG,
2796 -1, -1);
4d513a50
DG
2797 if (ret < 0) {
2798 ERR("Unable to create %s", opt_output_path);
178a0557
MD
2799 retval = -1;
2800 goto exit_options;
4d513a50
DG
2801 }
2802 }
2803
b8aa1682 2804 /* Daemonize */
b5218ffb 2805 if (opt_daemon || opt_background) {
3fd27398
MD
2806 int i;
2807
2808 ret = lttng_daemonize(&child_ppid, &recv_child_signal,
2809 !opt_background);
b8aa1682 2810 if (ret < 0) {
178a0557
MD
2811 retval = -1;
2812 goto exit_options;
b8aa1682 2813 }
3fd27398
MD
2814
2815 /*
2816 * We are in the child. Make sure all other file
2817 * descriptors are closed, in case we are called with
2818 * more opened file descriptors than the standard ones.
2819 */
2820 for (i = 3; i < sysconf(_SC_OPEN_MAX); i++) {
2821 (void) close(i);
2822 }
2823 }
2824
178a0557
MD
2825 /* Initialize thread health monitoring */
2826 health_relayd = health_app_create(NR_HEALTH_RELAYD_TYPES);
2827 if (!health_relayd) {
2828 PERROR("health_app_create error");
2829 retval = -1;
2830 goto exit_health_app_create;
2831 }
2832
3fd27398 2833 /* Create thread quit pipe */
178a0557
MD
2834 if (init_thread_quit_pipe()) {
2835 retval = -1;
2836 goto exit_init_data;
b8aa1682
JD
2837 }
2838
b8aa1682 2839 /* Setup the thread apps communication pipe. */
178a0557
MD
2840 if (create_relay_conn_pipe()) {
2841 retval = -1;
2842 goto exit_init_data;
b8aa1682
JD
2843 }
2844
2845 /* Init relay command queue. */
8bdee6e2 2846 cds_wfcq_init(&relay_conn_queue.head, &relay_conn_queue.tail);
b8aa1682 2847
554831e7
MD
2848 /* Initialize communication library */
2849 lttcomm_init();
87e45c13 2850 lttcomm_inet_init();
554831e7 2851
d3e2ba59 2852 /* tables of sessions indexed by session ID */
7591bab1
MD
2853 sessions_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
2854 if (!sessions_ht) {
178a0557
MD
2855 retval = -1;
2856 goto exit_init_data;
d3e2ba59
JD
2857 }
2858
2859 /* tables of streams indexed by stream ID */
2a174661 2860 relay_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
d3e2ba59 2861 if (!relay_streams_ht) {
178a0557
MD
2862 retval = -1;
2863 goto exit_init_data;
d3e2ba59
JD
2864 }
2865
2866 /* tables of streams indexed by stream ID */
92c6ca54
DG
2867 viewer_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
2868 if (!viewer_streams_ht) {
178a0557
MD
2869 retval = -1;
2870 goto exit_init_data;
55706a7d
MD
2871 }
2872
65931c8b 2873 ret = utils_create_pipe(health_quit_pipe);
178a0557
MD
2874 if (ret) {
2875 retval = -1;
2876 goto exit_health_quit_pipe;
65931c8b
MD
2877 }
2878
2879 /* Create thread to manage the client socket */
1a1a34b4 2880 ret = pthread_create(&health_thread, default_pthread_attr(),
65931c8b 2881 thread_manage_health, (void *) NULL);
178a0557
MD
2882 if (ret) {
2883 errno = ret;
65931c8b 2884 PERROR("pthread_create health");
178a0557
MD
2885 retval = -1;
2886 goto exit_health_thread;
65931c8b
MD
2887 }
2888
b8aa1682 2889 /* Setup the dispatcher thread */
1a1a34b4 2890 ret = pthread_create(&dispatcher_thread, default_pthread_attr(),
b8aa1682 2891 relay_thread_dispatcher, (void *) NULL);
178a0557
MD
2892 if (ret) {
2893 errno = ret;
b8aa1682 2894 PERROR("pthread_create dispatcher");
178a0557
MD
2895 retval = -1;
2896 goto exit_dispatcher_thread;
b8aa1682
JD
2897 }
2898
2899 /* Setup the worker thread */
1a1a34b4 2900 ret = pthread_create(&worker_thread, default_pthread_attr(),
7591bab1 2901 relay_thread_worker, NULL);
178a0557
MD
2902 if (ret) {
2903 errno = ret;
b8aa1682 2904 PERROR("pthread_create worker");
178a0557
MD
2905 retval = -1;
2906 goto exit_worker_thread;
b8aa1682
JD
2907 }
2908
2909 /* Setup the listener thread */
1a1a34b4 2910 ret = pthread_create(&listener_thread, default_pthread_attr(),
b8aa1682 2911 relay_thread_listener, (void *) NULL);
178a0557
MD
2912 if (ret) {
2913 errno = ret;
b8aa1682 2914 PERROR("pthread_create listener");
178a0557
MD
2915 retval = -1;
2916 goto exit_listener_thread;
b8aa1682
JD
2917 }
2918
7591bab1 2919 ret = relayd_live_create(live_uri);
178a0557 2920 if (ret) {
d3e2ba59 2921 ERR("Starting live viewer threads");
178a0557 2922 retval = -1;
50138f51 2923 goto exit_live;
d3e2ba59
JD
2924 }
2925
178a0557
MD
2926 /*
2927 * This is where we start awaiting program completion (e.g. through
2928 * signal that asks threads to teardown).
2929 */
2930
2931 ret = relayd_live_join();
2932 if (ret) {
2933 retval = -1;
2934 }
50138f51 2935exit_live:
178a0557 2936
b8aa1682 2937 ret = pthread_join(listener_thread, &status);
178a0557
MD
2938 if (ret) {
2939 errno = ret;
2940 PERROR("pthread_join listener_thread");
2941 retval = -1;
b8aa1682
JD
2942 }
2943
178a0557 2944exit_listener_thread:
b8aa1682 2945 ret = pthread_join(worker_thread, &status);
178a0557
MD
2946 if (ret) {
2947 errno = ret;
2948 PERROR("pthread_join worker_thread");
2949 retval = -1;
b8aa1682
JD
2950 }
2951
178a0557 2952exit_worker_thread:
b8aa1682 2953 ret = pthread_join(dispatcher_thread, &status);
178a0557
MD
2954 if (ret) {
2955 errno = ret;
2956 PERROR("pthread_join dispatcher_thread");
2957 retval = -1;
b8aa1682 2958 }
178a0557 2959exit_dispatcher_thread:
42415026 2960
65931c8b 2961 ret = pthread_join(health_thread, &status);
178a0557
MD
2962 if (ret) {
2963 errno = ret;
2964 PERROR("pthread_join health_thread");
2965 retval = -1;
65931c8b 2966 }
178a0557 2967exit_health_thread:
65931c8b 2968
65931c8b 2969 utils_close_pipe(health_quit_pipe);
178a0557 2970exit_health_quit_pipe:
65931c8b 2971
178a0557 2972exit_init_data:
55706a7d 2973 health_app_destroy(health_relayd);
55706a7d 2974exit_health_app_create:
178a0557 2975exit_options:
4d62fbf8
MD
2976 /*
2977 * Wait for all pending call_rcu work to complete before tearing
2978 * down data structures. call_rcu worker may be trying to
2979 * perform lookups in those structures.
2980 */
2981 rcu_barrier();
7591bab1
MD
2982 relayd_cleanup();
2983
2984 /* Ensure all prior call_rcu are done. */
2985 rcu_barrier();
d3e2ba59 2986
178a0557 2987 if (!retval) {
b8aa1682 2988 exit(EXIT_SUCCESS);
178a0557
MD
2989 } else {
2990 exit(EXIT_FAILURE);
b8aa1682 2991 }
b8aa1682 2992}
This page took 0.235175 seconds and 5 git commands to generate.