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