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