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