relayd: Implement custom EfficiOS session clear
[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
1466 DBG("Clear session received");
1467
1468 if (!session || !conn->version_check_done) {
1469 ERR("Trying to clear session before version check");
1470 ret = -1;
1471 goto end_no_session;
1472 }
1473
1474 if (!opt_allow_clear) {
1475 ERR("Trying to clear session, but clear is disallowed.");
1476 ret = -1;
1477 goto end_no_session;
1478 }
1479 ret = session_clear(session);
1480
1481 memset(&reply, 0, sizeof(reply));
1482 if (ret < 0) {
1483 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1484 } else {
1485 reply.ret_code = htobe32(LTTNG_OK);
1486 }
1487 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1488 sizeof(struct lttcomm_relayd_generic_reply), 0);
1489 if (send_ret < (ssize_t) sizeof(reply)) {
1490 ERR("Failed to send \"clear session\" command reply (ret = %zd)",
1491 send_ret);
1492 ret = -1;
1493 }
1494
1495end_no_session:
1496 return ret;
1497}
1498
b8aa1682
JD
1499/*
1500 * relay_unknown_command: send -1 if received unknown command
1501 */
7591bab1 1502static void relay_unknown_command(struct relay_connection *conn)
b8aa1682
JD
1503{
1504 struct lttcomm_relayd_generic_reply reply;
1505 int ret;
1506
53efb85a 1507 memset(&reply, 0, sizeof(reply));
f73fabfd 1508 reply.ret_code = htobe32(LTTNG_ERR_UNK);
58eb9381 1509 ret = conn->sock->ops->sendmsg(conn->sock, &reply,
b8aa1682
JD
1510 sizeof(struct lttcomm_relayd_generic_reply), 0);
1511 if (ret < 0) {
1512 ERR("Relay sending unknown command");
1513 }
1514}
1515
1516/*
1517 * relay_start: send an acknowledgment to the client to tell if we are
1518 * ready to receive data. We are ready if a session is established.
1519 */
7591bab1 1520static int relay_start(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1521 struct relay_connection *conn)
b8aa1682 1522{
f73fabfd 1523 int ret = htobe32(LTTNG_OK);
b8aa1682 1524 struct lttcomm_relayd_generic_reply reply;
58eb9381 1525 struct relay_session *session = conn->session;
b8aa1682
JD
1526
1527 if (!session) {
1528 DBG("Trying to start the streaming without a session established");
f73fabfd 1529 ret = htobe32(LTTNG_ERR_UNK);
b8aa1682
JD
1530 }
1531
53efb85a 1532 memset(&reply, 0, sizeof(reply));
b8aa1682 1533 reply.ret_code = ret;
58eb9381 1534 ret = conn->sock->ops->sendmsg(conn->sock, &reply,
b8aa1682
JD
1535 sizeof(struct lttcomm_relayd_generic_reply), 0);
1536 if (ret < 0) {
1537 ERR("Relay sending start ack");
1538 }
1539
1540 return ret;
1541}
1542
1d4dfdef
DG
1543/*
1544 * Append padding to the file pointed by the file descriptor fd.
1545 */
1546static int write_padding_to_file(int fd, uint32_t size)
1547{
6cd525e8 1548 ssize_t ret = 0;
1d4dfdef
DG
1549 char *zeros;
1550
1551 if (size == 0) {
1552 goto end;
1553 }
1554
1555 zeros = zmalloc(size);
1556 if (zeros == NULL) {
1557 PERROR("zmalloc zeros for padding");
1558 ret = -1;
1559 goto end;
1560 }
1561
6cd525e8
MD
1562 ret = lttng_write(fd, zeros, size);
1563 if (ret < size) {
1d4dfdef
DG
1564 PERROR("write padding to file");
1565 }
1566
e986c7a1
DG
1567 free(zeros);
1568
1d4dfdef
DG
1569end:
1570 return ret;
1571}
1572
b8aa1682 1573/*
7591bab1 1574 * relay_recv_metadata: receive the metadata for the session.
b8aa1682 1575 */
7591bab1 1576static int relay_recv_metadata(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1577 struct relay_connection *conn)
b8aa1682 1578{
32d1569c 1579 int ret = 0;
6cd525e8 1580 ssize_t size_ret;
58eb9381 1581 struct relay_session *session = conn->session;
b8aa1682
JD
1582 struct lttcomm_relayd_metadata_payload *metadata_struct;
1583 struct relay_stream *metadata_stream;
1584 uint64_t data_size, payload_size;
1585
1586 if (!session) {
1587 ERR("Metadata sent before version check");
1588 ret = -1;
1589 goto end;
1590 }
1591
f6416125
MD
1592 data_size = payload_size = be64toh(recv_hdr->data_size);
1593 if (data_size < sizeof(struct lttcomm_relayd_metadata_payload)) {
1594 ERR("Incorrect data size");
1595 ret = -1;
1596 goto end;
1597 }
1598 payload_size -= sizeof(struct lttcomm_relayd_metadata_payload);
1599
b8aa1682 1600 if (data_buffer_size < data_size) {
d7b3776f 1601 /* In case the realloc fails, we can free the memory */
c617c0c6
MD
1602 char *tmp_data_ptr;
1603
1604 tmp_data_ptr = realloc(data_buffer, data_size);
1605 if (!tmp_data_ptr) {
b8aa1682 1606 ERR("Allocating data buffer");
c617c0c6 1607 free(data_buffer);
b8aa1682
JD
1608 ret = -1;
1609 goto end;
1610 }
c617c0c6 1611 data_buffer = tmp_data_ptr;
b8aa1682
JD
1612 data_buffer_size = data_size;
1613 }
1614 memset(data_buffer, 0, data_size);
77c7c900 1615 DBG2("Relay receiving metadata, waiting for %" PRIu64 " bytes", data_size);
32d1569c
JG
1616 size_ret = conn->sock->ops->recvmsg(conn->sock, data_buffer, data_size, 0);
1617 if (size_ret < 0 || size_ret != data_size) {
1618 if (size_ret == 0) {
a6cd2b97 1619 /* Orderly shutdown. Not necessary to print an error. */
58eb9381 1620 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
a6cd2b97
DG
1621 } else {
1622 ERR("Relay didn't receive the whole metadata");
1623 }
b8aa1682 1624 ret = -1;
b8aa1682
JD
1625 goto end;
1626 }
1627 metadata_struct = (struct lttcomm_relayd_metadata_payload *) data_buffer;
9d1bbf21 1628
7591bab1 1629 metadata_stream = stream_get_by_id(be64toh(metadata_struct->stream_id));
b8aa1682
JD
1630 if (!metadata_stream) {
1631 ret = -1;
7591bab1 1632 goto end;
b8aa1682
JD
1633 }
1634
7591bab1
MD
1635 pthread_mutex_lock(&metadata_stream->lock);
1636
1637 size_ret = lttng_write(metadata_stream->stream_fd->fd, metadata_struct->payload,
6cd525e8
MD
1638 payload_size);
1639 if (size_ret < payload_size) {
b8aa1682
JD
1640 ERR("Relay error writing metadata on file");
1641 ret = -1;
7591bab1 1642 goto end_put;
b8aa1682 1643 }
1d4dfdef 1644
32d1569c 1645 size_ret = write_padding_to_file(metadata_stream->stream_fd->fd,
1d4dfdef 1646 be32toh(metadata_struct->padding_size));
32d1569c 1647 if (size_ret < 0) {
7591bab1 1648 goto end_put;
1d4dfdef 1649 }
2a174661 1650
7591bab1 1651 metadata_stream->metadata_received +=
d3e2ba59 1652 payload_size + be32toh(metadata_struct->padding_size);
7591bab1
MD
1653 DBG2("Relay metadata written. Updated metadata_received %" PRIu64,
1654 metadata_stream->metadata_received);
1d4dfdef 1655
7591bab1
MD
1656end_put:
1657 pthread_mutex_unlock(&metadata_stream->lock);
1658 stream_put(metadata_stream);
b8aa1682
JD
1659end:
1660 return ret;
1661}
1662
1663/*
1664 * relay_send_version: send relayd version number
1665 */
7591bab1 1666static int relay_send_version(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1667 struct relay_connection *conn)
b8aa1682 1668{
7f51dcba 1669 int ret;
092b6259 1670 struct lttcomm_relayd_version reply, msg;
b28f7baa 1671 bool compatible = true;
b8aa1682 1672
58eb9381 1673 conn->version_check_done = 1;
b8aa1682 1674
092b6259 1675 /* Get version from the other side. */
58eb9381 1676 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
092b6259 1677 if (ret < 0 || ret != sizeof(msg)) {
a6cd2b97
DG
1678 if (ret == 0) {
1679 /* Orderly shutdown. Not necessary to print an error. */
58eb9381 1680 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
a6cd2b97
DG
1681 } else {
1682 ERR("Relay failed to receive the version values.");
1683 }
092b6259 1684 ret = -1;
092b6259
DG
1685 goto end;
1686 }
1687
53efb85a 1688 memset(&reply, 0, sizeof(reply));
d83a952c
MD
1689 reply.major = RELAYD_VERSION_COMM_MAJOR;
1690 reply.minor = RELAYD_VERSION_COMM_MINOR;
d4519fa3
JD
1691
1692 /* Major versions must be the same */
1693 if (reply.major != be32toh(msg.major)) {
6151a90f
JD
1694 DBG("Incompatible major versions (%u vs %u), deleting session",
1695 reply.major, be32toh(msg.major));
b28f7baa 1696 compatible = false;
d4519fa3
JD
1697 }
1698
58eb9381 1699 conn->major = reply.major;
0f907de1
JD
1700 /* We adapt to the lowest compatible version */
1701 if (reply.minor <= be32toh(msg.minor)) {
58eb9381 1702 conn->minor = reply.minor;
0f907de1 1703 } else {
58eb9381 1704 conn->minor = be32toh(msg.minor);
0f907de1
JD
1705 }
1706
6151a90f
JD
1707 reply.major = htobe32(reply.major);
1708 reply.minor = htobe32(reply.minor);
58eb9381 1709 ret = conn->sock->ops->sendmsg(conn->sock, &reply,
6151a90f
JD
1710 sizeof(struct lttcomm_relayd_version), 0);
1711 if (ret < 0) {
1712 ERR("Relay sending version");
1713 }
1714
b28f7baa
JD
1715 if (!compatible) {
1716 ret = -1;
1717 goto end;
1718 }
1719
58eb9381
DG
1720 DBG("Version check done using protocol %u.%u", conn->major,
1721 conn->minor);
b8aa1682
JD
1722
1723end:
1724 return ret;
1725}
1726
c8f59ee5 1727/*
6d805429 1728 * Check for data pending for a given stream id from the session daemon.
c8f59ee5 1729 */
7591bab1 1730static int relay_data_pending(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1731 struct relay_connection *conn)
c8f59ee5 1732{
58eb9381 1733 struct relay_session *session = conn->session;
6d805429 1734 struct lttcomm_relayd_data_pending msg;
c8f59ee5
DG
1735 struct lttcomm_relayd_generic_reply reply;
1736 struct relay_stream *stream;
1737 int ret;
c8f59ee5
DG
1738 uint64_t last_net_seq_num, stream_id;
1739
6d805429 1740 DBG("Data pending command received");
c8f59ee5 1741
58eb9381 1742 if (!session || conn->version_check_done == 0) {
c8f59ee5
DG
1743 ERR("Trying to check for data before version check");
1744 ret = -1;
1745 goto end_no_session;
1746 }
1747
58eb9381 1748 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
c8f59ee5 1749 if (ret < sizeof(msg)) {
a6cd2b97
DG
1750 if (ret == 0) {
1751 /* Orderly shutdown. Not necessary to print an error. */
58eb9381 1752 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
a6cd2b97
DG
1753 } else {
1754 ERR("Relay didn't receive valid data_pending struct size : %d",
1755 ret);
1756 }
c8f59ee5
DG
1757 ret = -1;
1758 goto end_no_session;
1759 }
1760
1761 stream_id = be64toh(msg.stream_id);
1762 last_net_seq_num = be64toh(msg.last_net_seq_num);
1763
7591bab1 1764 stream = stream_get_by_id(stream_id);
de91f48a 1765 if (stream == NULL) {
c8f59ee5 1766 ret = -1;
7591bab1 1767 goto end;
c8f59ee5
DG
1768 }
1769
7591bab1
MD
1770 pthread_mutex_lock(&stream->lock);
1771
6d805429 1772 DBG("Data pending for stream id %" PRIu64 " prev_seq %" PRIu64
c8f59ee5
DG
1773 " and last_seq %" PRIu64, stream_id, stream->prev_seq,
1774 last_net_seq_num);
1775
33832e64 1776 /* Avoid wrapping issue */
39df6d9f 1777 if (((int64_t) (stream->prev_seq - last_net_seq_num)) >= 0) {
6d805429 1778 /* Data has in fact been written and is NOT pending */
c8f59ee5 1779 ret = 0;
6d805429
DG
1780 } else {
1781 /* Data still being streamed thus pending */
1782 ret = 1;
c8f59ee5
DG
1783 }
1784
7591bab1
MD
1785 stream->data_pending_check_done = true;
1786 pthread_mutex_unlock(&stream->lock);
f7079f67 1787
7591bab1
MD
1788 stream_put(stream);
1789end:
c8f59ee5 1790
53efb85a 1791 memset(&reply, 0, sizeof(reply));
c8f59ee5 1792 reply.ret_code = htobe32(ret);
58eb9381 1793 ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
c8f59ee5 1794 if (ret < 0) {
6d805429 1795 ERR("Relay data pending ret code failed");
c8f59ee5
DG
1796 }
1797
1798end_no_session:
1799 return ret;
1800}
1801
1802/*
1803 * Wait for the control socket to reach a quiescent state.
1804 *
7591bab1
MD
1805 * Note that for now, when receiving this command from the session
1806 * daemon, this means that every subsequent commands or data received on
1807 * the control socket has been handled. So, this is why we simply return
1808 * OK here.
c8f59ee5 1809 */
7591bab1 1810static int relay_quiescent_control(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1811 struct relay_connection *conn)
c8f59ee5
DG
1812{
1813 int ret;
ad7051c0
DG
1814 uint64_t stream_id;
1815 struct relay_stream *stream;
ad7051c0 1816 struct lttcomm_relayd_quiescent_control msg;
c8f59ee5
DG
1817 struct lttcomm_relayd_generic_reply reply;
1818
1819 DBG("Checking quiescent state on control socket");
1820
58eb9381 1821 if (!conn->session || conn->version_check_done == 0) {
ad7051c0
DG
1822 ERR("Trying to check for data before version check");
1823 ret = -1;
1824 goto end_no_session;
1825 }
1826
58eb9381 1827 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
ad7051c0 1828 if (ret < sizeof(msg)) {
a6cd2b97
DG
1829 if (ret == 0) {
1830 /* Orderly shutdown. Not necessary to print an error. */
58eb9381 1831 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
a6cd2b97
DG
1832 } else {
1833 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1834 ret);
1835 }
ad7051c0
DG
1836 ret = -1;
1837 goto end_no_session;
1838 }
1839
1840 stream_id = be64toh(msg.stream_id);
7591bab1
MD
1841 stream = stream_get_by_id(stream_id);
1842 if (!stream) {
1843 goto reply;
1844 }
1845 pthread_mutex_lock(&stream->lock);
1846 stream->data_pending_check_done = true;
1847 pthread_mutex_unlock(&stream->lock);
1848 DBG("Relay quiescent control pending flag set to %" PRIu64, stream_id);
1849 stream_put(stream);
1850reply:
53efb85a 1851 memset(&reply, 0, sizeof(reply));
c8f59ee5 1852 reply.ret_code = htobe32(LTTNG_OK);
58eb9381 1853 ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
c8f59ee5 1854 if (ret < 0) {
6d805429 1855 ERR("Relay data quiescent control ret code failed");
c8f59ee5
DG
1856 }
1857
ad7051c0 1858end_no_session:
c8f59ee5
DG
1859 return ret;
1860}
1861
f7079f67 1862/*
7591bab1
MD
1863 * Initialize a data pending command. This means that a consumer is about
1864 * to ask for data pending for each stream it holds. Simply iterate over
1865 * all streams of a session and set the data_pending_check_done flag.
f7079f67
DG
1866 *
1867 * This command returns to the client a LTTNG_OK code.
1868 */
7591bab1 1869static int relay_begin_data_pending(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1870 struct relay_connection *conn)
f7079f67
DG
1871{
1872 int ret;
1873 struct lttng_ht_iter iter;
1874 struct lttcomm_relayd_begin_data_pending msg;
1875 struct lttcomm_relayd_generic_reply reply;
1876 struct relay_stream *stream;
1877 uint64_t session_id;
1878
1879 assert(recv_hdr);
58eb9381 1880 assert(conn);
f7079f67
DG
1881
1882 DBG("Init streams for data pending");
1883
58eb9381 1884 if (!conn->session || conn->version_check_done == 0) {
f7079f67
DG
1885 ERR("Trying to check for data before version check");
1886 ret = -1;
1887 goto end_no_session;
1888 }
1889
58eb9381 1890 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
f7079f67 1891 if (ret < sizeof(msg)) {
a6cd2b97
DG
1892 if (ret == 0) {
1893 /* Orderly shutdown. Not necessary to print an error. */
58eb9381 1894 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
a6cd2b97
DG
1895 } else {
1896 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1897 ret);
1898 }
f7079f67
DG
1899 ret = -1;
1900 goto end_no_session;
1901 }
1902
1903 session_id = be64toh(msg.session_id);
1904
1905 /*
7591bab1
MD
1906 * Iterate over all streams to set the begin data pending flag.
1907 * For now, the streams are indexed by stream handle so we have
1908 * to iterate over all streams to find the one associated with
1909 * the right session_id.
f7079f67
DG
1910 */
1911 rcu_read_lock();
d3e2ba59 1912 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2a174661 1913 node.node) {
7591bab1
MD
1914 if (!stream_get(stream)) {
1915 continue;
1916 }
1917 if (stream->trace->session->id == session_id) {
1918 pthread_mutex_lock(&stream->lock);
1919 stream->data_pending_check_done = false;
1920 pthread_mutex_unlock(&stream->lock);
f7079f67
DG
1921 DBG("Set begin data pending flag to stream %" PRIu64,
1922 stream->stream_handle);
1923 }
7591bab1 1924 stream_put(stream);
f7079f67
DG
1925 }
1926 rcu_read_unlock();
1927
53efb85a 1928 memset(&reply, 0, sizeof(reply));
f7079f67
DG
1929 /* All good, send back reply. */
1930 reply.ret_code = htobe32(LTTNG_OK);
1931
58eb9381 1932 ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
f7079f67
DG
1933 if (ret < 0) {
1934 ERR("Relay begin data pending send reply failed");
1935 }
1936
1937end_no_session:
1938 return ret;
1939}
1940
1941/*
7591bab1
MD
1942 * End data pending command. This will check, for a given session id, if
1943 * each stream associated with it has its data_pending_check_done flag
1944 * set. If not, this means that the client lost track of the stream but
1945 * the data is still being streamed on our side. In this case, we inform
1946 * the client that data is in flight.
f7079f67
DG
1947 *
1948 * Return to the client if there is data in flight or not with a ret_code.
1949 */
7591bab1 1950static int relay_end_data_pending(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 1951 struct relay_connection *conn)
f7079f67
DG
1952{
1953 int ret;
1954 struct lttng_ht_iter iter;
1955 struct lttcomm_relayd_end_data_pending msg;
1956 struct lttcomm_relayd_generic_reply reply;
1957 struct relay_stream *stream;
1958 uint64_t session_id;
1959 uint32_t is_data_inflight = 0;
1960
f7079f67
DG
1961 DBG("End data pending command");
1962
58eb9381 1963 if (!conn->session || conn->version_check_done == 0) {
f7079f67
DG
1964 ERR("Trying to check for data before version check");
1965 ret = -1;
1966 goto end_no_session;
1967 }
1968
58eb9381 1969 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
f7079f67 1970 if (ret < sizeof(msg)) {
a6cd2b97
DG
1971 if (ret == 0) {
1972 /* Orderly shutdown. Not necessary to print an error. */
58eb9381 1973 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
a6cd2b97
DG
1974 } else {
1975 ERR("Relay didn't receive valid end data_pending struct size: %d",
1976 ret);
1977 }
f7079f67
DG
1978 ret = -1;
1979 goto end_no_session;
1980 }
1981
1982 session_id = be64toh(msg.session_id);
1983
7591bab1
MD
1984 /*
1985 * Iterate over all streams to see if the begin data pending
1986 * flag is set.
1987 */
f7079f67 1988 rcu_read_lock();
d3e2ba59 1989 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2a174661 1990 node.node) {
7591bab1
MD
1991 if (!stream_get(stream)) {
1992 continue;
1993 }
1994 if (stream->trace->session->id != session_id) {
1995 stream_put(stream);
1996 continue;
1997 }
1998 pthread_mutex_lock(&stream->lock);
1999 if (!stream->data_pending_check_done) {
2000 if (!stream->closed || !(((int64_t) (stream->prev_seq - stream->last_net_seq_num)) >= 0)) {
2001 is_data_inflight = 1;
2002 DBG("Data is still in flight for stream %" PRIu64,
2003 stream->stream_handle);
2004 pthread_mutex_unlock(&stream->lock);
2005 stream_put(stream);
2006 break;
2007 }
f7079f67 2008 }
7591bab1
MD
2009 pthread_mutex_unlock(&stream->lock);
2010 stream_put(stream);
f7079f67
DG
2011 }
2012 rcu_read_unlock();
2013
53efb85a 2014 memset(&reply, 0, sizeof(reply));
f7079f67
DG
2015 /* All good, send back reply. */
2016 reply.ret_code = htobe32(is_data_inflight);
2017
58eb9381 2018 ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
f7079f67
DG
2019 if (ret < 0) {
2020 ERR("Relay end data pending send reply failed");
2021 }
2022
2023end_no_session:
2024 return ret;
2025}
2026
1c20f0e2
JD
2027/*
2028 * Receive an index for a specific stream.
2029 *
2030 * Return 0 on success else a negative value.
2031 */
7591bab1 2032static int relay_recv_index(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 2033 struct relay_connection *conn)
1c20f0e2 2034{
7591bab1 2035 int ret, send_ret;
58eb9381 2036 struct relay_session *session = conn->session;
1c20f0e2 2037 struct lttcomm_relayd_index index_info;
7591bab1 2038 struct relay_index *index;
1c20f0e2
JD
2039 struct lttcomm_relayd_generic_reply reply;
2040 struct relay_stream *stream;
2041 uint64_t net_seq_num;
f8f3885c 2042 size_t msg_len;
1c20f0e2 2043
58eb9381 2044 assert(conn);
1c20f0e2
JD
2045
2046 DBG("Relay receiving index");
2047
58eb9381 2048 if (!session || conn->version_check_done == 0) {
1c20f0e2
JD
2049 ERR("Trying to close a stream before version check");
2050 ret = -1;
2051 goto end_no_session;
2052 }
2053
f8f3885c
MD
2054 msg_len = lttcomm_relayd_index_len(
2055 lttng_to_index_major(conn->major, conn->minor),
2056 lttng_to_index_minor(conn->major, conn->minor));
58eb9381 2057 ret = conn->sock->ops->recvmsg(conn->sock, &index_info,
f8f3885c
MD
2058 msg_len, 0);
2059 if (ret < msg_len) {
1c20f0e2
JD
2060 if (ret == 0) {
2061 /* Orderly shutdown. Not necessary to print an error. */
58eb9381 2062 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1c20f0e2
JD
2063 } else {
2064 ERR("Relay didn't receive valid index struct size : %d", ret);
2065 }
2066 ret = -1;
2067 goto end_no_session;
2068 }
2069
2070 net_seq_num = be64toh(index_info.net_seq_num);
2071
7591bab1 2072 stream = stream_get_by_id(be64toh(index_info.relay_stream_id));
1c20f0e2 2073 if (!stream) {
7591bab1 2074 ERR("stream_get_by_id not found");
1c20f0e2 2075 ret = -1;
7591bab1 2076 goto end;
1c20f0e2 2077 }
7591bab1 2078 pthread_mutex_lock(&stream->lock);
1c20f0e2 2079
d3e2ba59
JD
2080 /* Live beacon handling */
2081 if (index_info.packet_size == 0) {
7591bab1
MD
2082 DBG("Received live beacon for stream %" PRIu64,
2083 stream->stream_handle);
d3e2ba59
JD
2084
2085 /*
7591bab1
MD
2086 * Only flag a stream inactive when it has already
2087 * received data and no indexes are in flight.
d3e2ba59 2088 */
a44ca2ca 2089 if (stream->index_received_seqcount > 0
7591bab1
MD
2090 && stream->indexes_in_flight == 0) {
2091 stream->beacon_ts_end =
2092 be64toh(index_info.timestamp_end);
d3e2ba59
JD
2093 }
2094 ret = 0;
7591bab1 2095 goto end_stream_put;
d3e2ba59 2096 } else {
82b4cfcc
MD
2097 DBG("Received index for stream %" PRIu64,
2098 stream->stream_handle);
d3e2ba59
JD
2099 stream->beacon_ts_end = -1ULL;
2100 }
2101
528f2ffa
JD
2102 if (stream->ctf_stream_id == -1ULL) {
2103 stream->ctf_stream_id = be64toh(index_info.stream_id);
2104 }
7591bab1
MD
2105 index = relay_index_get_by_id_or_create(stream, net_seq_num);
2106 if (!index) {
2107 ret = -1;
2108 ERR("relay_index_get_by_id_or_create index NULL");
2109 goto end_stream_put;
1c20f0e2 2110 }
234cd636 2111 if (set_index_control_data(index, &index_info, conn)) {
7591bab1
MD
2112 ERR("set_index_control_data error");
2113 relay_index_put(index);
2114 ret = -1;
2115 goto end_stream_put;
2116 }
2117 ret = relay_index_try_flush(index);
2118 if (ret == 0) {
82b4cfcc 2119 tracefile_array_commit_seq(stream->tfa, stream->index_received_seqcount);
a44ca2ca 2120 stream->index_received_seqcount++;
82b4cfcc
MD
2121 /* Clear index and data file(s) if reaching the clear position. */
2122 ret = try_stream_clear_index_data(stream);
2123 if (ret) {
2124 goto end_stream_put;
2125 }
7591bab1
MD
2126 } else if (ret > 0) {
2127 /* no flush. */
2128 ret = 0;
2129 } else {
a86c0657
JR
2130 /*
2131 * ret < 0
2132 *
2133 * relay_index_try_flush is responsible for the self-reference
2134 * put of the index object on error.
2135 */
7591bab1 2136 ERR("relay_index_try_flush error %d", ret);
7591bab1 2137 ret = -1;
1c20f0e2 2138 }
82b4cfcc 2139 stream->prev_index_seq = net_seq_num;
1c20f0e2 2140
7591bab1
MD
2141end_stream_put:
2142 pthread_mutex_unlock(&stream->lock);
2143 stream_put(stream);
2144
2145end:
1c20f0e2 2146
53efb85a 2147 memset(&reply, 0, sizeof(reply));
1c20f0e2
JD
2148 if (ret < 0) {
2149 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2150 } else {
2151 reply.ret_code = htobe32(LTTNG_OK);
2152 }
58eb9381 2153 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1c20f0e2
JD
2154 if (send_ret < 0) {
2155 ERR("Relay sending close index id reply");
2156 ret = send_ret;
2157 }
2158
2159end_no_session:
2160 return ret;
2161}
2162
a4baae1b
JD
2163/*
2164 * Receive the streams_sent message.
2165 *
2166 * Return 0 on success else a negative value.
2167 */
7591bab1 2168static int relay_streams_sent(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 2169 struct relay_connection *conn)
a4baae1b
JD
2170{
2171 int ret, send_ret;
2172 struct lttcomm_relayd_generic_reply reply;
2173
58eb9381 2174 assert(conn);
a4baae1b
JD
2175
2176 DBG("Relay receiving streams_sent");
2177
58eb9381 2178 if (!conn->session || conn->version_check_done == 0) {
a4baae1b
JD
2179 ERR("Trying to close a stream before version check");
2180 ret = -1;
2181 goto end_no_session;
2182 }
2183
2184 /*
7591bab1
MD
2185 * Publish every pending stream in the connection recv list which are
2186 * now ready to be used by the viewer.
4a9daf17 2187 */
7591bab1 2188 publish_connection_local_streams(conn);
4a9daf17 2189
53efb85a 2190 memset(&reply, 0, sizeof(reply));
a4baae1b 2191 reply.ret_code = htobe32(LTTNG_OK);
58eb9381 2192 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
a4baae1b
JD
2193 if (send_ret < 0) {
2194 ERR("Relay sending sent_stream reply");
2195 ret = send_ret;
2196 } else {
2197 /* Success. */
2198 ret = 0;
2199 }
2200
2201end_no_session:
2202 return ret;
2203}
2204
b8aa1682 2205/*
d3e2ba59 2206 * Process the commands received on the control socket
b8aa1682 2207 */
7591bab1 2208static int relay_process_control(struct lttcomm_relayd_hdr *recv_hdr,
58eb9381 2209 struct relay_connection *conn)
b8aa1682
JD
2210{
2211 int ret = 0;
2212
2213 switch (be32toh(recv_hdr->cmd)) {
b8aa1682 2214 case RELAYD_CREATE_SESSION:
58eb9381 2215 ret = relay_create_session(recv_hdr, conn);
b8aa1682 2216 break;
b8aa1682 2217 case RELAYD_ADD_STREAM:
58eb9381 2218 ret = relay_add_stream(recv_hdr, conn);
b8aa1682
JD
2219 break;
2220 case RELAYD_START_DATA:
58eb9381 2221 ret = relay_start(recv_hdr, conn);
b8aa1682
JD
2222 break;
2223 case RELAYD_SEND_METADATA:
58eb9381 2224 ret = relay_recv_metadata(recv_hdr, conn);
b8aa1682
JD
2225 break;
2226 case RELAYD_VERSION:
58eb9381 2227 ret = relay_send_version(recv_hdr, conn);
b8aa1682 2228 break;
173af62f 2229 case RELAYD_CLOSE_STREAM:
58eb9381 2230 ret = relay_close_stream(recv_hdr, conn);
173af62f 2231 break;
6d805429 2232 case RELAYD_DATA_PENDING:
58eb9381 2233 ret = relay_data_pending(recv_hdr, conn);
c8f59ee5
DG
2234 break;
2235 case RELAYD_QUIESCENT_CONTROL:
58eb9381 2236 ret = relay_quiescent_control(recv_hdr, conn);
c8f59ee5 2237 break;
f7079f67 2238 case RELAYD_BEGIN_DATA_PENDING:
58eb9381 2239 ret = relay_begin_data_pending(recv_hdr, conn);
f7079f67
DG
2240 break;
2241 case RELAYD_END_DATA_PENDING:
58eb9381 2242 ret = relay_end_data_pending(recv_hdr, conn);
f7079f67 2243 break;
1c20f0e2 2244 case RELAYD_SEND_INDEX:
58eb9381 2245 ret = relay_recv_index(recv_hdr, conn);
1c20f0e2 2246 break;
a4baae1b 2247 case RELAYD_STREAMS_SENT:
58eb9381 2248 ret = relay_streams_sent(recv_hdr, conn);
a4baae1b 2249 break;
93ec662e
JD
2250 case RELAYD_RESET_METADATA:
2251 ret = relay_reset_metadata(recv_hdr, conn);
2252 break;
82b4cfcc
MD
2253 case RELAYD_CLEAR_SESSION_CUSTOM_EFFICIOS:
2254 ret = relay_clear_session(recv_hdr, conn);
2255 break;
b8aa1682
JD
2256 case RELAYD_UPDATE_SYNC_INFO:
2257 default:
2258 ERR("Received unknown command (%u)", be32toh(recv_hdr->cmd));
58eb9381 2259 relay_unknown_command(conn);
b8aa1682
JD
2260 ret = -1;
2261 goto end;
2262 }
2263
2264end:
2265 return ret;
2266}
2267
7d2f7452
DG
2268/*
2269 * Handle index for a data stream.
2270 *
7591bab1 2271 * Called with the stream lock held.
7d2f7452
DG
2272 *
2273 * Return 0 on success else a negative value.
2274 */
2275static int handle_index_data(struct relay_stream *stream, uint64_t net_seq_num,
2276 int rotate_index)
2277{
7591bab1
MD
2278 int ret = 0;
2279 uint64_t data_offset;
2280 struct relay_index *index;
7d2f7452 2281
7d2f7452
DG
2282 /* Get data offset because we are about to update the index. */
2283 data_offset = htobe64(stream->tracefile_size_current);
2284
65d66b19
MD
2285 DBG("handle_index_data: stream %" PRIu64 " net_seq_num %" PRIu64 " data offset %" PRIu64,
2286 stream->stream_handle, net_seq_num, stream->tracefile_size_current);
7591bab1 2287
7d2f7452 2288 /*
7591bab1
MD
2289 * Lookup for an existing index for that stream id/sequence
2290 * number. If it exists, the control thread has already received the
2291 * data for it, thus we need to write it to disk.
7d2f7452 2292 */
7591bab1 2293 index = relay_index_get_by_id_or_create(stream, net_seq_num);
7d2f7452 2294 if (!index) {
7591bab1
MD
2295 ret = -1;
2296 goto end;
7d2f7452
DG
2297 }
2298
f8f3885c
MD
2299 if (rotate_index || !stream->index_file) {
2300 uint32_t major, minor;
7591bab1 2301
f8f3885c
MD
2302 /* Put ref on previous index_file. */
2303 if (stream->index_file) {
2304 lttng_index_file_put(stream->index_file);
2305 stream->index_file = NULL;
7d2f7452 2306 }
f8f3885c
MD
2307 major = stream->trace->session->major;
2308 minor = stream->trace->session->minor;
2309 stream->index_file = lttng_index_file_create(stream->path_name,
2310 stream->channel_name,
7591bab1 2311 -1, -1, stream->tracefile_size,
f8f3885c
MD
2312 tracefile_array_get_file_index_head(stream->tfa),
2313 lttng_to_index_major(major, minor),
2314 lttng_to_index_minor(major, minor));
2315 if (!stream->index_file) {
7591bab1
MD
2316 ret = -1;
2317 /* Put self-ref for this index due to error. */
2318 relay_index_put(index);
f8f3885c 2319 index = NULL;
7591bab1 2320 goto end;
7d2f7452 2321 }
7d2f7452
DG
2322 }
2323
f8f3885c 2324 if (relay_index_set_file(index, stream->index_file, data_offset)) {
7591bab1
MD
2325 ret = -1;
2326 /* Put self-ref for this index due to error. */
2327 relay_index_put(index);
f8f3885c 2328 index = NULL;
7591bab1 2329 goto end;
7d2f7452
DG
2330 }
2331
7591bab1
MD
2332 ret = relay_index_try_flush(index);
2333 if (ret == 0) {
82b4cfcc 2334 tracefile_array_commit_seq(stream->tfa, stream->index_received_seqcount);
a44ca2ca 2335 stream->index_received_seqcount++;
82b4cfcc
MD
2336 /* Clear index and data file(s) if reaching the clear position. */
2337 ret = try_stream_clear_index_data(stream);
2338 if (ret) {
2339 goto end;
2340 }
7591bab1
MD
2341 } else if (ret > 0) {
2342 /* No flush. */
2343 ret = 0;
2344 } else {
a86c0657
JR
2345 /*
2346 * ret < 0
2347 *
2348 * relay_index_try_flush is responsible for the self-reference
2349 * put of the index object on error.
2350 */
2351 ERR("relay_index_try_flush error %d", ret);
7591bab1
MD
2352 ret = -1;
2353 }
2354end:
7d2f7452
DG
2355 return ret;
2356}
2357
b8aa1682
JD
2358/*
2359 * relay_process_data: Process the data received on the data socket
2360 */
7591bab1 2361static int relay_process_data(struct relay_connection *conn)
b8aa1682 2362{
7d2f7452 2363 int ret = 0, rotate_index = 0;
6cd525e8 2364 ssize_t size_ret;
b8aa1682
JD
2365 struct relay_stream *stream;
2366 struct lttcomm_relayd_data_hdr data_hdr;
7d2f7452 2367 uint64_t stream_id;
173af62f 2368 uint64_t net_seq_num;
b8aa1682 2369 uint32_t data_size;
2a174661 2370 struct relay_session *session;
bda7c7b9 2371 bool new_stream = false, close_requested = false;
0848dba7
MD
2372 size_t chunk_size = RECV_DATA_BUFFER_SIZE;
2373 size_t recv_off = 0;
2374 char data_buffer[chunk_size];
b8aa1682 2375
58eb9381 2376 ret = conn->sock->ops->recvmsg(conn->sock, &data_hdr,
7c5aef62 2377 sizeof(struct lttcomm_relayd_data_hdr), 0);
b8aa1682 2378 if (ret <= 0) {
a6cd2b97
DG
2379 if (ret == 0) {
2380 /* Orderly shutdown. Not necessary to print an error. */
58eb9381 2381 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
a6cd2b97 2382 } else {
58eb9381 2383 ERR("Unable to receive data header on sock %d", conn->sock->fd);
a6cd2b97 2384 }
b8aa1682
JD
2385 ret = -1;
2386 goto end;
2387 }
2388
2389 stream_id = be64toh(data_hdr.stream_id);
7591bab1 2390 stream = stream_get_by_id(stream_id);
b8aa1682 2391 if (!stream) {
65d66b19 2392 ERR("relay_process_data: Cannot find stream %" PRIu64, stream_id);
b8aa1682 2393 ret = -1;
7591bab1 2394 goto end;
b8aa1682 2395 }
7591bab1 2396 session = stream->trace->session;
b8aa1682 2397 data_size = be32toh(data_hdr.data_size);
b8aa1682 2398
173af62f
DG
2399 net_seq_num = be64toh(data_hdr.net_seq_num);
2400
82b4cfcc 2401 DBG("Receiving data of size %u for stream id %" PRIu64 " seqnum %" PRIu64,
173af62f 2402 data_size, stream_id, net_seq_num);
b8aa1682 2403
7591bab1
MD
2404 pthread_mutex_lock(&stream->lock);
2405
1c20f0e2 2406 /* Check if a rotation is needed. */
0f907de1
JD
2407 if (stream->tracefile_size > 0 &&
2408 (stream->tracefile_size_current + data_size) >
2409 stream->tracefile_size) {
a44ca2ca
MD
2410 uint64_t old_id, new_id;
2411
2412 old_id = tracefile_array_get_file_index_head(stream->tfa);
2413 tracefile_array_file_rotate(stream->tfa);
2414
2415 /* new_id is updated by utils_rotate_stream_file. */
2416 new_id = old_id;
6b6b9a5a 2417
7591bab1
MD
2418 ret = utils_rotate_stream_file(stream->path_name,
2419 stream->channel_name, stream->tracefile_size,
2420 stream->tracefile_count, -1,
2421 -1, stream->stream_fd->fd,
a44ca2ca 2422 &new_id, &stream->stream_fd->fd);
0f907de1 2423 if (ret < 0) {
1c20f0e2 2424 ERR("Rotating stream output file");
7591bab1
MD
2425 goto end_stream_unlock;
2426 }
7591bab1
MD
2427 /*
2428 * Reset current size because we just performed a stream
2429 * rotation.
2430 */
a6976990 2431 stream->tracefile_size_current = 0;
82b4cfcc 2432 stream->tracefile_count_current = new_id;
1c20f0e2
JD
2433 rotate_index = 1;
2434 }
2435
1c20f0e2 2436 /*
7591bab1
MD
2437 * Index are handled in protocol version 2.4 and above. Also,
2438 * snapshot and index are NOT supported.
1c20f0e2 2439 */
2a174661 2440 if (session->minor >= 4 && !session->snapshot) {
7d2f7452 2441 ret = handle_index_data(stream, net_seq_num, rotate_index);
1c20f0e2 2442 if (ret < 0) {
65d66b19
MD
2443 ERR("handle_index_data: fail stream %" PRIu64 " net_seq_num %" PRIu64 " ret %d",
2444 stream->stream_handle, net_seq_num, ret);
7591bab1 2445 goto end_stream_unlock;
1c20f0e2 2446 }
1c20f0e2
JD
2447 }
2448
0848dba7
MD
2449 for (recv_off = 0; recv_off < data_size; recv_off += chunk_size) {
2450 size_t recv_size = min(data_size - recv_off, chunk_size);
1d4dfdef 2451
0848dba7
MD
2452 ret = conn->sock->ops->recvmsg(conn->sock, data_buffer, recv_size, 0);
2453 if (ret <= 0) {
2454 if (ret == 0) {
2455 /* Orderly shutdown. Not necessary to print an error. */
2456 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
2457 } else {
2458 ERR("Socket %d error %d", conn->sock->fd, ret);
2459 }
2460 ret = -1;
2461 goto end_stream_unlock;
2462 }
2463
2464 /* Write data to stream output fd. */
2465 size_ret = lttng_write(stream->stream_fd->fd, data_buffer,
2466 recv_size);
2467 if (size_ret < recv_size) {
2468 ERR("Relay error writing data to file");
2469 ret = -1;
2470 goto end_stream_unlock;
2471 }
2472
2473 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64,
2474 size_ret, stream->stream_handle);
2475 }
5ab7344e 2476
7591bab1
MD
2477 ret = write_padding_to_file(stream->stream_fd->fd,
2478 be32toh(data_hdr.padding_size));
1d4dfdef 2479 if (ret < 0) {
65d66b19
MD
2480 ERR("write_padding_to_file: fail stream %" PRIu64 " net_seq_num %" PRIu64 " ret %d",
2481 stream->stream_handle, net_seq_num, ret);
7591bab1 2482 goto end_stream_unlock;
1d4dfdef 2483 }
7591bab1
MD
2484 stream->tracefile_size_current +=
2485 data_size + be32toh(data_hdr.padding_size);
c0bae11d
MD
2486 if (stream->prev_seq == -1ULL) {
2487 new_stream = true;
2488 }
2489
173af62f
DG
2490 stream->prev_seq = net_seq_num;
2491
7591bab1 2492end_stream_unlock:
bda7c7b9 2493 close_requested = stream->close_requested;
7591bab1 2494 pthread_mutex_unlock(&stream->lock);
bda7c7b9
JG
2495 if (close_requested) {
2496 try_stream_close(stream);
2497 }
2498
c0bae11d
MD
2499 if (new_stream) {
2500 pthread_mutex_lock(&session->lock);
2501 uatomic_set(&session->new_streams, 1);
2502 pthread_mutex_unlock(&session->lock);
2503 }
7591bab1 2504 stream_put(stream);
b8aa1682
JD
2505end:
2506 return ret;
2507}
2508
7591bab1 2509static void cleanup_connection_pollfd(struct lttng_poll_event *events, int pollfd)
b8aa1682
JD
2510{
2511 int ret;
2512
58eb9381 2513 (void) lttng_poll_del(events, pollfd);
b8aa1682
JD
2514
2515 ret = close(pollfd);
2516 if (ret < 0) {
2517 ERR("Closing pollfd %d", pollfd);
2518 }
2519}
2520
7591bab1
MD
2521static void relay_thread_close_connection(struct lttng_poll_event *events,
2522 int pollfd, struct relay_connection *conn)
9d1bbf21 2523{
7591bab1 2524 const char *type_str;
2a174661 2525
7591bab1
MD
2526 switch (conn->type) {
2527 case RELAY_DATA:
2528 type_str = "Data";
2529 break;
2530 case RELAY_CONTROL:
2531 type_str = "Control";
2532 break;
2533 case RELAY_VIEWER_COMMAND:
2534 type_str = "Viewer Command";
2535 break;
2536 case RELAY_VIEWER_NOTIFICATION:
2537 type_str = "Viewer Notification";
2538 break;
2539 default:
2540 type_str = "Unknown";
9d1bbf21 2541 }
7591bab1
MD
2542 cleanup_connection_pollfd(events, pollfd);
2543 connection_put(conn);
2544 DBG("%s connection closed with %d", type_str, pollfd);
b8aa1682
JD
2545}
2546
2547/*
2548 * This thread does the actual work
2549 */
7591bab1 2550static void *relay_thread_worker(void *data)
b8aa1682 2551{
beaad64c
DG
2552 int ret, err = -1, last_seen_data_fd = -1;
2553 uint32_t nb_fd;
b8aa1682
JD
2554 struct lttng_poll_event events;
2555 struct lttng_ht *relay_connections_ht;
b8aa1682 2556 struct lttng_ht_iter iter;
b8aa1682 2557 struct lttcomm_relayd_hdr recv_hdr;
90e7d72f 2558 struct relay_connection *destroy_conn = NULL;
b8aa1682
JD
2559
2560 DBG("[thread] Relay worker started");
2561
9d1bbf21
MD
2562 rcu_register_thread();
2563
55706a7d
MD
2564 health_register(health_relayd, HEALTH_RELAYD_TYPE_WORKER);
2565
9b5e0863
MD
2566 if (testpoint(relayd_thread_worker)) {
2567 goto error_testpoint;
2568 }
2569
f385ae0a
MD
2570 health_code_update();
2571
b8aa1682
JD
2572 /* table of connections indexed on socket */
2573 relay_connections_ht = lttng_ht_new(0, LTTNG_HT_TYPE_ULONG);
095a4ae5
MD
2574 if (!relay_connections_ht) {
2575 goto relay_connections_ht_error;
2576 }
b8aa1682 2577
b8aa1682
JD
2578 ret = create_thread_poll_set(&events, 2);
2579 if (ret < 0) {
2580 goto error_poll_create;
2581 }
2582
58eb9381 2583 ret = lttng_poll_add(&events, relay_conn_pipe[0], LPOLLIN | LPOLLRDHUP);
b8aa1682
JD
2584 if (ret < 0) {
2585 goto error;
2586 }
2587
beaad64c 2588restart:
b8aa1682 2589 while (1) {
beaad64c
DG
2590 int idx = -1, i, seen_control = 0, last_notdel_data_fd = -1;
2591
f385ae0a
MD
2592 health_code_update();
2593
b8aa1682 2594 /* Infinite blocking call, waiting for transmission */
87c1611d 2595 DBG3("Relayd worker thread polling...");
f385ae0a 2596 health_poll_entry();
b8aa1682 2597 ret = lttng_poll_wait(&events, -1);
f385ae0a 2598 health_poll_exit();
b8aa1682
JD
2599 if (ret < 0) {
2600 /*
2601 * Restart interrupted system call.
2602 */
2603 if (errno == EINTR) {
2604 goto restart;
2605 }
2606 goto error;
2607 }
2608
0d9c5d77
DG
2609 nb_fd = ret;
2610
beaad64c 2611 /*
7591bab1
MD
2612 * Process control. The control connection is
2613 * prioritized so we don't starve it with high
2614 * throughput tracing data on the data connection.
beaad64c 2615 */
b8aa1682
JD
2616 for (i = 0; i < nb_fd; i++) {
2617 /* Fetch once the poll data */
beaad64c
DG
2618 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
2619 int pollfd = LTTNG_POLL_GETFD(&events, i);
b8aa1682 2620
f385ae0a
MD
2621 health_code_update();
2622
fd20dac9 2623 if (!revents) {
7591bab1
MD
2624 /*
2625 * No activity for this FD (poll
2626 * implementation).
2627 */
fd20dac9
MD
2628 continue;
2629 }
2630
b8aa1682
JD
2631 /* Thread quit pipe has been closed. Killing thread. */
2632 ret = check_thread_quit_pipe(pollfd, revents);
2633 if (ret) {
095a4ae5
MD
2634 err = 0;
2635 goto exit;
b8aa1682
JD
2636 }
2637
58eb9381
DG
2638 /* Inspect the relay conn pipe for new connection */
2639 if (pollfd == relay_conn_pipe[0]) {
03e43155 2640 if (revents & LPOLLIN) {
90e7d72f
JG
2641 struct relay_connection *conn;
2642
58eb9381 2643 ret = lttng_read(relay_conn_pipe[0], &conn, sizeof(conn));
b8aa1682
JD
2644 if (ret < 0) {
2645 goto error;
2646 }
58eb9381
DG
2647 lttng_poll_add(&events, conn->sock->fd,
2648 LPOLLIN | LPOLLRDHUP);
7591bab1 2649 connection_ht_add(relay_connections_ht, conn);
58eb9381 2650 DBG("Connection socket %d added", conn->sock->fd);
03e43155
MD
2651 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2652 ERR("Relay connection pipe error");
2653 goto error;
2654 } else {
2655 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
2656 goto error;
b8aa1682 2657 }
58eb9381 2658 } else {
90e7d72f
JG
2659 struct relay_connection *ctrl_conn;
2660
7591bab1 2661 ctrl_conn = connection_get_by_sock(relay_connections_ht, pollfd);
58eb9381 2662 /* If not found, there is a synchronization issue. */
90e7d72f 2663 assert(ctrl_conn);
58eb9381 2664
03e43155
MD
2665 if (ctrl_conn->type == RELAY_DATA) {
2666 if (revents & LPOLLIN) {
beaad64c
DG
2667 /*
2668 * Flag the last seen data fd not deleted. It will be
2669 * used as the last seen fd if any fd gets deleted in
2670 * this first loop.
2671 */
2672 last_notdel_data_fd = pollfd;
2673 }
03e43155
MD
2674 goto put_ctrl_connection;
2675 }
2676 assert(ctrl_conn->type == RELAY_CONTROL);
2677
2678 if (revents & LPOLLIN) {
2679 ret = ctrl_conn->sock->ops->recvmsg(ctrl_conn->sock,
2680 &recv_hdr, sizeof(recv_hdr), 0);
2681 if (ret <= 0) {
2682 /* Connection closed */
2683 relay_thread_close_connection(&events, pollfd,
2684 ctrl_conn);
2685 } else {
2686 ret = relay_process_control(&recv_hdr, ctrl_conn);
2687 if (ret < 0) {
2688 /* Clear the session on error. */
2689 relay_thread_close_connection(&events,
2690 pollfd, ctrl_conn);
2691 }
2692 seen_control = 1;
2693 }
2694 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2695 relay_thread_close_connection(&events,
2696 pollfd, ctrl_conn);
2697 if (last_seen_data_fd == pollfd) {
2698 last_seen_data_fd = last_notdel_data_fd;
2699 }
58eb9381 2700 } else {
03e43155
MD
2701 ERR("Unexpected poll events %u for control sock %d",
2702 revents, pollfd);
2703 connection_put(ctrl_conn);
2704 goto error;
beaad64c 2705 }
03e43155 2706 put_ctrl_connection:
7591bab1 2707 connection_put(ctrl_conn);
beaad64c
DG
2708 }
2709 }
2710
2711 /*
2712 * The last loop handled a control request, go back to poll to make
2713 * sure we prioritise the control socket.
2714 */
2715 if (seen_control) {
2716 continue;
2717 }
2718
2719 if (last_seen_data_fd >= 0) {
2720 for (i = 0; i < nb_fd; i++) {
2721 int pollfd = LTTNG_POLL_GETFD(&events, i);
f385ae0a
MD
2722
2723 health_code_update();
2724
beaad64c
DG
2725 if (last_seen_data_fd == pollfd) {
2726 idx = i;
2727 break;
2728 }
2729 }
2730 }
2731
2732 /* Process data connection. */
2733 for (i = idx + 1; i < nb_fd; i++) {
2734 /* Fetch the poll data. */
2735 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
2736 int pollfd = LTTNG_POLL_GETFD(&events, i);
90e7d72f 2737 struct relay_connection *data_conn;
beaad64c 2738
f385ae0a
MD
2739 health_code_update();
2740
fd20dac9
MD
2741 if (!revents) {
2742 /* No activity for this FD (poll implementation). */
2743 continue;
2744 }
2745
beaad64c 2746 /* Skip the command pipe. It's handled in the first loop. */
58eb9381 2747 if (pollfd == relay_conn_pipe[0]) {
beaad64c
DG
2748 continue;
2749 }
2750
7591bab1 2751 data_conn = connection_get_by_sock(relay_connections_ht, pollfd);
90e7d72f 2752 if (!data_conn) {
fd20dac9 2753 /* Skip it. Might be removed before. */
fd20dac9
MD
2754 continue;
2755 }
03e43155
MD
2756 if (data_conn->type == RELAY_CONTROL) {
2757 goto put_data_connection;
2758 }
2759 assert(data_conn->type == RELAY_DATA);
fd20dac9
MD
2760
2761 if (revents & LPOLLIN) {
90e7d72f 2762 ret = relay_process_data(data_conn);
fd20dac9
MD
2763 /* Connection closed */
2764 if (ret < 0) {
7591bab1 2765 relay_thread_close_connection(&events, pollfd,
03e43155 2766 data_conn);
fd20dac9
MD
2767 /*
2768 * Every goto restart call sets the last seen fd where
2769 * here we don't really care since we gracefully
2770 * continue the loop after the connection is deleted.
2771 */
2772 } else {
2773 /* Keep last seen port. */
2774 last_seen_data_fd = pollfd;
7591bab1 2775 connection_put(data_conn);
fd20dac9 2776 goto restart;
b8aa1682 2777 }
03e43155
MD
2778 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2779 relay_thread_close_connection(&events, pollfd,
2780 data_conn);
2781 } else {
2782 ERR("Unknown poll events %u for data sock %d",
2783 revents, pollfd);
b8aa1682 2784 }
03e43155 2785 put_data_connection:
7591bab1 2786 connection_put(data_conn);
b8aa1682 2787 }
beaad64c 2788 last_seen_data_fd = -1;
b8aa1682
JD
2789 }
2790
f385ae0a
MD
2791 /* Normal exit, no error */
2792 ret = 0;
2793
095a4ae5 2794exit:
b8aa1682 2795error:
58eb9381 2796 /* Cleanup reamaining connection object. */
9d1bbf21 2797 rcu_read_lock();
90e7d72f
JG
2798 cds_lfht_for_each_entry(relay_connections_ht->ht, &iter.iter,
2799 destroy_conn,
58eb9381 2800 sock_n.node) {
f385ae0a 2801 health_code_update();
98ba050e
JR
2802
2803 if (session_abort(destroy_conn->session)) {
2804 assert(0);
2805 }
2806
7591bab1
MD
2807 /*
2808 * No need to grab another ref, because we own
2809 * destroy_conn.
2810 */
2811 relay_thread_close_connection(&events, destroy_conn->sock->fd,
2812 destroy_conn);
b8aa1682 2813 }
94d49140 2814 rcu_read_unlock();
7591bab1
MD
2815
2816 lttng_poll_clean(&events);
7d2f7452 2817error_poll_create:
b8aa1682 2818 lttng_ht_destroy(relay_connections_ht);
095a4ae5 2819relay_connections_ht_error:
58eb9381
DG
2820 /* Close relay conn pipes */
2821 utils_close_pipe(relay_conn_pipe);
095a4ae5
MD
2822 if (err) {
2823 DBG("Thread exited with error");
2824 }
b8aa1682 2825 DBG("Worker thread cleanup complete");
9b5e0863 2826error_testpoint:
f385ae0a
MD
2827 if (err) {
2828 health_error();
2829 ERR("Health error occurred in %s", __func__);
2830 }
2831 health_unregister(health_relayd);
9d1bbf21 2832 rcu_unregister_thread();
b4aacfdc 2833 lttng_relay_stop_threads();
b8aa1682
JD
2834 return NULL;
2835}
2836
2837/*
2838 * Create the relay command pipe to wake thread_manage_apps.
2839 * Closed in cleanup().
2840 */
58eb9381 2841static int create_relay_conn_pipe(void)
b8aa1682 2842{
a02de639 2843 int ret;
b8aa1682 2844
58eb9381 2845 ret = utils_create_pipe_cloexec(relay_conn_pipe);
b8aa1682 2846
b8aa1682
JD
2847 return ret;
2848}
2849
2850/*
2851 * main
2852 */
2853int main(int argc, char **argv)
2854{
178a0557 2855 int ret = 0, retval = 0;
b8aa1682
JD
2856 void *status;
2857
b8aa1682
JD
2858 /* Parse arguments */
2859 progname = argv[0];
178a0557
MD
2860 if (set_options(argc, argv)) {
2861 retval = -1;
2862 goto exit_options;
b8aa1682
JD
2863 }
2864
178a0557
MD
2865 if (set_signal_handler()) {
2866 retval = -1;
2867 goto exit_options;
b8aa1682
JD
2868 }
2869
f5a36bab
JR
2870 if (!opt_allow_clear) {
2871 DBG("Clear command disallowed.");
2872 }
2873
4d513a50
DG
2874 /* Try to create directory if -o, --output is specified. */
2875 if (opt_output_path) {
994fa64f
DG
2876 if (*opt_output_path != '/') {
2877 ERR("Please specify an absolute path for -o, --output PATH");
178a0557
MD
2878 retval = -1;
2879 goto exit_options;
994fa64f
DG
2880 }
2881
d77dded2
JG
2882 ret = utils_mkdir_recursive(opt_output_path, S_IRWXU | S_IRWXG,
2883 -1, -1);
4d513a50
DG
2884 if (ret < 0) {
2885 ERR("Unable to create %s", opt_output_path);
178a0557
MD
2886 retval = -1;
2887 goto exit_options;
4d513a50
DG
2888 }
2889 }
2890
b8aa1682 2891 /* Daemonize */
b5218ffb 2892 if (opt_daemon || opt_background) {
3fd27398
MD
2893 int i;
2894
2895 ret = lttng_daemonize(&child_ppid, &recv_child_signal,
2896 !opt_background);
b8aa1682 2897 if (ret < 0) {
178a0557
MD
2898 retval = -1;
2899 goto exit_options;
b8aa1682 2900 }
3fd27398
MD
2901
2902 /*
2903 * We are in the child. Make sure all other file
2904 * descriptors are closed, in case we are called with
2905 * more opened file descriptors than the standard ones.
2906 */
2907 for (i = 3; i < sysconf(_SC_OPEN_MAX); i++) {
2908 (void) close(i);
2909 }
2910 }
2911
178a0557
MD
2912 /* Initialize thread health monitoring */
2913 health_relayd = health_app_create(NR_HEALTH_RELAYD_TYPES);
2914 if (!health_relayd) {
2915 PERROR("health_app_create error");
2916 retval = -1;
2917 goto exit_health_app_create;
2918 }
2919
3fd27398 2920 /* Create thread quit pipe */
178a0557
MD
2921 if (init_thread_quit_pipe()) {
2922 retval = -1;
2923 goto exit_init_data;
b8aa1682
JD
2924 }
2925
b8aa1682 2926 /* Setup the thread apps communication pipe. */
178a0557
MD
2927 if (create_relay_conn_pipe()) {
2928 retval = -1;
2929 goto exit_init_data;
b8aa1682
JD
2930 }
2931
2932 /* Init relay command queue. */
8bdee6e2 2933 cds_wfcq_init(&relay_conn_queue.head, &relay_conn_queue.tail);
b8aa1682 2934
554831e7
MD
2935 /* Initialize communication library */
2936 lttcomm_init();
87e45c13 2937 lttcomm_inet_init();
554831e7 2938
d3e2ba59 2939 /* tables of sessions indexed by session ID */
7591bab1
MD
2940 sessions_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
2941 if (!sessions_ht) {
178a0557
MD
2942 retval = -1;
2943 goto exit_init_data;
d3e2ba59
JD
2944 }
2945
2946 /* tables of streams indexed by stream ID */
2a174661 2947 relay_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
d3e2ba59 2948 if (!relay_streams_ht) {
178a0557
MD
2949 retval = -1;
2950 goto exit_init_data;
d3e2ba59
JD
2951 }
2952
2953 /* tables of streams indexed by stream ID */
92c6ca54
DG
2954 viewer_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
2955 if (!viewer_streams_ht) {
178a0557
MD
2956 retval = -1;
2957 goto exit_init_data;
55706a7d
MD
2958 }
2959
65931c8b 2960 ret = utils_create_pipe(health_quit_pipe);
178a0557
MD
2961 if (ret) {
2962 retval = -1;
2963 goto exit_health_quit_pipe;
65931c8b
MD
2964 }
2965
2966 /* Create thread to manage the client socket */
1a1a34b4 2967 ret = pthread_create(&health_thread, default_pthread_attr(),
65931c8b 2968 thread_manage_health, (void *) NULL);
178a0557
MD
2969 if (ret) {
2970 errno = ret;
65931c8b 2971 PERROR("pthread_create health");
178a0557
MD
2972 retval = -1;
2973 goto exit_health_thread;
65931c8b
MD
2974 }
2975
b8aa1682 2976 /* Setup the dispatcher thread */
1a1a34b4 2977 ret = pthread_create(&dispatcher_thread, default_pthread_attr(),
b8aa1682 2978 relay_thread_dispatcher, (void *) NULL);
178a0557
MD
2979 if (ret) {
2980 errno = ret;
b8aa1682 2981 PERROR("pthread_create dispatcher");
178a0557
MD
2982 retval = -1;
2983 goto exit_dispatcher_thread;
b8aa1682
JD
2984 }
2985
2986 /* Setup the worker thread */
1a1a34b4 2987 ret = pthread_create(&worker_thread, default_pthread_attr(),
7591bab1 2988 relay_thread_worker, NULL);
178a0557
MD
2989 if (ret) {
2990 errno = ret;
b8aa1682 2991 PERROR("pthread_create worker");
178a0557
MD
2992 retval = -1;
2993 goto exit_worker_thread;
b8aa1682
JD
2994 }
2995
2996 /* Setup the listener thread */
1a1a34b4 2997 ret = pthread_create(&listener_thread, default_pthread_attr(),
b8aa1682 2998 relay_thread_listener, (void *) NULL);
178a0557
MD
2999 if (ret) {
3000 errno = ret;
b8aa1682 3001 PERROR("pthread_create listener");
178a0557
MD
3002 retval = -1;
3003 goto exit_listener_thread;
b8aa1682
JD
3004 }
3005
7591bab1 3006 ret = relayd_live_create(live_uri);
178a0557 3007 if (ret) {
d3e2ba59 3008 ERR("Starting live viewer threads");
178a0557 3009 retval = -1;
50138f51 3010 goto exit_live;
d3e2ba59
JD
3011 }
3012
178a0557
MD
3013 /*
3014 * This is where we start awaiting program completion (e.g. through
3015 * signal that asks threads to teardown).
3016 */
3017
3018 ret = relayd_live_join();
3019 if (ret) {
3020 retval = -1;
3021 }
50138f51 3022exit_live:
178a0557 3023
b8aa1682 3024 ret = pthread_join(listener_thread, &status);
178a0557
MD
3025 if (ret) {
3026 errno = ret;
3027 PERROR("pthread_join listener_thread");
3028 retval = -1;
b8aa1682
JD
3029 }
3030
178a0557 3031exit_listener_thread:
b8aa1682 3032 ret = pthread_join(worker_thread, &status);
178a0557
MD
3033 if (ret) {
3034 errno = ret;
3035 PERROR("pthread_join worker_thread");
3036 retval = -1;
b8aa1682
JD
3037 }
3038
178a0557 3039exit_worker_thread:
b8aa1682 3040 ret = pthread_join(dispatcher_thread, &status);
178a0557
MD
3041 if (ret) {
3042 errno = ret;
3043 PERROR("pthread_join dispatcher_thread");
3044 retval = -1;
b8aa1682 3045 }
178a0557 3046exit_dispatcher_thread:
42415026 3047
65931c8b 3048 ret = pthread_join(health_thread, &status);
178a0557
MD
3049 if (ret) {
3050 errno = ret;
3051 PERROR("pthread_join health_thread");
3052 retval = -1;
65931c8b 3053 }
178a0557 3054exit_health_thread:
65931c8b 3055
65931c8b 3056 utils_close_pipe(health_quit_pipe);
178a0557 3057exit_health_quit_pipe:
65931c8b 3058
178a0557 3059exit_init_data:
55706a7d 3060 health_app_destroy(health_relayd);
55706a7d 3061exit_health_app_create:
178a0557 3062exit_options:
4d62fbf8
MD
3063 /*
3064 * Wait for all pending call_rcu work to complete before tearing
3065 * down data structures. call_rcu worker may be trying to
3066 * perform lookups in those structures.
3067 */
3068 rcu_barrier();
7591bab1
MD
3069 relayd_cleanup();
3070
3071 /* Ensure all prior call_rcu are done. */
3072 rcu_barrier();
d3e2ba59 3073
178a0557 3074 if (!retval) {
b8aa1682 3075 exit(EXIT_SUCCESS);
178a0557
MD
3076 } else {
3077 exit(EXIT_FAILURE);
b8aa1682 3078 }
b8aa1682 3079}
This page took 0.312155 seconds and 5 git commands to generate.