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