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