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