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