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