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