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