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