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