Fix: release reference to created chunk if it can't be published
[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>
70626904 40#include <urcu/rculist.h>
b8aa1682
JD
41#include <unistd.h>
42#include <fcntl.h>
f8be1183 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>
70626904 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"
23c8ff50 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,
a9577b76 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
23c8ff50
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
298a25ca
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;
4c6885d2 1071 struct relay_session *session = NULL;
ecd1a12f 1072 struct lttcomm_relayd_create_session_reply_2_11 reply = {};
1e791a74
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;
46ef2188 1077 bool session_name_contains_creation_timestamp = false;
23c8ff50 1078 /* Left nil for peers < 2.11. */
6fa5fe7c 1079 char base_path[LTTNG_PATH_MAX] = {};
23c8ff50 1080 lttng_uuid sessiond_uuid = {};
1e791a74
JG
1081 LTTNG_OPTIONAL(uint64_t) id_sessiond = {};
1082 LTTNG_OPTIONAL(uint64_t) current_chunk_id = {};
db1da059 1083 LTTNG_OPTIONAL(time_t) creation_time = {};
ecd1a12f
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 {
84fa4db5 1096 bool has_current_chunk;
db1da059
JG
1097 uint64_t current_chunk_id_value;
1098 time_t creation_time_value;
1099 uint64_t id_sessiond_value;
84fa4db5 1100
f86f6389 1101 /* From 2.11 to ... */
db1da059 1102 ret = cmd_create_session_2_11(payload, session_name, hostname,
6fa5fe7c 1103 base_path, &live_timer, &snapshot, &id_sessiond_value,
db1da059 1104 sessiond_uuid, &has_current_chunk,
46ef2188
MD
1105 &current_chunk_id_value, &creation_time_value,
1106 &session_name_contains_creation_timestamp);
23c8ff50
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 }
db1da059
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
6fa5fe7c 1125 session = session_create(session_name, hostname, base_path, live_timer,
1e791a74
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,
db1da059 1129 creation_time.is_set ? &creation_time.value : NULL,
46ef2188
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
ecd1a12f 1140 reply.generic.session_id = htobe64(session->id);
7591bab1
MD
1141
1142send_reply:
c5b6f4f0 1143 if (ret < 0) {
ecd1a12f 1144 reply.generic.ret_code = htobe32(LTTNG_ERR_FATAL);
c5b6f4f0 1145 } else {
ecd1a12f 1146 reply.generic.ret_code = htobe32(LTTNG_OK);
c5b6f4f0
DG
1147 }
1148
ecd1a12f
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 =
1160 strlen(session->output_path) + 1;
1161
1162 reply.output_path_length = htobe32(output_path_length);
1163 ret = lttng_dynamic_buffer_append(&reply_payload, &reply,
1164 sizeof(reply));
1165 if (ret) {
1166 ERR("Failed to append \"create session\" command reply header to payload buffer");
1167 goto end;
1168 }
1169
1170 ret = lttng_dynamic_buffer_append(&reply_payload,
1171 session->output_path, output_path_length);
1172 if (ret) {
1173 ERR("Failed to append \"create session\" command reply path to payload buffer");
1174 goto end;
1175 }
1176 }
1177
1178 send_ret = conn->sock->ops->sendmsg(conn->sock, reply_payload.data,
1179 reply_payload.size, 0);
1180 if (send_ret < (ssize_t) reply_payload.size) {
1181 ERR("Failed to send \"create session\" command reply of %zu bytes (ret = %zd)",
1182 reply_payload.size, send_ret);
5312a3ed 1183 ret = -1;
c5b6f4f0 1184 }
ecd1a12f 1185end:
4c6885d2
JG
1186 if (ret < 0 && session) {
1187 session_put(session);
1188 }
ecd1a12f 1189 lttng_dynamic_buffer_reset(&reply_payload);
c5b6f4f0
DG
1190 return ret;
1191}
1192
a4baae1b
JD
1193/*
1194 * When we have received all the streams and the metadata for a channel,
1195 * we make them visible to the viewer threads.
1196 */
7591bab1 1197static void publish_connection_local_streams(struct relay_connection *conn)
a4baae1b 1198{
7591bab1
MD
1199 struct relay_stream *stream;
1200 struct relay_session *session = conn->session;
a4baae1b 1201
7591bab1
MD
1202 /*
1203 * We publish all streams belonging to a session atomically wrt
1204 * session lock.
1205 */
1206 pthread_mutex_lock(&session->lock);
1207 rcu_read_lock();
1208 cds_list_for_each_entry_rcu(stream, &session->recv_list,
1209 recv_node) {
1210 stream_publish(stream);
a4baae1b 1211 }
7591bab1 1212 rcu_read_unlock();
a4baae1b 1213
7591bab1
MD
1214 /*
1215 * Inform the viewer that there are new streams in the session.
1216 */
1217 if (session->viewer_attached) {
1218 uatomic_set(&session->new_streams, 1);
1219 }
1220 pthread_mutex_unlock(&session->lock);
a4baae1b
JD
1221}
1222
348a81dc
JG
1223static int conform_channel_path(char *channel_path)
1224{
1225 int ret = 0;
1226
1227 if (strstr("../", channel_path)) {
1228 ERR("Refusing channel path as it walks up the path hierarchy: \"%s\"",
1229 channel_path);
1230 ret = -1;
1231 goto end;
1232 }
1233
1234 if (*channel_path == '/') {
1235 const size_t len = strlen(channel_path);
1236
1237 /*
1238 * Channel paths from peers prior to 2.11 are expressed as an
1239 * absolute path that is, in reality, relative to the relay
1240 * daemon's output directory. Remove the leading slash so it
1241 * is correctly interpreted as a relative path later on.
1242 *
1243 * len (and not len - 1) is used to copy the trailing NULL.
1244 */
1245 bcopy(channel_path + 1, channel_path, len);
1246 }
1247end:
1248 return ret;
1249}
1250
b8aa1682
JD
1251/*
1252 * relay_add_stream: allocate a new stream for a session
1253 */
5312a3ed
JG
1254static int relay_add_stream(const struct lttcomm_relayd_hdr *recv_hdr,
1255 struct relay_connection *conn,
1256 const struct lttng_buffer_view *payload)
b8aa1682 1257{
7591bab1
MD
1258 int ret;
1259 ssize_t send_ret;
58eb9381 1260 struct relay_session *session = conn->session;
b8aa1682
JD
1261 struct relay_stream *stream = NULL;
1262 struct lttcomm_relayd_status_stream reply;
4030a636 1263 struct ctf_trace *trace = NULL;
7591bab1
MD
1264 uint64_t stream_handle = -1ULL;
1265 char *path_name = NULL, *channel_name = NULL;
1266 uint64_t tracefile_size = 0, tracefile_count = 0;
348a81dc 1267 LTTNG_OPTIONAL(uint64_t) stream_chunk_id = {};
b8aa1682 1268
5312a3ed 1269 if (!session || !conn->version_check_done) {
b8aa1682
JD
1270 ERR("Trying to add a stream before version check");
1271 ret = -1;
1272 goto end_no_session;
1273 }
1274
2f21a469
JR
1275 if (session->minor == 1) {
1276 /* For 2.1 */
5312a3ed 1277 ret = cmd_recv_stream_2_1(payload, &path_name,
7591bab1 1278 &channel_name);
2f21a469
JR
1279 } else if (session->minor > 1 && session->minor < 11) {
1280 /* From 2.2 to 2.10 */
5312a3ed 1281 ret = cmd_recv_stream_2_2(payload, &path_name,
7591bab1 1282 &channel_name, &tracefile_size, &tracefile_count);
2f21a469
JR
1283 } else {
1284 /* From 2.11 to ... */
1285 ret = cmd_recv_stream_2_11(payload, &path_name,
0b50e4b3
JG
1286 &channel_name, &tracefile_size, &tracefile_count,
1287 &stream_chunk_id.value);
1288 stream_chunk_id.is_set = true;
0f907de1 1289 }
2f21a469 1290
0f907de1 1291 if (ret < 0) {
7591bab1 1292 goto send_reply;
b8aa1682
JD
1293 }
1294
348a81dc
JG
1295 if (conform_channel_path(path_name)) {
1296 goto send_reply;
1297 }
1298
7591bab1 1299 trace = ctf_trace_get_by_path_or_create(session, path_name);
2a174661 1300 if (!trace) {
7591bab1 1301 goto send_reply;
2a174661 1302 }
7591bab1 1303 /* This stream here has one reference on the trace. */
2a174661 1304
7591bab1
MD
1305 pthread_mutex_lock(&last_relay_stream_id_lock);
1306 stream_handle = ++last_relay_stream_id;
1307 pthread_mutex_unlock(&last_relay_stream_id_lock);
d3e2ba59 1308
7591bab1
MD
1309 /* We pass ownership of path_name and channel_name. */
1310 stream = stream_create(trace, stream_handle, path_name,
348a81dc 1311 channel_name, tracefile_size, tracefile_count);
7591bab1
MD
1312 path_name = NULL;
1313 channel_name = NULL;
a4baae1b 1314
2a174661 1315 /*
7591bab1
MD
1316 * Streams are the owners of their trace. Reference to trace is
1317 * kept within stream_create().
2a174661 1318 */
7591bab1 1319 ctf_trace_put(trace);
d3e2ba59 1320
7591bab1 1321send_reply:
53efb85a 1322 memset(&reply, 0, sizeof(reply));
7591bab1
MD
1323 reply.handle = htobe64(stream_handle);
1324 if (!stream) {
f73fabfd 1325 reply.ret_code = htobe32(LTTNG_ERR_UNK);
b8aa1682 1326 } else {
f73fabfd 1327 reply.ret_code = htobe32(LTTNG_OK);
b8aa1682 1328 }
5af40280 1329
58eb9381 1330 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
b8aa1682 1331 sizeof(struct lttcomm_relayd_status_stream), 0);
5312a3ed
JG
1332 if (send_ret < (ssize_t) sizeof(reply)) {
1333 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1334 send_ret);
1335 ret = -1;
b8aa1682
JD
1336 }
1337
1338end_no_session:
7591bab1
MD
1339 free(path_name);
1340 free(channel_name);
0f907de1 1341 return ret;
b8aa1682
JD
1342}
1343
173af62f
DG
1344/*
1345 * relay_close_stream: close a specific stream
1346 */
5312a3ed
JG
1347static int relay_close_stream(const struct lttcomm_relayd_hdr *recv_hdr,
1348 struct relay_connection *conn,
1349 const struct lttng_buffer_view *payload)
173af62f 1350{
5312a3ed
JG
1351 int ret;
1352 ssize_t send_ret;
58eb9381 1353 struct relay_session *session = conn->session;
173af62f
DG
1354 struct lttcomm_relayd_close_stream stream_info;
1355 struct lttcomm_relayd_generic_reply reply;
1356 struct relay_stream *stream;
173af62f
DG
1357
1358 DBG("Close stream received");
1359
5312a3ed 1360 if (!session || !conn->version_check_done) {
173af62f
DG
1361 ERR("Trying to close a stream before version check");
1362 ret = -1;
1363 goto end_no_session;
1364 }
1365
5312a3ed
JG
1366 if (payload->size < sizeof(stream_info)) {
1367 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1368 sizeof(stream_info), payload->size);
173af62f
DG
1369 ret = -1;
1370 goto end_no_session;
1371 }
5312a3ed
JG
1372 memcpy(&stream_info, payload->data, sizeof(stream_info));
1373 stream_info.stream_id = be64toh(stream_info.stream_id);
1374 stream_info.last_net_seq_num = be64toh(stream_info.last_net_seq_num);
173af62f 1375
5312a3ed 1376 stream = stream_get_by_id(stream_info.stream_id);
173af62f
DG
1377 if (!stream) {
1378 ret = -1;
7591bab1 1379 goto end;
173af62f 1380 }
77f7bd85
MD
1381
1382 /*
1383 * Set last_net_seq_num before the close flag. Required by data
1384 * pending check.
1385 */
7591bab1 1386 pthread_mutex_lock(&stream->lock);
5312a3ed 1387 stream->last_net_seq_num = stream_info.last_net_seq_num;
77f7bd85
MD
1388 pthread_mutex_unlock(&stream->lock);
1389
bda7c7b9
JG
1390 /*
1391 * This is one of the conditions which may trigger a stream close
1392 * with the others being:
1393 * 1) A close command is received for a stream
1394 * 2) The control connection owning the stream is closed
1395 * 3) We have received all of the stream's data _after_ a close
1396 * request.
1397 */
1398 try_stream_close(stream);
7591bab1
MD
1399 if (stream->is_metadata) {
1400 struct relay_viewer_stream *vstream;
173af62f 1401
7591bab1
MD
1402 vstream = viewer_stream_get_by_id(stream->stream_handle);
1403 if (vstream) {
1404 if (vstream->metadata_sent == stream->metadata_received) {
1405 /*
1406 * Since all the metadata has been sent to the
1407 * viewer and that we have a request to close
1408 * its stream, we can safely teardown the
1409 * corresponding metadata viewer stream.
1410 */
1411 viewer_stream_put(vstream);
1412 }
1413 /* Put local reference. */
1414 viewer_stream_put(vstream);
1415 }
1416 }
7591bab1 1417 stream_put(stream);
5312a3ed 1418 ret = 0;
173af62f 1419
7591bab1 1420end:
53efb85a 1421 memset(&reply, 0, sizeof(reply));
173af62f 1422 if (ret < 0) {
f73fabfd 1423 reply.ret_code = htobe32(LTTNG_ERR_UNK);
173af62f 1424 } else {
f73fabfd 1425 reply.ret_code = htobe32(LTTNG_OK);
173af62f 1426 }
58eb9381 1427 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
173af62f 1428 sizeof(struct lttcomm_relayd_generic_reply), 0);
5312a3ed
JG
1429 if (send_ret < (ssize_t) sizeof(reply)) {
1430 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1431 send_ret);
1432 ret = -1;
173af62f
DG
1433 }
1434
1435end_no_session:
1436 return ret;
1437}
1438
93ec662e
JD
1439/*
1440 * relay_reset_metadata: reset a metadata stream
1441 */
1442static
5312a3ed
JG
1443int relay_reset_metadata(const struct lttcomm_relayd_hdr *recv_hdr,
1444 struct relay_connection *conn,
1445 const struct lttng_buffer_view *payload)
93ec662e 1446{
5312a3ed
JG
1447 int ret;
1448 ssize_t send_ret;
93ec662e
JD
1449 struct relay_session *session = conn->session;
1450 struct lttcomm_relayd_reset_metadata stream_info;
1451 struct lttcomm_relayd_generic_reply reply;
1452 struct relay_stream *stream;
1453
1454 DBG("Reset metadata received");
1455
5312a3ed 1456 if (!session || !conn->version_check_done) {
93ec662e
JD
1457 ERR("Trying to reset a metadata stream before version check");
1458 ret = -1;
1459 goto end_no_session;
1460 }
1461
5312a3ed
JG
1462 if (payload->size < sizeof(stream_info)) {
1463 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1464 sizeof(stream_info), payload->size);
93ec662e
JD
1465 ret = -1;
1466 goto end_no_session;
1467 }
5312a3ed
JG
1468 memcpy(&stream_info, payload->data, sizeof(stream_info));
1469 stream_info.stream_id = be64toh(stream_info.stream_id);
1470 stream_info.version = be64toh(stream_info.version);
1471
1472 DBG("Update metadata to version %" PRIu64, stream_info.version);
93ec662e
JD
1473
1474 /* Unsupported for live sessions for now. */
1475 if (session->live_timer != 0) {
1476 ret = -1;
1477 goto end;
1478 }
1479
5312a3ed 1480 stream = stream_get_by_id(stream_info.stream_id);
93ec662e
JD
1481 if (!stream) {
1482 ret = -1;
1483 goto end;
1484 }
1485 pthread_mutex_lock(&stream->lock);
1486 if (!stream->is_metadata) {
1487 ret = -1;
1488 goto end_unlock;
1489 }
1490
c35f9726 1491 ret = stream_reset_file(stream);
93ec662e 1492 if (ret < 0) {
c35f9726
JG
1493 ERR("Failed to reset metadata stream %" PRIu64
1494 ": stream_path = %s, channel = %s",
1495 stream->stream_handle, stream->path_name,
1496 stream->channel_name);
93ec662e
JD
1497 goto end_unlock;
1498 }
93ec662e
JD
1499end_unlock:
1500 pthread_mutex_unlock(&stream->lock);
1501 stream_put(stream);
1502
1503end:
1504 memset(&reply, 0, sizeof(reply));
1505 if (ret < 0) {
1506 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1507 } else {
1508 reply.ret_code = htobe32(LTTNG_OK);
1509 }
1510 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1511 sizeof(struct lttcomm_relayd_generic_reply), 0);
5312a3ed
JG
1512 if (send_ret < (ssize_t) sizeof(reply)) {
1513 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1514 send_ret);
1515 ret = -1;
93ec662e
JD
1516 }
1517
1518end_no_session:
1519 return ret;
1520}
1521
b8aa1682
JD
1522/*
1523 * relay_unknown_command: send -1 if received unknown command
1524 */
7591bab1 1525static void relay_unknown_command(struct relay_connection *conn)
b8aa1682
JD
1526{
1527 struct lttcomm_relayd_generic_reply reply;
5312a3ed 1528 ssize_t send_ret;
b8aa1682 1529
53efb85a 1530 memset(&reply, 0, sizeof(reply));
f73fabfd 1531 reply.ret_code = htobe32(LTTNG_ERR_UNK);
5312a3ed
JG
1532 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1533 if (send_ret < sizeof(reply)) {
1534 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret);
b8aa1682
JD
1535 }
1536}
1537
1538/*
1539 * relay_start: send an acknowledgment to the client to tell if we are
1540 * ready to receive data. We are ready if a session is established.
1541 */
5312a3ed
JG
1542static int relay_start(const struct lttcomm_relayd_hdr *recv_hdr,
1543 struct relay_connection *conn,
1544 const struct lttng_buffer_view *payload)
b8aa1682 1545{
5312a3ed
JG
1546 int ret = 0;
1547 ssize_t send_ret;
b8aa1682 1548 struct lttcomm_relayd_generic_reply reply;
58eb9381 1549 struct relay_session *session = conn->session;
b8aa1682
JD
1550
1551 if (!session) {
1552 DBG("Trying to start the streaming without a session established");
f73fabfd 1553 ret = htobe32(LTTNG_ERR_UNK);
b8aa1682
JD
1554 }
1555
53efb85a 1556 memset(&reply, 0, sizeof(reply));
5312a3ed
JG
1557 reply.ret_code = htobe32(LTTNG_OK);
1558 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1559 sizeof(reply), 0);
1560 if (send_ret < (ssize_t) sizeof(reply)) {
1561 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1562 send_ret);
1563 ret = -1;
b8aa1682
JD
1564 }
1565
1566 return ret;
1567}
1568
b8aa1682 1569/*
7591bab1 1570 * relay_recv_metadata: receive the metadata for the session.
b8aa1682 1571 */
5312a3ed
JG
1572static int relay_recv_metadata(const struct lttcomm_relayd_hdr *recv_hdr,
1573 struct relay_connection *conn,
1574 const struct lttng_buffer_view *payload)
b8aa1682 1575{
32d1569c 1576 int ret = 0;
58eb9381 1577 struct relay_session *session = conn->session;
5312a3ed 1578 struct lttcomm_relayd_metadata_payload metadata_payload_header;
b8aa1682 1579 struct relay_stream *metadata_stream;
5312a3ed 1580 uint64_t metadata_payload_size;
c35f9726 1581 struct lttng_buffer_view packet_view;
b8aa1682
JD
1582
1583 if (!session) {
1584 ERR("Metadata sent before version check");
1585 ret = -1;
1586 goto end;
1587 }
1588
5312a3ed 1589 if (recv_hdr->data_size < sizeof(struct lttcomm_relayd_metadata_payload)) {
f6416125
MD
1590 ERR("Incorrect data size");
1591 ret = -1;
1592 goto end;
1593 }
5312a3ed
JG
1594 metadata_payload_size = recv_hdr->data_size -
1595 sizeof(struct lttcomm_relayd_metadata_payload);
f6416125 1596
5312a3ed
JG
1597 memcpy(&metadata_payload_header, payload->data,
1598 sizeof(metadata_payload_header));
1599 metadata_payload_header.stream_id = be64toh(
1600 metadata_payload_header.stream_id);
1601 metadata_payload_header.padding_size = be32toh(
1602 metadata_payload_header.padding_size);
9d1bbf21 1603
5312a3ed 1604 metadata_stream = stream_get_by_id(metadata_payload_header.stream_id);
b8aa1682
JD
1605 if (!metadata_stream) {
1606 ret = -1;
7591bab1 1607 goto end;
b8aa1682
JD
1608 }
1609
c35f9726
JG
1610 packet_view = lttng_buffer_view_from_view(payload,
1611 sizeof(metadata_payload_header), metadata_payload_size);
1612 if (!packet_view.data) {
1613 ERR("Invalid metadata packet length announced by header");
b8aa1682 1614 ret = -1;
7591bab1 1615 goto end_put;
b8aa1682 1616 }
1d4dfdef 1617
c35f9726
JG
1618 pthread_mutex_lock(&metadata_stream->lock);
1619 ret = stream_write(metadata_stream, &packet_view,
5312a3ed 1620 metadata_payload_header.padding_size);
c35f9726
JG
1621 pthread_mutex_unlock(&metadata_stream->lock);
1622 if (ret){
5312a3ed 1623 ret = -1;
7591bab1 1624 goto end_put;
1d4dfdef 1625 }
7591bab1 1626end_put:
7591bab1 1627 stream_put(metadata_stream);
b8aa1682
JD
1628end:
1629 return ret;
1630}
1631
1632/*
1633 * relay_send_version: send relayd version number
1634 */
5312a3ed
JG
1635static int relay_send_version(const struct lttcomm_relayd_hdr *recv_hdr,
1636 struct relay_connection *conn,
1637 const struct lttng_buffer_view *payload)
b8aa1682 1638{
7f51dcba 1639 int ret;
5312a3ed 1640 ssize_t send_ret;
092b6259 1641 struct lttcomm_relayd_version reply, msg;
87cb6359 1642 bool compatible = true;
b8aa1682 1643
5312a3ed 1644 conn->version_check_done = true;
b8aa1682 1645
092b6259 1646 /* Get version from the other side. */
5312a3ed
JG
1647 if (payload->size < sizeof(msg)) {
1648 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1649 sizeof(msg), payload->size);
092b6259 1650 ret = -1;
092b6259
DG
1651 goto end;
1652 }
1653
5312a3ed
JG
1654 memcpy(&msg, payload->data, sizeof(msg));
1655 msg.major = be32toh(msg.major);
1656 msg.minor = be32toh(msg.minor);
1657
53efb85a 1658 memset(&reply, 0, sizeof(reply));
d83a952c
MD
1659 reply.major = RELAYD_VERSION_COMM_MAJOR;
1660 reply.minor = RELAYD_VERSION_COMM_MINOR;
d4519fa3
JD
1661
1662 /* Major versions must be the same */
5312a3ed 1663 if (reply.major != msg.major) {
6151a90f 1664 DBG("Incompatible major versions (%u vs %u), deleting session",
5312a3ed 1665 reply.major, msg.major);
87cb6359 1666 compatible = false;
d4519fa3
JD
1667 }
1668
58eb9381 1669 conn->major = reply.major;
0f907de1 1670 /* We adapt to the lowest compatible version */
5312a3ed 1671 if (reply.minor <= msg.minor) {
58eb9381 1672 conn->minor = reply.minor;
0f907de1 1673 } else {
5312a3ed 1674 conn->minor = msg.minor;
0f907de1
JD
1675 }
1676
6151a90f
JD
1677 reply.major = htobe32(reply.major);
1678 reply.minor = htobe32(reply.minor);
5312a3ed
JG
1679 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1680 sizeof(reply), 0);
1681 if (send_ret < (ssize_t) sizeof(reply)) {
1682 ERR("Failed to send \"send version\" command reply (ret = %zd)",
1683 send_ret);
1684 ret = -1;
1685 goto end;
1686 } else {
1687 ret = 0;
6151a90f
JD
1688 }
1689
87cb6359
JD
1690 if (!compatible) {
1691 ret = -1;
1692 goto end;
1693 }
1694
58eb9381
DG
1695 DBG("Version check done using protocol %u.%u", conn->major,
1696 conn->minor);
b8aa1682
JD
1697
1698end:
1699 return ret;
1700}
1701
c8f59ee5 1702/*
6d805429 1703 * Check for data pending for a given stream id from the session daemon.
c8f59ee5 1704 */
5312a3ed
JG
1705static int relay_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
1706 struct relay_connection *conn,
1707 const struct lttng_buffer_view *payload)
c8f59ee5 1708{
58eb9381 1709 struct relay_session *session = conn->session;
6d805429 1710 struct lttcomm_relayd_data_pending msg;
c8f59ee5
DG
1711 struct lttcomm_relayd_generic_reply reply;
1712 struct relay_stream *stream;
5312a3ed 1713 ssize_t send_ret;
c8f59ee5 1714 int ret;
298a25ca 1715 uint64_t stream_seq;
c8f59ee5 1716
6d805429 1717 DBG("Data pending command received");
c8f59ee5 1718
5312a3ed 1719 if (!session || !conn->version_check_done) {
c8f59ee5
DG
1720 ERR("Trying to check for data before version check");
1721 ret = -1;
1722 goto end_no_session;
1723 }
1724
5312a3ed
JG
1725 if (payload->size < sizeof(msg)) {
1726 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
1727 sizeof(msg), payload->size);
c8f59ee5
DG
1728 ret = -1;
1729 goto end_no_session;
1730 }
5312a3ed
JG
1731 memcpy(&msg, payload->data, sizeof(msg));
1732 msg.stream_id = be64toh(msg.stream_id);
1733 msg.last_net_seq_num = be64toh(msg.last_net_seq_num);
c8f59ee5 1734
5312a3ed 1735 stream = stream_get_by_id(msg.stream_id);
de91f48a 1736 if (stream == NULL) {
c8f59ee5 1737 ret = -1;
7591bab1 1738 goto end;
c8f59ee5
DG
1739 }
1740
7591bab1
MD
1741 pthread_mutex_lock(&stream->lock);
1742
298a25ca
JG
1743 if (session_streams_have_index(session)) {
1744 /*
1745 * Ensure that both the index and stream data have been
1746 * flushed up to the requested point.
1747 */
a8f9f353 1748 stream_seq = min(stream->prev_data_seq, stream->prev_index_seq);
298a25ca 1749 } else {
a8f9f353 1750 stream_seq = stream->prev_data_seq;
298a25ca 1751 }
a8f9f353 1752 DBG("Data pending for stream id %" PRIu64 ": prev_data_seq %" PRIu64
298a25ca
JG
1753 ", prev_index_seq %" PRIu64
1754 ", and last_seq %" PRIu64, msg.stream_id,
a8f9f353 1755 stream->prev_data_seq, stream->prev_index_seq,
298a25ca 1756 msg.last_net_seq_num);
c8f59ee5 1757
33832e64 1758 /* Avoid wrapping issue */
298a25ca 1759 if (((int64_t) (stream_seq - msg.last_net_seq_num)) >= 0) {
6d805429 1760 /* Data has in fact been written and is NOT pending */
c8f59ee5 1761 ret = 0;
6d805429
DG
1762 } else {
1763 /* Data still being streamed thus pending */
1764 ret = 1;
c8f59ee5
DG
1765 }
1766
7591bab1
MD
1767 stream->data_pending_check_done = true;
1768 pthread_mutex_unlock(&stream->lock);
f7079f67 1769
7591bab1
MD
1770 stream_put(stream);
1771end:
c8f59ee5 1772
53efb85a 1773 memset(&reply, 0, sizeof(reply));
c8f59ee5 1774 reply.ret_code = htobe32(ret);
5312a3ed
JG
1775 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1776 if (send_ret < (ssize_t) sizeof(reply)) {
1777 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
1778 send_ret);
1779 ret = -1;
c8f59ee5
DG
1780 }
1781
1782end_no_session:
1783 return ret;
1784}
1785
1786/*
1787 * Wait for the control socket to reach a quiescent state.
1788 *
7591bab1
MD
1789 * Note that for now, when receiving this command from the session
1790 * daemon, this means that every subsequent commands or data received on
1791 * the control socket has been handled. So, this is why we simply return
1792 * OK here.
c8f59ee5 1793 */
5312a3ed
JG
1794static int relay_quiescent_control(const struct lttcomm_relayd_hdr *recv_hdr,
1795 struct relay_connection *conn,
1796 const struct lttng_buffer_view *payload)
c8f59ee5
DG
1797{
1798 int ret;
5312a3ed 1799 ssize_t send_ret;
ad7051c0 1800 struct relay_stream *stream;
ad7051c0 1801 struct lttcomm_relayd_quiescent_control msg;
c8f59ee5
DG
1802 struct lttcomm_relayd_generic_reply reply;
1803
1804 DBG("Checking quiescent state on control socket");
1805
5312a3ed 1806 if (!conn->session || !conn->version_check_done) {
ad7051c0
DG
1807 ERR("Trying to check for data before version check");
1808 ret = -1;
1809 goto end_no_session;
1810 }
1811
5312a3ed
JG
1812 if (payload->size < sizeof(msg)) {
1813 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
1814 sizeof(msg), payload->size);
ad7051c0
DG
1815 ret = -1;
1816 goto end_no_session;
1817 }
5312a3ed
JG
1818 memcpy(&msg, payload->data, sizeof(msg));
1819 msg.stream_id = be64toh(msg.stream_id);
ad7051c0 1820
5312a3ed 1821 stream = stream_get_by_id(msg.stream_id);
7591bab1
MD
1822 if (!stream) {
1823 goto reply;
1824 }
1825 pthread_mutex_lock(&stream->lock);
1826 stream->data_pending_check_done = true;
1827 pthread_mutex_unlock(&stream->lock);
5312a3ed
JG
1828
1829 DBG("Relay quiescent control pending flag set to %" PRIu64, msg.stream_id);
7591bab1
MD
1830 stream_put(stream);
1831reply:
53efb85a 1832 memset(&reply, 0, sizeof(reply));
c8f59ee5 1833 reply.ret_code = htobe32(LTTNG_OK);
5312a3ed
JG
1834 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1835 if (send_ret < (ssize_t) sizeof(reply)) {
1836 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
1837 send_ret);
1838 ret = -1;
1839 } else {
1840 ret = 0;
c8f59ee5
DG
1841 }
1842
ad7051c0 1843end_no_session:
c8f59ee5
DG
1844 return ret;
1845}
1846
f7079f67 1847/*
7591bab1
MD
1848 * Initialize a data pending command. This means that a consumer is about
1849 * to ask for data pending for each stream it holds. Simply iterate over
1850 * all streams of a session and set the data_pending_check_done flag.
f7079f67
DG
1851 *
1852 * This command returns to the client a LTTNG_OK code.
1853 */
5312a3ed
JG
1854static int relay_begin_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
1855 struct relay_connection *conn,
1856 const struct lttng_buffer_view *payload)
f7079f67
DG
1857{
1858 int ret;
5312a3ed 1859 ssize_t send_ret;
f7079f67
DG
1860 struct lttng_ht_iter iter;
1861 struct lttcomm_relayd_begin_data_pending msg;
1862 struct lttcomm_relayd_generic_reply reply;
1863 struct relay_stream *stream;
f7079f67
DG
1864
1865 assert(recv_hdr);
58eb9381 1866 assert(conn);
f7079f67
DG
1867
1868 DBG("Init streams for data pending");
1869
5312a3ed 1870 if (!conn->session || !conn->version_check_done) {
f7079f67
DG
1871 ERR("Trying to check for data before version check");
1872 ret = -1;
1873 goto end_no_session;
1874 }
1875
5312a3ed
JG
1876 if (payload->size < sizeof(msg)) {
1877 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
1878 sizeof(msg), payload->size);
f7079f67
DG
1879 ret = -1;
1880 goto end_no_session;
1881 }
5312a3ed
JG
1882 memcpy(&msg, payload->data, sizeof(msg));
1883 msg.session_id = be64toh(msg.session_id);
f7079f67
DG
1884
1885 /*
7591bab1
MD
1886 * Iterate over all streams to set the begin data pending flag.
1887 * For now, the streams are indexed by stream handle so we have
1888 * to iterate over all streams to find the one associated with
1889 * the right session_id.
f7079f67
DG
1890 */
1891 rcu_read_lock();
d3e2ba59 1892 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2a174661 1893 node.node) {
7591bab1
MD
1894 if (!stream_get(stream)) {
1895 continue;
1896 }
5312a3ed 1897 if (stream->trace->session->id == msg.session_id) {
7591bab1
MD
1898 pthread_mutex_lock(&stream->lock);
1899 stream->data_pending_check_done = false;
1900 pthread_mutex_unlock(&stream->lock);
f7079f67
DG
1901 DBG("Set begin data pending flag to stream %" PRIu64,
1902 stream->stream_handle);
1903 }
7591bab1 1904 stream_put(stream);
f7079f67
DG
1905 }
1906 rcu_read_unlock();
1907
53efb85a 1908 memset(&reply, 0, sizeof(reply));
f7079f67
DG
1909 /* All good, send back reply. */
1910 reply.ret_code = htobe32(LTTNG_OK);
1911
5312a3ed
JG
1912 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1913 if (send_ret < (ssize_t) sizeof(reply)) {
1914 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
1915 send_ret);
1916 ret = -1;
1917 } else {
1918 ret = 0;
f7079f67
DG
1919 }
1920
1921end_no_session:
1922 return ret;
1923}
1924
1925/*
7591bab1
MD
1926 * End data pending command. This will check, for a given session id, if
1927 * each stream associated with it has its data_pending_check_done flag
1928 * set. If not, this means that the client lost track of the stream but
1929 * the data is still being streamed on our side. In this case, we inform
1930 * the client that data is in flight.
f7079f67
DG
1931 *
1932 * Return to the client if there is data in flight or not with a ret_code.
1933 */
5312a3ed
JG
1934static int relay_end_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
1935 struct relay_connection *conn,
1936 const struct lttng_buffer_view *payload)
f7079f67
DG
1937{
1938 int ret;
5312a3ed 1939 ssize_t send_ret;
f7079f67
DG
1940 struct lttng_ht_iter iter;
1941 struct lttcomm_relayd_end_data_pending msg;
1942 struct lttcomm_relayd_generic_reply reply;
1943 struct relay_stream *stream;
f7079f67
DG
1944 uint32_t is_data_inflight = 0;
1945
f7079f67
DG
1946 DBG("End data pending command");
1947
5312a3ed 1948 if (!conn->session || !conn->version_check_done) {
f7079f67
DG
1949 ERR("Trying to check for data before version check");
1950 ret = -1;
1951 goto end_no_session;
1952 }
1953
5312a3ed
JG
1954 if (payload->size < sizeof(msg)) {
1955 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
1956 sizeof(msg), payload->size);
f7079f67
DG
1957 ret = -1;
1958 goto end_no_session;
1959 }
5312a3ed
JG
1960 memcpy(&msg, payload->data, sizeof(msg));
1961 msg.session_id = be64toh(msg.session_id);
f7079f67 1962
7591bab1
MD
1963 /*
1964 * Iterate over all streams to see if the begin data pending
1965 * flag is set.
1966 */
f7079f67 1967 rcu_read_lock();
d3e2ba59 1968 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2a174661 1969 node.node) {
7591bab1
MD
1970 if (!stream_get(stream)) {
1971 continue;
1972 }
5312a3ed 1973 if (stream->trace->session->id != msg.session_id) {
7591bab1
MD
1974 stream_put(stream);
1975 continue;
1976 }
1977 pthread_mutex_lock(&stream->lock);
1978 if (!stream->data_pending_check_done) {
298a25ca
JG
1979 uint64_t stream_seq;
1980
1981 if (session_streams_have_index(conn->session)) {
1982 /*
1983 * Ensure that both the index and stream data have been
1984 * flushed up to the requested point.
1985 */
a8f9f353 1986 stream_seq = min(stream->prev_data_seq, stream->prev_index_seq);
298a25ca 1987 } else {
a8f9f353 1988 stream_seq = stream->prev_data_seq;
298a25ca
JG
1989 }
1990 if (!stream->closed || !(((int64_t) (stream_seq - stream->last_net_seq_num)) >= 0)) {
7591bab1
MD
1991 is_data_inflight = 1;
1992 DBG("Data is still in flight for stream %" PRIu64,
1993 stream->stream_handle);
1994 pthread_mutex_unlock(&stream->lock);
1995 stream_put(stream);
1996 break;
1997 }
f7079f67 1998 }
7591bab1
MD
1999 pthread_mutex_unlock(&stream->lock);
2000 stream_put(stream);
f7079f67
DG
2001 }
2002 rcu_read_unlock();
2003
53efb85a 2004 memset(&reply, 0, sizeof(reply));
f7079f67
DG
2005 /* All good, send back reply. */
2006 reply.ret_code = htobe32(is_data_inflight);
2007
5312a3ed
JG
2008 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2009 if (send_ret < (ssize_t) sizeof(reply)) {
2010 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2011 send_ret);
2012 ret = -1;
2013 } else {
2014 ret = 0;
f7079f67
DG
2015 }
2016
2017end_no_session:
2018 return ret;
2019}
2020
1c20f0e2
JD
2021/*
2022 * Receive an index for a specific stream.
2023 *
2024 * Return 0 on success else a negative value.
2025 */
5312a3ed
JG
2026static int relay_recv_index(const struct lttcomm_relayd_hdr *recv_hdr,
2027 struct relay_connection *conn,
2028 const struct lttng_buffer_view *payload)
1c20f0e2 2029{
5312a3ed
JG
2030 int ret;
2031 ssize_t send_ret;
58eb9381 2032 struct relay_session *session = conn->session;
1c20f0e2 2033 struct lttcomm_relayd_index index_info;
1c20f0e2
JD
2034 struct lttcomm_relayd_generic_reply reply;
2035 struct relay_stream *stream;
f8f3885c 2036 size_t msg_len;
1c20f0e2 2037
58eb9381 2038 assert(conn);
1c20f0e2
JD
2039
2040 DBG("Relay receiving index");
2041
5312a3ed 2042 if (!session || !conn->version_check_done) {
1c20f0e2
JD
2043 ERR("Trying to close a stream before version check");
2044 ret = -1;
2045 goto end_no_session;
2046 }
2047
f8f3885c
MD
2048 msg_len = lttcomm_relayd_index_len(
2049 lttng_to_index_major(conn->major, conn->minor),
2050 lttng_to_index_minor(conn->major, conn->minor));
5312a3ed
JG
2051 if (payload->size < msg_len) {
2052 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2053 msg_len, payload->size);
1c20f0e2
JD
2054 ret = -1;
2055 goto end_no_session;
2056 }
5312a3ed
JG
2057 memcpy(&index_info, payload->data, msg_len);
2058 index_info.relay_stream_id = be64toh(index_info.relay_stream_id);
2059 index_info.net_seq_num = be64toh(index_info.net_seq_num);
2060 index_info.packet_size = be64toh(index_info.packet_size);
2061 index_info.content_size = be64toh(index_info.content_size);
2062 index_info.timestamp_begin = be64toh(index_info.timestamp_begin);
2063 index_info.timestamp_end = be64toh(index_info.timestamp_end);
2064 index_info.events_discarded = be64toh(index_info.events_discarded);
2065 index_info.stream_id = be64toh(index_info.stream_id);
81df238b
JR
2066
2067 if (conn->minor >= 8) {
2068 index_info.stream_instance_id =
2069 be64toh(index_info.stream_instance_id);
2070 index_info.packet_seq_num = be64toh(index_info.packet_seq_num);
2071 }
5312a3ed
JG
2072
2073 stream = stream_get_by_id(index_info.relay_stream_id);
1c20f0e2 2074 if (!stream) {
7591bab1 2075 ERR("stream_get_by_id not found");
1c20f0e2 2076 ret = -1;
7591bab1 2077 goto end;
1c20f0e2 2078 }
d3e2ba59 2079
c35f9726
JG
2080 pthread_mutex_lock(&stream->lock);
2081 ret = stream_add_index(stream, &index_info);
2082 pthread_mutex_unlock(&stream->lock);
2083 if (ret) {
7591bab1
MD
2084 goto end_stream_put;
2085 }
1c20f0e2 2086
7591bab1 2087end_stream_put:
7591bab1 2088 stream_put(stream);
7591bab1 2089end:
53efb85a 2090 memset(&reply, 0, sizeof(reply));
1c20f0e2
JD
2091 if (ret < 0) {
2092 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2093 } else {
2094 reply.ret_code = htobe32(LTTNG_OK);
2095 }
58eb9381 2096 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
5312a3ed
JG
2097 if (send_ret < (ssize_t) sizeof(reply)) {
2098 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret);
2099 ret = -1;
1c20f0e2
JD
2100 }
2101
2102end_no_session:
2103 return ret;
2104}
2105
a4baae1b
JD
2106/*
2107 * Receive the streams_sent message.
2108 *
2109 * Return 0 on success else a negative value.
2110 */
5312a3ed
JG
2111static int relay_streams_sent(const struct lttcomm_relayd_hdr *recv_hdr,
2112 struct relay_connection *conn,
2113 const struct lttng_buffer_view *payload)
a4baae1b 2114{
5312a3ed
JG
2115 int ret;
2116 ssize_t send_ret;
a4baae1b
JD
2117 struct lttcomm_relayd_generic_reply reply;
2118
58eb9381 2119 assert(conn);
a4baae1b
JD
2120
2121 DBG("Relay receiving streams_sent");
2122
5312a3ed 2123 if (!conn->session || !conn->version_check_done) {
a4baae1b
JD
2124 ERR("Trying to close a stream before version check");
2125 ret = -1;
2126 goto end_no_session;
2127 }
2128
2129 /*
7591bab1
MD
2130 * Publish every pending stream in the connection recv list which are
2131 * now ready to be used by the viewer.
4a9daf17 2132 */
7591bab1 2133 publish_connection_local_streams(conn);
4a9daf17 2134
53efb85a 2135 memset(&reply, 0, sizeof(reply));
a4baae1b 2136 reply.ret_code = htobe32(LTTNG_OK);
58eb9381 2137 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
5312a3ed
JG
2138 if (send_ret < (ssize_t) sizeof(reply)) {
2139 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2140 send_ret);
2141 ret = -1;
a4baae1b
JD
2142 } else {
2143 /* Success. */
2144 ret = 0;
2145 }
2146
2147end_no_session:
2148 return ret;
2149}
2150
d3ecc550 2151/*
c35f9726
JG
2152 * relay_rotate_session_stream: rotate a stream to a new tracefile for the
2153 * session rotation feature (not the tracefile rotation feature).
d3ecc550 2154 */
c35f9726
JG
2155static int relay_rotate_session_streams(
2156 const struct lttcomm_relayd_hdr *recv_hdr,
5312a3ed
JG
2157 struct relay_connection *conn,
2158 const struct lttng_buffer_view *payload)
d3ecc550 2159{
30b9d5ab 2160 int ret = 0;
c35f9726 2161 uint32_t i;
5312a3ed 2162 ssize_t send_ret;
c35f9726 2163 enum lttng_error_code reply_code = LTTNG_ERR_UNK;
d3ecc550 2164 struct relay_session *session = conn->session;
c35f9726
JG
2165 struct lttcomm_relayd_rotate_streams rotate_streams;
2166 struct lttcomm_relayd_generic_reply reply = {};
2167 struct relay_stream *stream = NULL;
2168 const size_t header_len = sizeof(struct lttcomm_relayd_rotate_streams);
2169 struct lttng_trace_chunk *next_trace_chunk = NULL;
2170 struct lttng_buffer_view stream_positions;
70626904
JG
2171 char chunk_id_buf[MAX_INT_DEC_LEN(uint64_t)];
2172 const char *chunk_id_str = "none";
d3ecc550 2173
d3ecc550
JD
2174 if (!session || !conn->version_check_done) {
2175 ERR("Trying to rotate a stream before version check");
2176 ret = -1;
2177 goto end_no_reply;
2178 }
2179
2180 if (session->major == 2 && session->minor < 11) {
2181 ERR("Unsupported feature before 2.11");
2182 ret = -1;
2183 goto end_no_reply;
2184 }
2185
5312a3ed
JG
2186 if (payload->size < header_len) {
2187 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2188 header_len, payload->size);
d3ecc550
JD
2189 ret = -1;
2190 goto end_no_reply;
2191 }
2192
c35f9726 2193 memcpy(&rotate_streams, payload->data, header_len);
5312a3ed 2194
c35f9726
JG
2195 /* Convert header to host endianness. */
2196 rotate_streams = (typeof(rotate_streams)) {
2197 .stream_count = be32toh(rotate_streams.stream_count),
2198 .new_chunk_id = (typeof(rotate_streams.new_chunk_id)) {
2199 .is_set = !!rotate_streams.new_chunk_id.is_set,
2200 .value = be64toh(rotate_streams.new_chunk_id.value),
2201 }
2202 };
d3ecc550 2203
c35f9726
JG
2204 if (rotate_streams.new_chunk_id.is_set) {
2205 /*
2206 * Retrieve the trace chunk the stream must transition to. As
2207 * per the protocol, this chunk should have been created
2208 * before this command is received.
2209 */
2210 next_trace_chunk = sessiond_trace_chunk_registry_get_chunk(
2211 sessiond_trace_chunk_registry,
2212 session->sessiond_uuid, session->id,
2213 rotate_streams.new_chunk_id.value);
2214 if (!next_trace_chunk) {
2215 char uuid_str[UUID_STR_LEN];
2216
2217 lttng_uuid_to_str(session->sessiond_uuid, uuid_str);
2218 ERR("Unknown next trace chunk in ROTATE_STREAMS command: sessiond_uuid = {%s}, session_id = %" PRIu64
2219 ", trace_chunk_id = %" PRIu64,
2220 uuid_str, session->id,
2221 rotate_streams.new_chunk_id.value);
2222 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2223 ret = -1;
2224 goto end;
2225 }
70626904
JG
2226
2227 ret = snprintf(chunk_id_buf, sizeof(chunk_id_buf), "%" PRIu64,
2228 rotate_streams.new_chunk_id.value);
2229 if (ret < 0 || ret >= sizeof(chunk_id_buf)) {
2230 chunk_id_str = "formatting error";
2231 } else {
2232 chunk_id_str = chunk_id_buf;
2233 }
ecd1a12f 2234 session->has_rotated = true;
d3ecc550
JD
2235 }
2236
70626904
JG
2237 DBG("Rotate %" PRIu32 " streams of session \"%s\" to chunk \"%s\"",
2238 rotate_streams.stream_count, session->session_name,
2239 chunk_id_str);
2240
c35f9726
JG
2241 stream_positions = lttng_buffer_view_from_view(payload,
2242 sizeof(rotate_streams), -1);
2243 if (!stream_positions.data ||
2244 stream_positions.size <
2245 (rotate_streams.stream_count *
2246 sizeof(struct lttcomm_relayd_stream_rotation_position))) {
2247 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
d3ecc550 2248 ret = -1;
5312a3ed 2249 goto end;
d3ecc550
JD
2250 }
2251
c35f9726
JG
2252 for (i = 0; i < rotate_streams.stream_count; i++) {
2253 struct lttcomm_relayd_stream_rotation_position *position_comm =
2254 &((typeof(position_comm)) stream_positions.data)[i];
2255 const struct lttcomm_relayd_stream_rotation_position pos = {
2256 .stream_id = be64toh(position_comm->stream_id),
2257 .rotate_at_seq_num = be64toh(
2258 position_comm->rotate_at_seq_num),
2259 };
5312a3ed 2260
c35f9726
JG
2261 stream = stream_get_by_id(pos.stream_id);
2262 if (!stream) {
2263 reply_code = LTTNG_ERR_INVALID;
2264 ret = -1;
2265 goto end;
c6db3843
JG
2266 }
2267
c35f9726
JG
2268 pthread_mutex_lock(&stream->lock);
2269 ret = stream_set_pending_rotation(stream, next_trace_chunk,
2270 pos.rotate_at_seq_num);
2271 pthread_mutex_unlock(&stream->lock);
2272 if (ret) {
2273 reply_code = LTTNG_ERR_FILE_CREATION_ERROR;
2274 goto end;
c6db3843 2275 }
c35f9726
JG
2276
2277 stream_put(stream);
2278 stream = NULL;
d3ecc550
JD
2279 }
2280
c35f9726 2281 reply_code = LTTNG_OK;
d3ecc550 2282end:
c35f9726
JG
2283 if (stream) {
2284 stream_put(stream);
d3ecc550 2285 }
c35f9726
JG
2286
2287 reply.ret_code = htobe32((uint32_t) reply_code);
d3ecc550
JD
2288 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
2289 sizeof(struct lttcomm_relayd_generic_reply), 0);
5312a3ed
JG
2290 if (send_ret < (ssize_t) sizeof(reply)) {
2291 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2292 send_ret);
2293 ret = -1;
d3ecc550
JD
2294 }
2295
2fdaeb7e 2296 ret = 0;
d3ecc550 2297end_no_reply:
c35f9726 2298 lttng_trace_chunk_put(next_trace_chunk);
d3ecc550
JD
2299 return ret;
2300}
2301
e5add6d0 2302
e5add6d0
JG
2303
2304/*
2305 * relay_create_trace_chunk: create a new trace chunk
2306 */
2307static int relay_create_trace_chunk(const struct lttcomm_relayd_hdr *recv_hdr,
2308 struct relay_connection *conn,
2309 const struct lttng_buffer_view *payload)
2310{
2311 int ret = 0;
2312 ssize_t send_ret;
2313 struct relay_session *session = conn->session;
2314 struct lttcomm_relayd_create_trace_chunk *msg;
2315 struct lttcomm_relayd_generic_reply reply = {};
2316 struct lttng_buffer_view header_view;
2317 struct lttng_buffer_view chunk_name_view;
2318 struct lttng_trace_chunk *chunk = NULL, *published_chunk = NULL;
2319 enum lttng_error_code reply_code = LTTNG_OK;
2320 enum lttng_trace_chunk_status chunk_status;
2321 struct lttng_directory_handle session_output;
2322
2323 if (!session || !conn->version_check_done) {
2324 ERR("Trying to create a trace chunk before version check");
2325 ret = -1;
2326 goto end_no_reply;
2327 }
2328
2329 if (session->major == 2 && session->minor < 11) {
2330 ERR("Chunk creation command is unsupported before 2.11");
2331 ret = -1;
2332 goto end_no_reply;
2333 }
2334
2335 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
2336 if (!header_view.data) {
2337 ERR("Failed to receive payload of chunk creation command");
2338 ret = -1;
2339 goto end_no_reply;
2340 }
2341
2342 /* Convert to host endianness. */
2343 msg = (typeof(msg)) header_view.data;
2344 msg->chunk_id = be64toh(msg->chunk_id);
2345 msg->creation_timestamp = be64toh(msg->creation_timestamp);
2346 msg->override_name_length = be32toh(msg->override_name_length);
2347
2348 chunk = lttng_trace_chunk_create(
2349 msg->chunk_id, msg->creation_timestamp);
2350 if (!chunk) {
2351 ERR("Failed to create trace chunk in trace chunk creation command");
2352 ret = -1;
2353 reply_code = LTTNG_ERR_NOMEM;
2354 goto end;
2355 }
2356
2357 if (msg->override_name_length) {
2358 const char *name;
2359
2360 chunk_name_view = lttng_buffer_view_from_view(payload,
2361 sizeof(*msg),
2362 msg->override_name_length);
2363 name = chunk_name_view.data;
2364 if (!name || name[msg->override_name_length - 1]) {
2365 ERR("Failed to receive payload of chunk creation command");
2366 ret = -1;
2367 reply_code = LTTNG_ERR_INVALID;
2368 goto end;
2369 }
2370
2371 chunk_status = lttng_trace_chunk_override_name(
2372 chunk, chunk_name_view.data);
2373 switch (chunk_status) {
2374 case LTTNG_TRACE_CHUNK_STATUS_OK:
2375 break;
2376 case LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT:
2377 ERR("Failed to set the name of new trace chunk in trace chunk creation command (invalid name)");
2378 reply_code = LTTNG_ERR_INVALID;
2379 ret = -1;
2380 goto end;
2381 default:
2382 ERR("Failed to set the name of new trace chunk in trace chunk creation command (unknown error)");
2383 reply_code = LTTNG_ERR_UNK;
2384 ret = -1;
2385 goto end;
2386 }
2387 }
2388
d37856b8 2389 ret = session_init_output_directory_handle(
e5add6d0
JG
2390 conn->session, &session_output);
2391 if (ret) {
2392 reply_code = LTTNG_ERR_CREATE_DIR_FAIL;
2393 goto end;
2394 }
2395
2396 chunk_status = lttng_trace_chunk_set_credentials_current_user(chunk);
2397 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2398 reply_code = LTTNG_ERR_UNK;
2399 ret = -1;
2400 goto end;
2401 }
2402
2403 chunk_status = lttng_trace_chunk_set_as_owner(chunk, &session_output);
2404 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2405 reply_code = LTTNG_ERR_UNK;
2406 ret = -1;
2407 goto end;
2408 }
2409
2410 published_chunk = sessiond_trace_chunk_registry_publish_chunk(
2411 sessiond_trace_chunk_registry,
2412 conn->session->sessiond_uuid,
2413 conn->session->id,
2414 chunk);
2415 if (!published_chunk) {
2416 char uuid_str[UUID_STR_LEN];
2417
2418 lttng_uuid_to_str(conn->session->sessiond_uuid, uuid_str);
2419 ERR("Failed to publish chunk: sessiond_uuid = %s, session_id = %" PRIu64 ", chunk_id = %" PRIu64,
2420 uuid_str,
2421 conn->session->id,
2422 msg->chunk_id);
2423 ret = -1;
2424 reply_code = LTTNG_ERR_NOMEM;
2425 goto end;
2426 }
2427
2428 pthread_mutex_lock(&conn->session->lock);
62bad3bf
JG
2429 if (conn->session->pending_closure_trace_chunk) {
2430 /*
2431 * Invalid; this means a second create_trace_chunk command was
2432 * received before a close_trace_chunk.
2433 */
2434 ERR("Invalid trace chunk close command received; a trace chunk is already waiting for a trace chunk close command");
2435 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2436 ret = -1;
2437 goto end_unlock_session;
2438 }
2439 conn->session->pending_closure_trace_chunk =
2440 conn->session->current_trace_chunk;
e5add6d0 2441 conn->session->current_trace_chunk = published_chunk;
e5add6d0 2442 published_chunk = NULL;
62bad3bf 2443end_unlock_session:
c35f9726 2444 pthread_mutex_unlock(&conn->session->lock);
e5add6d0
JG
2445end:
2446 reply.ret_code = htobe32((uint32_t) reply_code);
2447 send_ret = conn->sock->ops->sendmsg(conn->sock,
2448 &reply,
2449 sizeof(struct lttcomm_relayd_generic_reply),
2450 0);
2451 if (send_ret < (ssize_t) sizeof(reply)) {
2452 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
2453 send_ret);
2454 ret = -1;
2455 }
2456end_no_reply:
2457 lttng_trace_chunk_put(chunk);
2458 lttng_trace_chunk_put(published_chunk);
2459 lttng_directory_handle_fini(&session_output);
2460 return ret;
2461}
2462
bbc4768c
JG
2463/*
2464 * relay_close_trace_chunk: close a trace chunk
2465 */
2466static int relay_close_trace_chunk(const struct lttcomm_relayd_hdr *recv_hdr,
2467 struct relay_connection *conn,
2468 const struct lttng_buffer_view *payload)
2469{
2470 int ret = 0;
2471 ssize_t send_ret;
2472 struct relay_session *session = conn->session;
2473 struct lttcomm_relayd_close_trace_chunk *msg;
ecd1a12f 2474 struct lttcomm_relayd_close_trace_chunk_reply reply = {};
bbc4768c
JG
2475 struct lttng_buffer_view header_view;
2476 struct lttng_trace_chunk *chunk = NULL;
2477 enum lttng_error_code reply_code = LTTNG_OK;
2478 enum lttng_trace_chunk_status chunk_status;
2479 uint64_t chunk_id;
c35f9726 2480 LTTNG_OPTIONAL(enum lttng_trace_chunk_command_type) close_command = {};
bbc4768c 2481 time_t close_timestamp;
ecd1a12f
MD
2482 char closed_trace_chunk_path[LTTNG_PATH_MAX];
2483 size_t path_length = 0;
2484 const char *chunk_name = NULL;
2485 struct lttng_dynamic_buffer reply_payload;
2486
2487 lttng_dynamic_buffer_init(&reply_payload);
bbc4768c
JG
2488
2489 if (!session || !conn->version_check_done) {
2490 ERR("Trying to close a trace chunk before version check");
2491 ret = -1;
2492 goto end_no_reply;
2493 }
2494
2495 if (session->major == 2 && session->minor < 11) {
2496 ERR("Chunk close command is unsupported before 2.11");
2497 ret = -1;
2498 goto end_no_reply;
2499 }
2500
2501 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
2502 if (!header_view.data) {
2503 ERR("Failed to receive payload of chunk close command");
2504 ret = -1;
2505 goto end_no_reply;
2506 }
2507
2508 /* Convert to host endianness. */
2509 msg = (typeof(msg)) header_view.data;
2510 chunk_id = be64toh(msg->chunk_id);
2511 close_timestamp = (time_t) be64toh(msg->close_timestamp);
2512 close_command = (typeof(close_command)){
2513 .value = be32toh(msg->close_command.value),
2514 .is_set = msg->close_command.is_set,
2515 };
2516
2517 chunk = sessiond_trace_chunk_registry_get_chunk(
2518 sessiond_trace_chunk_registry,
2519 conn->session->sessiond_uuid,
2520 conn->session->id,
2521 chunk_id);
2522 if (!chunk) {
2523 char uuid_str[UUID_STR_LEN];
2524
2525 lttng_uuid_to_str(conn->session->sessiond_uuid, uuid_str);
2526 ERR("Failed to find chunk to close: sessiond_uuid = %s, session_id = %" PRIu64 ", chunk_id = %" PRIu64,
2527 uuid_str,
2528 conn->session->id,
2529 msg->chunk_id);
2530 ret = -1;
2531 reply_code = LTTNG_ERR_NOMEM;
2532 goto end;
2533 }
2534
62bad3bf
JG
2535 pthread_mutex_lock(&session->lock);
2536 if (session->pending_closure_trace_chunk &&
2537 session->pending_closure_trace_chunk != chunk) {
2538 ERR("Trace chunk close command for session \"%s\" does not target the trace chunk pending closure",
2539 session->session_name);
2540 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2541 ret = -1;
2542 goto end_unlock_session;
2543 }
2544
bbc4768c
JG
2545 chunk_status = lttng_trace_chunk_set_close_timestamp(
2546 chunk, close_timestamp);
2547 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2548 ERR("Failed to set trace chunk close timestamp");
2549 ret = -1;
2550 reply_code = LTTNG_ERR_UNK;
62bad3bf 2551 goto end_unlock_session;
bbc4768c
JG
2552 }
2553
2554 if (close_command.is_set) {
2555 chunk_status = lttng_trace_chunk_set_close_command(
2556 chunk, close_command.value);
2557 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2558 ret = -1;
2559 reply_code = LTTNG_ERR_INVALID;
62bad3bf 2560 goto end_unlock_session;
bbc4768c
JG
2561 }
2562 }
ecd1a12f
MD
2563 chunk_status = lttng_trace_chunk_get_name(chunk, &chunk_name, NULL);
2564 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2565 ERR("Failed to get chunk name");
2566 ret = -1;
2567 reply_code = LTTNG_ERR_UNK;
2568 goto end_unlock_session;
2569 }
2570 if (!session->has_rotated && !session->snapshot) {
2571 ret = lttng_strncpy(closed_trace_chunk_path,
2572 session->output_path,
2573 sizeof(closed_trace_chunk_path));
2574 if (ret) {
2575 ERR("Failed to send trace chunk path: path length of %zu bytes exceeds the maximal allowed length of %zu bytes",
2576 strlen(session->output_path),
2577 sizeof(closed_trace_chunk_path));
2578 reply_code = LTTNG_ERR_NOMEM;
2579 ret = -1;
2580 goto end_unlock_session;
2581 }
2582 } else {
2583 if (session->snapshot) {
2584 ret = snprintf(closed_trace_chunk_path,
2585 sizeof(closed_trace_chunk_path),
2586 "%s/%s", session->output_path,
2587 chunk_name);
2588 } else {
2589 ret = snprintf(closed_trace_chunk_path,
2590 sizeof(closed_trace_chunk_path),
2591 "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY
2592 "/%s",
2593 session->output_path, chunk_name);
2594 }
2595 if (ret < 0 || ret == sizeof(closed_trace_chunk_path)) {
2596 ERR("Failed to format closed trace chunk resulting path");
2597 reply_code = ret < 0 ? LTTNG_ERR_UNK : LTTNG_ERR_NOMEM;
2598 ret = -1;
2599 goto end_unlock_session;
2600 }
2601 }
2602 DBG("Reply chunk path on close: %s", closed_trace_chunk_path);
2603 path_length = strlen(closed_trace_chunk_path) + 1;
2604 if (path_length > UINT32_MAX) {
2605 ERR("Closed trace chunk path exceeds the maximal length allowed by the protocol");
2606 ret = -1;
2607 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2608 goto end_unlock_session;
2609 }
bbc4768c 2610
c35f9726
JG
2611 if (session->current_trace_chunk == chunk) {
2612 /*
2613 * After a trace chunk close command, no new streams
2614 * referencing the chunk may be created. Hence, on the
2615 * event that no new trace chunk have been created for
2616 * the session, the reference to the current trace chunk
2617 * is released in order to allow it to be reclaimed when
2618 * the last stream releases its reference to it.
2619 */
2620 lttng_trace_chunk_put(session->current_trace_chunk);
2621 session->current_trace_chunk = NULL;
2622 }
62bad3bf
JG
2623 lttng_trace_chunk_put(session->pending_closure_trace_chunk);
2624 session->pending_closure_trace_chunk = NULL;
2625end_unlock_session:
c35f9726
JG
2626 pthread_mutex_unlock(&session->lock);
2627
bbc4768c 2628end:
ecd1a12f
MD
2629 reply.generic.ret_code = htobe32((uint32_t) reply_code);
2630 reply.path_length = htobe32((uint32_t) path_length);
2631 ret = lttng_dynamic_buffer_append(
2632 &reply_payload, &reply, sizeof(reply));
2633 if (ret) {
2634 ERR("Failed to append \"close trace chunk\" command reply header to payload buffer");
2635 goto end_no_reply;
2636 }
2637
2638 if (reply_code == LTTNG_OK) {
2639 ret = lttng_dynamic_buffer_append(&reply_payload,
2640 closed_trace_chunk_path, path_length);
2641 if (ret) {
2642 ERR("Failed to append \"close trace chunk\" command reply path to payload buffer");
2643 goto end_no_reply;
2644 }
2645 }
2646
bbc4768c 2647 send_ret = conn->sock->ops->sendmsg(conn->sock,
ecd1a12f
MD
2648 reply_payload.data,
2649 reply_payload.size,
bbc4768c 2650 0);
ecd1a12f
MD
2651 if (send_ret < reply_payload.size) {
2652 ERR("Failed to send \"close trace chunk\" command reply of %zu bytes (ret = %zd)",
2653 reply_payload.size, send_ret);
bbc4768c 2654 ret = -1;
ecd1a12f 2655 goto end_no_reply;
bbc4768c
JG
2656 }
2657end_no_reply:
2658 lttng_trace_chunk_put(chunk);
ecd1a12f 2659 lttng_dynamic_buffer_reset(&reply_payload);
bbc4768c
JG
2660 return ret;
2661}
2662
c35f9726
JG
2663/*
2664 * relay_trace_chunk_exists: check if a trace chunk exists
2665 */
2666static int relay_trace_chunk_exists(const struct lttcomm_relayd_hdr *recv_hdr,
2667 struct relay_connection *conn,
2668 const struct lttng_buffer_view *payload)
2669{
2670 int ret = 0;
2671 ssize_t send_ret;
2672 struct relay_session *session = conn->session;
2673 struct lttcomm_relayd_trace_chunk_exists *msg;
2674 struct lttcomm_relayd_trace_chunk_exists_reply reply = {};
2675 struct lttng_buffer_view header_view;
2676 struct lttng_trace_chunk *chunk = NULL;
2677 uint64_t chunk_id;
2678
2679 if (!session || !conn->version_check_done) {
2680 ERR("Trying to close a trace chunk before version check");
2681 ret = -1;
2682 goto end_no_reply;
2683 }
2684
2685 if (session->major == 2 && session->minor < 11) {
2686 ERR("Chunk close command is unsupported before 2.11");
2687 ret = -1;
2688 goto end_no_reply;
2689 }
2690
2691 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
2692 if (!header_view.data) {
2693 ERR("Failed to receive payload of chunk close command");
2694 ret = -1;
2695 goto end_no_reply;
2696 }
2697
2698 /* Convert to host endianness. */
2699 msg = (typeof(msg)) header_view.data;
2700 chunk_id = be64toh(msg->chunk_id);
2701
2702 chunk = sessiond_trace_chunk_registry_get_chunk(
2703 sessiond_trace_chunk_registry,
2704 conn->session->sessiond_uuid,
2705 conn->session->id,
2706 chunk_id);
2707
2708 reply = (typeof(reply)) {
2709 .generic.ret_code = htobe32((uint32_t) LTTNG_OK),
2710 .trace_chunk_exists = !!chunk,
2711 };
2712 send_ret = conn->sock->ops->sendmsg(conn->sock,
2713 &reply, sizeof(reply), 0);
2714 if (send_ret < (ssize_t) sizeof(reply)) {
2715 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
2716 send_ret);
2717 ret = -1;
2718 }
2719end_no_reply:
2720 lttng_trace_chunk_put(chunk);
2721 return ret;
2722}
2723
5312a3ed
JG
2724#define DBG_CMD(cmd_name, conn) \
2725 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
2726
2727static int relay_process_control_command(struct relay_connection *conn,
2728 const struct lttcomm_relayd_hdr *header,
2729 const struct lttng_buffer_view *payload)
b8aa1682
JD
2730{
2731 int ret = 0;
2732
5312a3ed 2733 switch (header->cmd) {
b8aa1682 2734 case RELAYD_CREATE_SESSION:
5312a3ed
JG
2735 DBG_CMD("RELAYD_CREATE_SESSION", conn);
2736 ret = relay_create_session(header, conn, payload);
b8aa1682 2737 break;
b8aa1682 2738 case RELAYD_ADD_STREAM:
5312a3ed
JG
2739 DBG_CMD("RELAYD_ADD_STREAM", conn);
2740 ret = relay_add_stream(header, conn, payload);
b8aa1682
JD
2741 break;
2742 case RELAYD_START_DATA:
5312a3ed
JG
2743 DBG_CMD("RELAYD_START_DATA", conn);
2744 ret = relay_start(header, conn, payload);
b8aa1682
JD
2745 break;
2746 case RELAYD_SEND_METADATA:
5312a3ed
JG
2747 DBG_CMD("RELAYD_SEND_METADATA", conn);
2748 ret = relay_recv_metadata(header, conn, payload);
b8aa1682
JD
2749 break;
2750 case RELAYD_VERSION:
5312a3ed
JG
2751 DBG_CMD("RELAYD_VERSION", conn);
2752 ret = relay_send_version(header, conn, payload);
b8aa1682 2753 break;
173af62f 2754 case RELAYD_CLOSE_STREAM:
5312a3ed
JG
2755 DBG_CMD("RELAYD_CLOSE_STREAM", conn);
2756 ret = relay_close_stream(header, conn, payload);
173af62f 2757 break;
6d805429 2758 case RELAYD_DATA_PENDING:
5312a3ed
JG
2759 DBG_CMD("RELAYD_DATA_PENDING", conn);
2760 ret = relay_data_pending(header, conn, payload);
c8f59ee5
DG
2761 break;
2762 case RELAYD_QUIESCENT_CONTROL:
5312a3ed
JG
2763 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn);
2764 ret = relay_quiescent_control(header, conn, payload);
c8f59ee5 2765 break;
f7079f67 2766 case RELAYD_BEGIN_DATA_PENDING:
5312a3ed
JG
2767 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn);
2768 ret = relay_begin_data_pending(header, conn, payload);
f7079f67
DG
2769 break;
2770 case RELAYD_END_DATA_PENDING:
5312a3ed
JG
2771 DBG_CMD("RELAYD_END_DATA_PENDING", conn);
2772 ret = relay_end_data_pending(header, conn, payload);
f7079f67 2773 break;
1c20f0e2 2774 case RELAYD_SEND_INDEX:
5312a3ed
JG
2775 DBG_CMD("RELAYD_SEND_INDEX", conn);
2776 ret = relay_recv_index(header, conn, payload);
1c20f0e2 2777 break;
a4baae1b 2778 case RELAYD_STREAMS_SENT:
5312a3ed
JG
2779 DBG_CMD("RELAYD_STREAMS_SENT", conn);
2780 ret = relay_streams_sent(header, conn, payload);
a4baae1b 2781 break;
93ec662e 2782 case RELAYD_RESET_METADATA:
5312a3ed
JG
2783 DBG_CMD("RELAYD_RESET_METADATA", conn);
2784 ret = relay_reset_metadata(header, conn, payload);
93ec662e 2785 break;
c35f9726
JG
2786 case RELAYD_ROTATE_STREAMS:
2787 DBG_CMD("RELAYD_ROTATE_STREAMS", conn);
2788 ret = relay_rotate_session_streams(header, conn, payload);
d3ecc550 2789 break;
e5add6d0
JG
2790 case RELAYD_CREATE_TRACE_CHUNK:
2791 DBG_CMD("RELAYD_CREATE_TRACE_CHUNK", conn);
2792 ret = relay_create_trace_chunk(header, conn, payload);
2793 break;
bbc4768c
JG
2794 case RELAYD_CLOSE_TRACE_CHUNK:
2795 DBG_CMD("RELAYD_CLOSE_TRACE_CHUNK", conn);
2796 ret = relay_close_trace_chunk(header, conn, payload);
2797 break;
c35f9726
JG
2798 case RELAYD_TRACE_CHUNK_EXISTS:
2799 DBG_CMD("RELAYD_TRACE_CHUNK_EXISTS", conn);
2800 ret = relay_trace_chunk_exists(header, conn, payload);
2801 break;
b8aa1682
JD
2802 case RELAYD_UPDATE_SYNC_INFO:
2803 default:
5312a3ed 2804 ERR("Received unknown command (%u)", header->cmd);
58eb9381 2805 relay_unknown_command(conn);
b8aa1682
JD
2806 ret = -1;
2807 goto end;
2808 }
2809
2810end:
2811 return ret;
2812}
2813
5569b118
JG
2814static enum relay_connection_status relay_process_control_receive_payload(
2815 struct relay_connection *conn)
5312a3ed
JG
2816{
2817 int ret = 0;
5569b118 2818 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
5312a3ed
JG
2819 struct lttng_dynamic_buffer *reception_buffer =
2820 &conn->protocol.ctrl.reception_buffer;
2821 struct ctrl_connection_state_receive_payload *state =
2822 &conn->protocol.ctrl.state.receive_payload;
2823 struct lttng_buffer_view payload_view;
2824
2825 if (state->left_to_receive == 0) {
2826 /* Short-circuit for payload-less commands. */
2827 goto reception_complete;
2828 }
2829
2830 ret = conn->sock->ops->recvmsg(conn->sock,
2831 reception_buffer->data + state->received,
2832 state->left_to_receive, MSG_DONTWAIT);
2833 if (ret < 0) {
5569b118
JG
2834 if (errno != EAGAIN && errno != EWOULDBLOCK) {
2835 PERROR("Unable to receive command payload on sock %d",
2836 conn->sock->fd);
2837 status = RELAY_CONNECTION_STATUS_ERROR;
2838 }
5312a3ed
JG
2839 goto end;
2840 } else if (ret == 0) {
2841 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
5569b118 2842 status = RELAY_CONNECTION_STATUS_CLOSED;
5312a3ed
JG
2843 goto end;
2844 }
2845
2846 assert(ret > 0);
2847 assert(ret <= state->left_to_receive);
2848
2849 state->left_to_receive -= ret;
2850 state->received += ret;
2851
2852 if (state->left_to_receive > 0) {
2853 /*
2854 * Can't transition to the protocol's next state, wait to
2855 * receive the rest of the header.
2856 */
2857 DBG3("Partial reception of control connection protocol payload (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
2858 state->received, state->left_to_receive,
2859 conn->sock->fd);
5312a3ed
JG
2860 goto end;
2861 }
2862
2863reception_complete:
2864 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64 " bytes",
2865 conn->sock->fd, state->received);
2866 /*
2867 * The payload required to process the command has been received.
2868 * A view to the reception buffer is forwarded to the various
2869 * commands and the state of the control is reset on success.
2870 *
2871 * Commands are responsible for sending their reply to the peer.
2872 */
2873 payload_view = lttng_buffer_view_from_dynamic_buffer(reception_buffer,
2874 0, -1);
2875 ret = relay_process_control_command(conn,
2876 &state->header, &payload_view);
2877 if (ret < 0) {
5569b118 2878 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed
JG
2879 goto end;
2880 }
2881
2882 ret = connection_reset_protocol_state(conn);
5569b118
JG
2883 if (ret) {
2884 status = RELAY_CONNECTION_STATUS_ERROR;
2885 }
5312a3ed 2886end:
5569b118 2887 return status;
5312a3ed
JG
2888}
2889
5569b118
JG
2890static enum relay_connection_status relay_process_control_receive_header(
2891 struct relay_connection *conn)
5312a3ed
JG
2892{
2893 int ret = 0;
5569b118 2894 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
5312a3ed
JG
2895 struct lttcomm_relayd_hdr header;
2896 struct lttng_dynamic_buffer *reception_buffer =
2897 &conn->protocol.ctrl.reception_buffer;
2898 struct ctrl_connection_state_receive_header *state =
2899 &conn->protocol.ctrl.state.receive_header;
2900
2901 assert(state->left_to_receive != 0);
2902
2903 ret = conn->sock->ops->recvmsg(conn->sock,
2904 reception_buffer->data + state->received,
2905 state->left_to_receive, MSG_DONTWAIT);
2906 if (ret < 0) {
5569b118
JG
2907 if (errno != EAGAIN && errno != EWOULDBLOCK) {
2908 PERROR("Unable to receive control command header on sock %d",
2909 conn->sock->fd);
2910 status = RELAY_CONNECTION_STATUS_ERROR;
2911 }
5312a3ed
JG
2912 goto end;
2913 } else if (ret == 0) {
2914 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
5569b118 2915 status = RELAY_CONNECTION_STATUS_CLOSED;
5312a3ed
JG
2916 goto end;
2917 }
2918
2919 assert(ret > 0);
2920 assert(ret <= state->left_to_receive);
2921
2922 state->left_to_receive -= ret;
2923 state->received += ret;
2924
2925 if (state->left_to_receive > 0) {
2926 /*
2927 * Can't transition to the protocol's next state, wait to
2928 * receive the rest of the header.
2929 */
2930 DBG3("Partial reception of control connection protocol header (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
2931 state->received, state->left_to_receive,
2932 conn->sock->fd);
5312a3ed
JG
2933 goto end;
2934 }
2935
2936 /* Transition to next state: receiving the command's payload. */
2937 conn->protocol.ctrl.state_id =
2938 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD;
2939 memcpy(&header, reception_buffer->data, sizeof(header));
2940 header.circuit_id = be64toh(header.circuit_id);
2941 header.data_size = be64toh(header.data_size);
2942 header.cmd = be32toh(header.cmd);
2943 header.cmd_version = be32toh(header.cmd_version);
2944 memcpy(&conn->protocol.ctrl.state.receive_payload.header,
2945 &header, sizeof(header));
2946
2947 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32 ", cmd_version = %" PRIu32 ", payload size = %" PRIu64 " bytes",
2948 conn->sock->fd, header.cmd, header.cmd_version,
2949 header.data_size);
2950
715e6fb1 2951 if (header.data_size > DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE) {
5312a3ed
JG
2952 ERR("Command header indicates a payload (%" PRIu64 " bytes) that exceeds the maximal payload size allowed on a control connection.",
2953 header.data_size);
5569b118 2954 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed
JG
2955 goto end;
2956 }
2957
2958 conn->protocol.ctrl.state.receive_payload.left_to_receive =
2959 header.data_size;
2960 conn->protocol.ctrl.state.receive_payload.received = 0;
2961 ret = lttng_dynamic_buffer_set_size(reception_buffer,
2962 header.data_size);
2963 if (ret) {
5569b118 2964 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed
JG
2965 goto end;
2966 }
2967
2968 if (header.data_size == 0) {
2969 /*
2970 * Manually invoke the next state as the poll loop
2971 * will not wake-up to allow us to proceed further.
2972 */
5569b118 2973 status = relay_process_control_receive_payload(conn);
5312a3ed
JG
2974 }
2975end:
5569b118 2976 return status;
5312a3ed
JG
2977}
2978
2979/*
2980 * Process the commands received on the control socket
2981 */
5569b118
JG
2982static enum relay_connection_status relay_process_control(
2983 struct relay_connection *conn)
5312a3ed 2984{
5569b118 2985 enum relay_connection_status status;
5312a3ed
JG
2986
2987 switch (conn->protocol.ctrl.state_id) {
2988 case CTRL_CONNECTION_STATE_RECEIVE_HEADER:
5569b118 2989 status = relay_process_control_receive_header(conn);
5312a3ed
JG
2990 break;
2991 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD:
5569b118 2992 status = relay_process_control_receive_payload(conn);
5312a3ed
JG
2993 break;
2994 default:
2995 ERR("Unknown control connection protocol state encountered.");
2996 abort();
2997 }
2998
5569b118 2999 return status;
5312a3ed
JG
3000}
3001
5569b118
JG
3002static enum relay_connection_status relay_process_data_receive_header(
3003 struct relay_connection *conn)
b8aa1682 3004{
5312a3ed 3005 int ret;
5569b118 3006 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
5312a3ed
JG
3007 struct data_connection_state_receive_header *state =
3008 &conn->protocol.data.state.receive_header;
3009 struct lttcomm_relayd_data_hdr header;
b8aa1682 3010 struct relay_stream *stream;
5312a3ed
JG
3011
3012 assert(state->left_to_receive != 0);
3013
3014 ret = conn->sock->ops->recvmsg(conn->sock,
3015 state->header_reception_buffer + state->received,
3016 state->left_to_receive, MSG_DONTWAIT);
3017 if (ret < 0) {
5569b118
JG
3018 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3019 PERROR("Unable to receive data header on sock %d", conn->sock->fd);
3020 status = RELAY_CONNECTION_STATUS_ERROR;
3021 }
5312a3ed
JG
3022 goto end;
3023 } else if (ret == 0) {
3024 /* Orderly shutdown. Not necessary to print an error. */
3025 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
5569b118 3026 status = RELAY_CONNECTION_STATUS_CLOSED;
b8aa1682
JD
3027 goto end;
3028 }
3029
5312a3ed
JG
3030 assert(ret > 0);
3031 assert(ret <= state->left_to_receive);
3032
3033 state->left_to_receive -= ret;
3034 state->received += ret;
3035
3036 if (state->left_to_receive > 0) {
3037 /*
3038 * Can't transition to the protocol's next state, wait to
3039 * receive the rest of the header.
3040 */
3041 DBG3("Partial reception of data connection header (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
3042 state->received, state->left_to_receive,
3043 conn->sock->fd);
7591bab1 3044 goto end;
b8aa1682 3045 }
b8aa1682 3046
5312a3ed
JG
3047 /* Transition to next state: receiving the payload. */
3048 conn->protocol.data.state_id = DATA_CONNECTION_STATE_RECEIVE_PAYLOAD;
173af62f 3049
5312a3ed
JG
3050 memcpy(&header, state->header_reception_buffer, sizeof(header));
3051 header.circuit_id = be64toh(header.circuit_id);
3052 header.stream_id = be64toh(header.stream_id);
3053 header.data_size = be32toh(header.data_size);
3054 header.net_seq_num = be64toh(header.net_seq_num);
3055 header.padding_size = be32toh(header.padding_size);
3056 memcpy(&conn->protocol.data.state.receive_payload.header, &header, sizeof(header));
3057
3058 conn->protocol.data.state.receive_payload.left_to_receive =
3059 header.data_size;
3060 conn->protocol.data.state.receive_payload.received = 0;
3061 conn->protocol.data.state.receive_payload.rotate_index = false;
3062
3063 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64 ", stream_id = %" PRIu64 ", data_size = %" PRIu32 ", net_seq_num = %" PRIu64 ", padding_size = %" PRIu32,
3064 conn->sock->fd, header.circuit_id,
3065 header.stream_id, header.data_size,
3066 header.net_seq_num, header.padding_size);
3067
3068 stream = stream_get_by_id(header.stream_id);
3069 if (!stream) {
3070 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64,
3071 header.stream_id);
5569b118
JG
3072 /* Protocol error. */
3073 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed
JG
3074 goto end;
3075 }
b8aa1682 3076
7591bab1 3077 pthread_mutex_lock(&stream->lock);
c35f9726
JG
3078 /* Prepare stream for the reception of a new packet. */
3079 ret = stream_init_packet(stream, header.data_size,
3080 &conn->protocol.data.state.receive_payload.rotate_index);
3081 pthread_mutex_unlock(&stream->lock);
3082 if (ret) {
3083 ERR("Failed to rotate stream output file");
3084 status = RELAY_CONNECTION_STATUS_ERROR;
3085 goto end_stream_unlock;
1c20f0e2
JD
3086 }
3087
5312a3ed 3088end_stream_unlock:
5312a3ed
JG
3089 stream_put(stream);
3090end:
5569b118 3091 return status;
5312a3ed
JG
3092}
3093
5569b118
JG
3094static enum relay_connection_status relay_process_data_receive_payload(
3095 struct relay_connection *conn)
5312a3ed
JG
3096{
3097 int ret;
5569b118 3098 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
5312a3ed
JG
3099 struct relay_stream *stream;
3100 struct data_connection_state_receive_payload *state =
3101 &conn->protocol.data.state.receive_payload;
3102 const size_t chunk_size = RECV_DATA_BUFFER_SIZE;
3103 char data_buffer[chunk_size];
3104 bool partial_recv = false;
3105 bool new_stream = false, close_requested = false, index_flushed = false;
3106 uint64_t left_to_receive = state->left_to_receive;
3107 struct relay_session *session;
3108
fd0f1e3e
JR
3109 DBG3("Receiving data for stream id %" PRIu64 " seqnum %" PRIu64 ", %" PRIu64" bytes received, %" PRIu64 " bytes left to receive",
3110 state->header.stream_id, state->header.net_seq_num,
3111 state->received, left_to_receive);
3112
5312a3ed
JG
3113 stream = stream_get_by_id(state->header.stream_id);
3114 if (!stream) {
5569b118 3115 /* Protocol error. */
fd0f1e3e 3116 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64,
5312a3ed 3117 state->header.stream_id);
5569b118 3118 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed 3119 goto end;
1c20f0e2
JD
3120 }
3121
5312a3ed
JG
3122 pthread_mutex_lock(&stream->lock);
3123 session = stream->trace->session;
fd0f1e3e
JR
3124 if (!conn->session) {
3125 ret = connection_set_session(conn, session);
3126 if (ret) {
3127 status = RELAY_CONNECTION_STATUS_ERROR;
3128 goto end_stream_unlock;
3129 }
3130 }
5312a3ed
JG
3131
3132 /*
3133 * The size of the "chunk" received on any iteration is bounded by:
3134 * - the data left to receive,
3135 * - the data immediately available on the socket,
3136 * - the on-stack data buffer
3137 */
3138 while (left_to_receive > 0 && !partial_recv) {
5312a3ed 3139 size_t recv_size = min(left_to_receive, chunk_size);
c35f9726 3140 struct lttng_buffer_view packet_chunk;
5312a3ed
JG
3141
3142 ret = conn->sock->ops->recvmsg(conn->sock, data_buffer,
3143 recv_size, MSG_DONTWAIT);
3144 if (ret < 0) {
5569b118
JG
3145 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3146 PERROR("Socket %d error", conn->sock->fd);
3147 status = RELAY_CONNECTION_STATUS_ERROR;
3148 }
0848dba7 3149 goto end_stream_unlock;
5312a3ed
JG
3150 } else if (ret == 0) {
3151 /* No more data ready to be consumed on socket. */
3152 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64,
3153 state->header.stream_id);
5569b118 3154 status = RELAY_CONNECTION_STATUS_CLOSED;
5312a3ed
JG
3155 break;
3156 } else if (ret < (int) recv_size) {
3157 /*
3158 * All the data available on the socket has been
3159 * consumed.
3160 */
3161 partial_recv = true;
c35f9726 3162 recv_size = ret;
0848dba7
MD
3163 }
3164
c35f9726
JG
3165 packet_chunk = lttng_buffer_view_init(data_buffer,
3166 0, recv_size);
3167 assert(packet_chunk.data);
5312a3ed 3168
c35f9726
JG
3169 ret = stream_write(stream, &packet_chunk, 0);
3170 if (ret) {
0848dba7 3171 ERR("Relay error writing data to file");
5569b118 3172 status = RELAY_CONNECTION_STATUS_ERROR;
0848dba7
MD
3173 goto end_stream_unlock;
3174 }
3175
5312a3ed
JG
3176 left_to_receive -= recv_size;
3177 state->received += recv_size;
3178 state->left_to_receive = left_to_receive;
5312a3ed
JG
3179 }
3180
3181 if (state->left_to_receive > 0) {
3182 /*
3183 * Did not receive all the data expected, wait for more data to
3184 * become available on the socket.
3185 */
3186 DBG3("Partial receive on data connection of stream id %" PRIu64 ", %" PRIu64 " bytes received, %" PRIu64 " bytes left to receive",
3187 state->header.stream_id, state->received,
3188 state->left_to_receive);
5312a3ed 3189 goto end_stream_unlock;
0848dba7 3190 }
5ab7344e 3191
c35f9726
JG
3192 ret = stream_write(stream, NULL, state->header.padding_size);
3193 if (ret) {
5569b118 3194 status = RELAY_CONNECTION_STATUS_ERROR;
7591bab1 3195 goto end_stream_unlock;
1d4dfdef 3196 }
5312a3ed 3197
298a25ca 3198 if (session_streams_have_index(session)) {
c35f9726
JG
3199 ret = stream_update_index(stream, state->header.net_seq_num,
3200 state->rotate_index, &index_flushed,
3201 state->header.data_size + state->header.padding_size);
5312a3ed 3202 if (ret < 0) {
c35f9726 3203 ERR("Failed to update index: stream %" PRIu64 " net_seq_num %" PRIu64 " ret %d",
5312a3ed
JG
3204 stream->stream_handle,
3205 state->header.net_seq_num, ret);
5569b118 3206 status = RELAY_CONNECTION_STATUS_ERROR;
5312a3ed
JG
3207 goto end_stream_unlock;
3208 }
3209 }
3210
a8f9f353 3211 if (stream->prev_data_seq == -1ULL) {
c0bae11d
MD
3212 new_stream = true;
3213 }
3214
c35f9726
JG
3215 ret = stream_complete_packet(stream, state->header.data_size +
3216 state->header.padding_size, state->header.net_seq_num,
3217 index_flushed);
3218 if (ret) {
3219 status = RELAY_CONNECTION_STATUS_ERROR;
3220 goto end_stream_unlock;
3221 }
5312a3ed
JG
3222
3223 /*
3224 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3225 * contents of *state which are aliased (union) to the same location as
3226 * the new state. Don't use it beyond this point.
3227 */
3228 connection_reset_protocol_state(conn);
3229 state = NULL;
173af62f 3230
7591bab1 3231end_stream_unlock:
bda7c7b9 3232 close_requested = stream->close_requested;
7591bab1 3233 pthread_mutex_unlock(&stream->lock);
5312a3ed 3234 if (close_requested && left_to_receive == 0) {
bda7c7b9
JG
3235 try_stream_close(stream);
3236 }
3237
c0bae11d
MD
3238 if (new_stream) {
3239 pthread_mutex_lock(&session->lock);
3240 uatomic_set(&session->new_streams, 1);
3241 pthread_mutex_unlock(&session->lock);
3242 }
5312a3ed 3243
7591bab1 3244 stream_put(stream);
b8aa1682 3245end:
5569b118 3246 return status;
b8aa1682
JD
3247}
3248
5312a3ed
JG
3249/*
3250 * relay_process_data: Process the data received on the data socket
3251 */
5569b118
JG
3252static enum relay_connection_status relay_process_data(
3253 struct relay_connection *conn)
5312a3ed 3254{
5569b118 3255 enum relay_connection_status status;
5312a3ed
JG
3256
3257 switch (conn->protocol.data.state_id) {
3258 case DATA_CONNECTION_STATE_RECEIVE_HEADER:
5569b118 3259 status = relay_process_data_receive_header(conn);
5312a3ed
JG
3260 break;
3261 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD:
5569b118 3262 status = relay_process_data_receive_payload(conn);
5312a3ed
JG
3263 break;
3264 default:
3265 ERR("Unexpected data connection communication state.");
3266 abort();
3267 }
3268
5569b118 3269 return status;
5312a3ed
JG
3270}
3271
7591bab1 3272static void cleanup_connection_pollfd(struct lttng_poll_event *events, int pollfd)
b8aa1682
JD
3273{
3274 int ret;
3275
58eb9381 3276 (void) lttng_poll_del(events, pollfd);
b8aa1682
JD
3277
3278 ret = close(pollfd);
3279 if (ret < 0) {
3280 ERR("Closing pollfd %d", pollfd);
3281 }
3282}
3283
7591bab1
MD
3284static void relay_thread_close_connection(struct lttng_poll_event *events,
3285 int pollfd, struct relay_connection *conn)
9d1bbf21 3286{
7591bab1 3287 const char *type_str;
2a174661 3288
7591bab1
MD
3289 switch (conn->type) {
3290 case RELAY_DATA:
3291 type_str = "Data";
3292 break;
3293 case RELAY_CONTROL:
3294 type_str = "Control";
3295 break;
3296 case RELAY_VIEWER_COMMAND:
3297 type_str = "Viewer Command";
3298 break;
3299 case RELAY_VIEWER_NOTIFICATION:
3300 type_str = "Viewer Notification";
3301 break;
3302 default:
3303 type_str = "Unknown";
9d1bbf21 3304 }
7591bab1
MD
3305 cleanup_connection_pollfd(events, pollfd);
3306 connection_put(conn);
3307 DBG("%s connection closed with %d", type_str, pollfd);
b8aa1682
JD
3308}
3309
3310/*
3311 * This thread does the actual work
3312 */
7591bab1 3313static void *relay_thread_worker(void *data)
b8aa1682 3314{
beaad64c
DG
3315 int ret, err = -1, last_seen_data_fd = -1;
3316 uint32_t nb_fd;
b8aa1682
JD
3317 struct lttng_poll_event events;
3318 struct lttng_ht *relay_connections_ht;
b8aa1682 3319 struct lttng_ht_iter iter;
90e7d72f 3320 struct relay_connection *destroy_conn = NULL;
b8aa1682
JD
3321
3322 DBG("[thread] Relay worker started");
3323
9d1bbf21
MD
3324 rcu_register_thread();
3325
55706a7d
MD
3326 health_register(health_relayd, HEALTH_RELAYD_TYPE_WORKER);
3327
9b5e0863
MD
3328 if (testpoint(relayd_thread_worker)) {
3329 goto error_testpoint;
3330 }
3331
f385ae0a
MD
3332 health_code_update();
3333
b8aa1682
JD
3334 /* table of connections indexed on socket */
3335 relay_connections_ht = lttng_ht_new(0, LTTNG_HT_TYPE_ULONG);
095a4ae5
MD
3336 if (!relay_connections_ht) {
3337 goto relay_connections_ht_error;
3338 }
b8aa1682 3339
b8aa1682
JD
3340 ret = create_thread_poll_set(&events, 2);
3341 if (ret < 0) {
3342 goto error_poll_create;
3343 }
3344
58eb9381 3345 ret = lttng_poll_add(&events, relay_conn_pipe[0], LPOLLIN | LPOLLRDHUP);
b8aa1682
JD
3346 if (ret < 0) {
3347 goto error;
3348 }
3349
beaad64c 3350restart:
b8aa1682 3351 while (1) {
beaad64c
DG
3352 int idx = -1, i, seen_control = 0, last_notdel_data_fd = -1;
3353
f385ae0a
MD
3354 health_code_update();
3355
b8aa1682 3356 /* Infinite blocking call, waiting for transmission */
87c1611d 3357 DBG3("Relayd worker thread polling...");
f385ae0a 3358 health_poll_entry();
b8aa1682 3359 ret = lttng_poll_wait(&events, -1);
f385ae0a 3360 health_poll_exit();
b8aa1682
JD
3361 if (ret < 0) {
3362 /*
3363 * Restart interrupted system call.
3364 */
3365 if (errno == EINTR) {
3366 goto restart;
3367 }
3368 goto error;
3369 }
3370
0d9c5d77
DG
3371 nb_fd = ret;
3372
beaad64c 3373 /*
7591bab1
MD
3374 * Process control. The control connection is
3375 * prioritized so we don't starve it with high
3376 * throughput tracing data on the data connection.
beaad64c 3377 */
b8aa1682
JD
3378 for (i = 0; i < nb_fd; i++) {
3379 /* Fetch once the poll data */
beaad64c
DG
3380 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
3381 int pollfd = LTTNG_POLL_GETFD(&events, i);
b8aa1682 3382
f385ae0a
MD
3383 health_code_update();
3384
b8aa1682
JD
3385 /* Thread quit pipe has been closed. Killing thread. */
3386 ret = check_thread_quit_pipe(pollfd, revents);
3387 if (ret) {
095a4ae5
MD
3388 err = 0;
3389 goto exit;
b8aa1682
JD
3390 }
3391
58eb9381
DG
3392 /* Inspect the relay conn pipe for new connection */
3393 if (pollfd == relay_conn_pipe[0]) {
03e43155 3394 if (revents & LPOLLIN) {
90e7d72f
JG
3395 struct relay_connection *conn;
3396
58eb9381 3397 ret = lttng_read(relay_conn_pipe[0], &conn, sizeof(conn));
b8aa1682
JD
3398 if (ret < 0) {
3399 goto error;
3400 }
58eb9381
DG
3401 lttng_poll_add(&events, conn->sock->fd,
3402 LPOLLIN | LPOLLRDHUP);
7591bab1 3403 connection_ht_add(relay_connections_ht, conn);
58eb9381 3404 DBG("Connection socket %d added", conn->sock->fd);
03e43155
MD
3405 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
3406 ERR("Relay connection pipe error");
3407 goto error;
3408 } else {
3409 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
3410 goto error;
b8aa1682 3411 }
58eb9381 3412 } else {
90e7d72f
JG
3413 struct relay_connection *ctrl_conn;
3414
7591bab1 3415 ctrl_conn = connection_get_by_sock(relay_connections_ht, pollfd);
58eb9381 3416 /* If not found, there is a synchronization issue. */
90e7d72f 3417 assert(ctrl_conn);
58eb9381 3418
03e43155
MD
3419 if (ctrl_conn->type == RELAY_DATA) {
3420 if (revents & LPOLLIN) {
beaad64c
DG
3421 /*
3422 * Flag the last seen data fd not deleted. It will be
3423 * used as the last seen fd if any fd gets deleted in
3424 * this first loop.
3425 */
3426 last_notdel_data_fd = pollfd;
3427 }
03e43155
MD
3428 goto put_ctrl_connection;
3429 }
3430 assert(ctrl_conn->type == RELAY_CONTROL);
3431
3432 if (revents & LPOLLIN) {
5569b118
JG
3433 enum relay_connection_status status;
3434
3435 status = relay_process_control(ctrl_conn);
3436 if (status != RELAY_CONNECTION_STATUS_OK) {
fd0f1e3e
JR
3437 /*
3438 * On socket error flag the session as aborted to force
3439 * the cleanup of its stream otherwise it can leak
3440 * during the lifetime of the relayd.
3441 *
3442 * This prevents situations in which streams can be
3443 * left opened because an index was received, the
3444 * control connection is closed, and the data
3445 * connection is closed (uncleanly) before the packet's
3446 * data provided.
3447 *
3448 * Since the control connection encountered an error,
3449 * it is okay to be conservative and close the
3450 * session right now as we can't rely on the protocol
3451 * being respected anymore.
3452 */
3453 if (status == RELAY_CONNECTION_STATUS_ERROR) {
3454 session_abort(ctrl_conn->session);
3455 }
3456
5569b118 3457 /* Clear the connection on error or close. */
5312a3ed
JG
3458 relay_thread_close_connection(&events,
3459 pollfd,
03e43155 3460 ctrl_conn);
03e43155 3461 }
5312a3ed 3462 seen_control = 1;
03e43155
MD
3463 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
3464 relay_thread_close_connection(&events,
3465 pollfd, ctrl_conn);
3466 if (last_seen_data_fd == pollfd) {
3467 last_seen_data_fd = last_notdel_data_fd;
3468 }
58eb9381 3469 } else {
03e43155
MD
3470 ERR("Unexpected poll events %u for control sock %d",
3471 revents, pollfd);
3472 connection_put(ctrl_conn);
3473 goto error;
beaad64c 3474 }
03e43155 3475 put_ctrl_connection:
7591bab1 3476 connection_put(ctrl_conn);
beaad64c
DG
3477 }
3478 }
3479
3480 /*
3481 * The last loop handled a control request, go back to poll to make
3482 * sure we prioritise the control socket.
3483 */
3484 if (seen_control) {
3485 continue;
3486 }
3487
3488 if (last_seen_data_fd >= 0) {
3489 for (i = 0; i < nb_fd; i++) {
3490 int pollfd = LTTNG_POLL_GETFD(&events, i);
f385ae0a
MD
3491
3492 health_code_update();
3493
beaad64c
DG
3494 if (last_seen_data_fd == pollfd) {
3495 idx = i;
3496 break;
3497 }
3498 }
3499 }
3500
3501 /* Process data connection. */
3502 for (i = idx + 1; i < nb_fd; i++) {
3503 /* Fetch the poll data. */
3504 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
3505 int pollfd = LTTNG_POLL_GETFD(&events, i);
90e7d72f 3506 struct relay_connection *data_conn;
beaad64c 3507
f385ae0a
MD
3508 health_code_update();
3509
fd20dac9
MD
3510 if (!revents) {
3511 /* No activity for this FD (poll implementation). */
3512 continue;
3513 }
3514
beaad64c 3515 /* Skip the command pipe. It's handled in the first loop. */
58eb9381 3516 if (pollfd == relay_conn_pipe[0]) {
beaad64c
DG
3517 continue;
3518 }
3519
7591bab1 3520 data_conn = connection_get_by_sock(relay_connections_ht, pollfd);
90e7d72f 3521 if (!data_conn) {
fd20dac9 3522 /* Skip it. Might be removed before. */
fd20dac9
MD
3523 continue;
3524 }
03e43155
MD
3525 if (data_conn->type == RELAY_CONTROL) {
3526 goto put_data_connection;
3527 }
3528 assert(data_conn->type == RELAY_DATA);
fd20dac9
MD
3529
3530 if (revents & LPOLLIN) {
5569b118
JG
3531 enum relay_connection_status status;
3532
3533 status = relay_process_data(data_conn);
3534 /* Connection closed or error. */
3535 if (status != RELAY_CONNECTION_STATUS_OK) {
fd0f1e3e
JR
3536 /*
3537 * On socket error flag the session as aborted to force
3538 * the cleanup of its stream otherwise it can leak
3539 * during the lifetime of the relayd.
3540 *
3541 * This prevents situations in which streams can be
3542 * left opened because an index was received, the
3543 * control connection is closed, and the data
3544 * connection is closed (uncleanly) before the packet's
3545 * data provided.
3546 *
3547 * Since the data connection encountered an error,
3548 * it is okay to be conservative and close the
3549 * session right now as we can't rely on the protocol
3550 * being respected anymore.
3551 */
3552 if (status == RELAY_CONNECTION_STATUS_ERROR) {
3553 session_abort(data_conn->session);
3554 }
7591bab1 3555 relay_thread_close_connection(&events, pollfd,
03e43155 3556 data_conn);
fd20dac9
MD
3557 /*
3558 * Every goto restart call sets the last seen fd where
3559 * here we don't really care since we gracefully
3560 * continue the loop after the connection is deleted.
3561 */
3562 } else {
3563 /* Keep last seen port. */
3564 last_seen_data_fd = pollfd;
7591bab1 3565 connection_put(data_conn);
fd20dac9 3566 goto restart;
b8aa1682 3567 }
03e43155
MD
3568 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
3569 relay_thread_close_connection(&events, pollfd,
3570 data_conn);
3571 } else {
3572 ERR("Unknown poll events %u for data sock %d",
3573 revents, pollfd);
b8aa1682 3574 }
03e43155 3575 put_data_connection:
7591bab1 3576 connection_put(data_conn);
b8aa1682 3577 }
beaad64c 3578 last_seen_data_fd = -1;
b8aa1682
JD
3579 }
3580
f385ae0a
MD
3581 /* Normal exit, no error */
3582 ret = 0;
3583
095a4ae5 3584exit:
b8aa1682 3585error:
71efa8ef 3586 /* Cleanup remaining connection object. */
9d1bbf21 3587 rcu_read_lock();
90e7d72f
JG
3588 cds_lfht_for_each_entry(relay_connections_ht->ht, &iter.iter,
3589 destroy_conn,
58eb9381 3590 sock_n.node) {
f385ae0a 3591 health_code_update();
98ba050e 3592
fd0f1e3e 3593 session_abort(destroy_conn->session);
98ba050e 3594
7591bab1
MD
3595 /*
3596 * No need to grab another ref, because we own
3597 * destroy_conn.
3598 */
3599 relay_thread_close_connection(&events, destroy_conn->sock->fd,
3600 destroy_conn);
b8aa1682 3601 }
94d49140 3602 rcu_read_unlock();
7591bab1
MD
3603
3604 lttng_poll_clean(&events);
7d2f7452 3605error_poll_create:
b8aa1682 3606 lttng_ht_destroy(relay_connections_ht);
095a4ae5 3607relay_connections_ht_error:
58eb9381
DG
3608 /* Close relay conn pipes */
3609 utils_close_pipe(relay_conn_pipe);
095a4ae5
MD
3610 if (err) {
3611 DBG("Thread exited with error");
3612 }
b8aa1682 3613 DBG("Worker thread cleanup complete");
9b5e0863 3614error_testpoint:
f385ae0a
MD
3615 if (err) {
3616 health_error();
3617 ERR("Health error occurred in %s", __func__);
3618 }
3619 health_unregister(health_relayd);
9d1bbf21 3620 rcu_unregister_thread();
b4aacfdc 3621 lttng_relay_stop_threads();
b8aa1682
JD
3622 return NULL;
3623}
3624
3625/*
3626 * Create the relay command pipe to wake thread_manage_apps.
3627 * Closed in cleanup().
3628 */
58eb9381 3629static int create_relay_conn_pipe(void)
b8aa1682 3630{
a02de639 3631 int ret;
b8aa1682 3632
58eb9381 3633 ret = utils_create_pipe_cloexec(relay_conn_pipe);
b8aa1682 3634
b8aa1682
JD
3635 return ret;
3636}
3637
3638/*
3639 * main
3640 */
3641int main(int argc, char **argv)
3642{
178a0557 3643 int ret = 0, retval = 0;
b8aa1682
JD
3644 void *status;
3645
b8aa1682
JD
3646 /* Parse arguments */
3647 progname = argv[0];
178a0557
MD
3648 if (set_options(argc, argv)) {
3649 retval = -1;
3650 goto exit_options;
b8aa1682
JD
3651 }
3652
178a0557
MD
3653 if (set_signal_handler()) {
3654 retval = -1;
3655 goto exit_options;
b8aa1682
JD
3656 }
3657
4d513a50
DG
3658 /* Try to create directory if -o, --output is specified. */
3659 if (opt_output_path) {
994fa64f
DG
3660 if (*opt_output_path != '/') {
3661 ERR("Please specify an absolute path for -o, --output PATH");
178a0557
MD
3662 retval = -1;
3663 goto exit_options;
994fa64f
DG
3664 }
3665
d77dded2
JG
3666 ret = utils_mkdir_recursive(opt_output_path, S_IRWXU | S_IRWXG,
3667 -1, -1);
4d513a50
DG
3668 if (ret < 0) {
3669 ERR("Unable to create %s", opt_output_path);
178a0557
MD
3670 retval = -1;
3671 goto exit_options;
4d513a50
DG
3672 }
3673 }
3674
b8aa1682 3675 /* Daemonize */
b5218ffb 3676 if (opt_daemon || opt_background) {
3fd27398
MD
3677 int i;
3678
3679 ret = lttng_daemonize(&child_ppid, &recv_child_signal,
3680 !opt_background);
b8aa1682 3681 if (ret < 0) {
178a0557
MD
3682 retval = -1;
3683 goto exit_options;
b8aa1682 3684 }
3fd27398
MD
3685
3686 /*
3687 * We are in the child. Make sure all other file
3688 * descriptors are closed, in case we are called with
3689 * more opened file descriptors than the standard ones.
3690 */
3691 for (i = 3; i < sysconf(_SC_OPEN_MAX); i++) {
3692 (void) close(i);
3693 }
3694 }
3695
23c8ff50
JG
3696 sessiond_trace_chunk_registry = sessiond_trace_chunk_registry_create();
3697 if (!sessiond_trace_chunk_registry) {
3698 ERR("Failed to initialize session daemon trace chunk registry");
3699 retval = -1;
3700 goto exit_sessiond_trace_chunk_registry;
3701 }
3702
178a0557
MD
3703 /* Initialize thread health monitoring */
3704 health_relayd = health_app_create(NR_HEALTH_RELAYD_TYPES);
3705 if (!health_relayd) {
3706 PERROR("health_app_create error");
3707 retval = -1;
3708 goto exit_health_app_create;
3709 }
3710
3fd27398 3711 /* Create thread quit pipe */
178a0557
MD
3712 if (init_thread_quit_pipe()) {
3713 retval = -1;
3714 goto exit_init_data;
b8aa1682
JD
3715 }
3716
b8aa1682 3717 /* Setup the thread apps communication pipe. */
178a0557
MD
3718 if (create_relay_conn_pipe()) {
3719 retval = -1;
3720 goto exit_init_data;
b8aa1682
JD
3721 }
3722
3723 /* Init relay command queue. */
8bdee6e2 3724 cds_wfcq_init(&relay_conn_queue.head, &relay_conn_queue.tail);
b8aa1682 3725
554831e7
MD
3726 /* Initialize communication library */
3727 lttcomm_init();
87e45c13 3728 lttcomm_inet_init();
554831e7 3729
d3e2ba59 3730 /* tables of sessions indexed by session ID */
7591bab1
MD
3731 sessions_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3732 if (!sessions_ht) {
178a0557
MD
3733 retval = -1;
3734 goto exit_init_data;
d3e2ba59
JD
3735 }
3736
3737 /* tables of streams indexed by stream ID */
2a174661 3738 relay_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
d3e2ba59 3739 if (!relay_streams_ht) {
178a0557
MD
3740 retval = -1;
3741 goto exit_init_data;
d3e2ba59
JD
3742 }
3743
3744 /* tables of streams indexed by stream ID */
92c6ca54
DG
3745 viewer_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3746 if (!viewer_streams_ht) {
178a0557
MD
3747 retval = -1;
3748 goto exit_init_data;
55706a7d
MD
3749 }
3750
65931c8b 3751 ret = utils_create_pipe(health_quit_pipe);
178a0557
MD
3752 if (ret) {
3753 retval = -1;
3754 goto exit_health_quit_pipe;
65931c8b
MD
3755 }
3756
3757 /* Create thread to manage the client socket */
1a1a34b4 3758 ret = pthread_create(&health_thread, default_pthread_attr(),
65931c8b 3759 thread_manage_health, (void *) NULL);
178a0557
MD
3760 if (ret) {
3761 errno = ret;
65931c8b 3762 PERROR("pthread_create health");
178a0557
MD
3763 retval = -1;
3764 goto exit_health_thread;
65931c8b
MD
3765 }
3766
b8aa1682 3767 /* Setup the dispatcher thread */
1a1a34b4 3768 ret = pthread_create(&dispatcher_thread, default_pthread_attr(),
b8aa1682 3769 relay_thread_dispatcher, (void *) NULL);
178a0557
MD
3770 if (ret) {
3771 errno = ret;
b8aa1682 3772 PERROR("pthread_create dispatcher");
178a0557
MD
3773 retval = -1;
3774 goto exit_dispatcher_thread;
b8aa1682
JD
3775 }
3776
3777 /* Setup the worker thread */
1a1a34b4 3778 ret = pthread_create(&worker_thread, default_pthread_attr(),
7591bab1 3779 relay_thread_worker, NULL);
178a0557
MD
3780 if (ret) {
3781 errno = ret;
b8aa1682 3782 PERROR("pthread_create worker");
178a0557
MD
3783 retval = -1;
3784 goto exit_worker_thread;
b8aa1682
JD
3785 }
3786
3787 /* Setup the listener thread */
1a1a34b4 3788 ret = pthread_create(&listener_thread, default_pthread_attr(),
b8aa1682 3789 relay_thread_listener, (void *) NULL);
178a0557
MD
3790 if (ret) {
3791 errno = ret;
b8aa1682 3792 PERROR("pthread_create listener");
178a0557
MD
3793 retval = -1;
3794 goto exit_listener_thread;
b8aa1682
JD
3795 }
3796
7591bab1 3797 ret = relayd_live_create(live_uri);
178a0557 3798 if (ret) {
d3e2ba59 3799 ERR("Starting live viewer threads");
178a0557 3800 retval = -1;
50138f51 3801 goto exit_live;
d3e2ba59
JD
3802 }
3803
178a0557
MD
3804 /*
3805 * This is where we start awaiting program completion (e.g. through
3806 * signal that asks threads to teardown).
3807 */
3808
3809 ret = relayd_live_join();
3810 if (ret) {
3811 retval = -1;
3812 }
50138f51 3813exit_live:
178a0557 3814
b8aa1682 3815 ret = pthread_join(listener_thread, &status);
178a0557
MD
3816 if (ret) {
3817 errno = ret;
3818 PERROR("pthread_join listener_thread");
3819 retval = -1;
b8aa1682
JD
3820 }
3821
178a0557 3822exit_listener_thread:
b8aa1682 3823 ret = pthread_join(worker_thread, &status);
178a0557
MD
3824 if (ret) {
3825 errno = ret;
3826 PERROR("pthread_join worker_thread");
3827 retval = -1;
b8aa1682
JD
3828 }
3829
178a0557 3830exit_worker_thread:
b8aa1682 3831 ret = pthread_join(dispatcher_thread, &status);
178a0557
MD
3832 if (ret) {
3833 errno = ret;
3834 PERROR("pthread_join dispatcher_thread");
3835 retval = -1;
b8aa1682 3836 }
178a0557 3837exit_dispatcher_thread:
42415026 3838
65931c8b 3839 ret = pthread_join(health_thread, &status);
178a0557
MD
3840 if (ret) {
3841 errno = ret;
3842 PERROR("pthread_join health_thread");
3843 retval = -1;
65931c8b 3844 }
178a0557 3845exit_health_thread:
65931c8b 3846
65931c8b 3847 utils_close_pipe(health_quit_pipe);
178a0557 3848exit_health_quit_pipe:
65931c8b 3849
178a0557 3850exit_init_data:
55706a7d 3851 health_app_destroy(health_relayd);
23c8ff50 3852 sessiond_trace_chunk_registry_destroy(sessiond_trace_chunk_registry);
55706a7d 3853exit_health_app_create:
23c8ff50 3854exit_sessiond_trace_chunk_registry:
178a0557 3855exit_options:
4d62fbf8
MD
3856 /*
3857 * Wait for all pending call_rcu work to complete before tearing
3858 * down data structures. call_rcu worker may be trying to
3859 * perform lookups in those structures.
3860 */
3861 rcu_barrier();
7591bab1
MD
3862 relayd_cleanup();
3863
3864 /* Ensure all prior call_rcu are done. */
3865 rcu_barrier();
d3e2ba59 3866
178a0557 3867 if (!retval) {
b8aa1682 3868 exit(EXIT_SUCCESS);
178a0557
MD
3869 } else {
3870 exit(EXIT_FAILURE);
b8aa1682 3871 }
b8aa1682 3872}
This page took 0.273077 seconds and 4 git commands to generate.