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