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