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