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