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