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