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