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