relayd: track the health quit pipe with the fd-tracker
[lttng-tools.git] / src / bin / lttng-relayd / main.c
1 /*
2 * Copyright (C) 2012 - Julien Desfossez <jdesfossez@efficios.com>
3 * David Goulet <dgoulet@efficios.com>
4 * 2013 - Jérémie Galarneau <jeremie.galarneau@efficios.com>
5 * 2015 - Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
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
21 #define _LGPL_SOURCE
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>
37 #include <sys/resource.h>
38 #include <inttypes.h>
39 #include <urcu/futex.h>
40 #include <urcu/uatomic.h>
41 #include <urcu/rculist.h>
42 #include <unistd.h>
43 #include <fcntl.h>
44 #include <strings.h>
45 #include <ctype.h>
46
47 #include <lttng/lttng.h>
48 #include <common/common.h>
49 #include <common/compat/poll.h>
50 #include <common/compat/socket.h>
51 #include <common/compat/endian.h>
52 #include <common/compat/getenv.h>
53 #include <common/defaults.h>
54 #include <common/daemonize.h>
55 #include <common/futex.h>
56 #include <common/sessiond-comm/sessiond-comm.h>
57 #include <common/sessiond-comm/inet.h>
58 #include <common/sessiond-comm/relayd.h>
59 #include <common/uri.h>
60 #include <common/utils.h>
61 #include <common/align.h>
62 #include <common/config/session-config.h>
63 #include <common/dynamic-buffer.h>
64 #include <common/buffer-view.h>
65 #include <common/string-utils/format.h>
66 #include <common/fd-tracker/fd-tracker.h>
67 #include <common/fd-tracker/utils.h>
68
69 #include "backward-compatibility-group-by.h"
70 #include "cmd.h"
71 #include "connection.h"
72 #include "ctf-trace.h"
73 #include "health-relayd.h"
74 #include "index.h"
75 #include "live.h"
76 #include "lttng-relayd.h"
77 #include "session.h"
78 #include "sessiond-trace-chunks.h"
79 #include "stream.h"
80 #include "tcp_keep_alive.h"
81 #include "testpoint.h"
82 #include "tracefile-array.h"
83 #include "utils.h"
84 #include "version.h"
85 #include "viewer-stream.h"
86
87 static const char *help_msg =
88 #ifdef LTTNG_EMBED_HELP
89 #include <lttng-relayd.8.h>
90 #else
91 NULL
92 #endif
93 ;
94
95 enum relay_connection_status {
96 RELAY_CONNECTION_STATUS_OK,
97 /* An error occurred while processing an event on the connection. */
98 RELAY_CONNECTION_STATUS_ERROR,
99 /* Connection closed/shutdown cleanly. */
100 RELAY_CONNECTION_STATUS_CLOSED,
101 };
102
103 /* command line options */
104 char *opt_output_path, *opt_working_directory;
105 static int opt_daemon, opt_background, opt_print_version, opt_allow_clear = 1;
106 enum relay_group_output_by opt_group_output_by = RELAYD_GROUP_OUTPUT_BY_UNKNOWN;
107
108 /*
109 * We need to wait for listener and live listener threads, as well as
110 * health check thread, before being ready to signal readiness.
111 */
112 #define NR_LTTNG_RELAY_READY 3
113 static int lttng_relay_ready = NR_LTTNG_RELAY_READY;
114
115 /* Size of receive buffer. */
116 #define RECV_DATA_BUFFER_SIZE 65536
117
118 static int recv_child_signal; /* Set to 1 when a SIGUSR1 signal is received. */
119 static pid_t child_ppid; /* Internal parent PID use with daemonize. */
120
121 static struct lttng_uri *control_uri;
122 static struct lttng_uri *data_uri;
123 static struct lttng_uri *live_uri;
124
125 const char *progname;
126
127 const char *tracing_group_name = DEFAULT_TRACING_GROUP;
128 static int tracing_group_name_override;
129
130 const char * const config_section_name = "relayd";
131
132 /*
133 * Quit pipe for all threads. This permits a single cancellation point
134 * for all threads when receiving an event on the pipe.
135 */
136 int thread_quit_pipe[2] = { -1, -1 };
137
138 /*
139 * This pipe is used to inform the worker thread that a command is queued and
140 * ready to be processed.
141 */
142 static int relay_conn_pipe[2] = { -1, -1 };
143
144 /* Shared between threads */
145 static int dispatch_thread_exit;
146
147 static pthread_t listener_thread;
148 static pthread_t dispatcher_thread;
149 static pthread_t worker_thread;
150 static pthread_t health_thread;
151
152 /*
153 * last_relay_stream_id_lock protects last_relay_stream_id increment
154 * atomicity on 32-bit architectures.
155 */
156 static pthread_mutex_t last_relay_stream_id_lock = PTHREAD_MUTEX_INITIALIZER;
157 static uint64_t last_relay_stream_id;
158
159 /*
160 * Relay command queue.
161 *
162 * The relay_thread_listener and relay_thread_dispatcher communicate with this
163 * queue.
164 */
165 static struct relay_conn_queue relay_conn_queue;
166
167 /* Cap of file desriptors to be in simultaneous use by the relay daemon. */
168 static unsigned int lttng_opt_fd_cap;
169
170 /* Global relay stream hash table. */
171 struct lttng_ht *relay_streams_ht;
172
173 /* Global relay viewer stream hash table. */
174 struct lttng_ht *viewer_streams_ht;
175
176 /* Global relay sessions hash table. */
177 struct lttng_ht *sessions_ht;
178
179 /* Relayd health monitoring */
180 struct health_app *health_relayd;
181
182 struct sessiond_trace_chunk_registry *sessiond_trace_chunk_registry;
183
184 /* Global fd tracker. */
185 struct fd_tracker *the_fd_tracker;
186
187 static struct option long_options[] = {
188 { "control-port", 1, 0, 'C', },
189 { "data-port", 1, 0, 'D', },
190 { "live-port", 1, 0, 'L', },
191 { "daemonize", 0, 0, 'd', },
192 { "background", 0, 0, 'b', },
193 { "group", 1, 0, 'g', },
194 { "fd-cap", 1, 0, '\0', },
195 { "help", 0, 0, 'h', },
196 { "output", 1, 0, 'o', },
197 { "verbose", 0, 0, 'v', },
198 { "config", 1, 0, 'f' },
199 { "version", 0, 0, 'V' },
200 { "working-directory", 1, 0, 'w', },
201 { "group-output-by-session", 0, 0, 's', },
202 { "group-output-by-host", 0, 0, 'p', },
203 { "disallow-clear", 0, 0, 'x' },
204 { NULL, 0, 0, 0, },
205 };
206
207 static const char *config_ignore_options[] = { "help", "config", "version" };
208
209 static void print_version(void) {
210 fprintf(stdout, "%s\n", VERSION);
211 }
212
213 static void relayd_config_log(void)
214 {
215 DBG("LTTng-relayd " VERSION " - " VERSION_NAME "%s%s",
216 GIT_VERSION[0] == '\0' ? "" : " - " GIT_VERSION,
217 EXTRA_VERSION_NAME[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME);
218 if (EXTRA_VERSION_DESCRIPTION[0] != '\0') {
219 DBG("LTTng-relayd extra version description:\n\t" EXTRA_VERSION_DESCRIPTION "\n");
220 }
221 if (EXTRA_VERSION_PATCHES[0] != '\0') {
222 DBG("LTTng-relayd extra patches:\n\t" EXTRA_VERSION_PATCHES "\n");
223 }
224 }
225
226 /*
227 * Take an option from the getopt output and set it in the right variable to be
228 * used later.
229 *
230 * Return 0 on success else a negative value.
231 */
232 static int set_option(int opt, const char *arg, const char *optname)
233 {
234 int ret;
235
236 switch (opt) {
237 case 0:
238 if (!strcmp(optname, "fd-cap")) {
239 unsigned long v;
240
241 errno = 0;
242 v = strtoul(arg, NULL, 0);
243 if (errno != 0 || !isdigit(arg[0])) {
244 ERR("Wrong value in --fd-cap parameter: %s",
245 arg);
246 ret = -1;
247 goto end;
248 }
249 if (v < DEFAULT_RELAYD_MINIMAL_FD_CAP) {
250 ERR("File descriptor cap must be set to at least %d",
251 DEFAULT_RELAYD_MINIMAL_FD_CAP);
252 }
253 if (v >= UINT_MAX) {
254 ERR("File descriptor cap overflow in --fd-cap parameter: %s",
255 arg);
256 ret = -1;
257 goto end;
258 }
259 lttng_opt_fd_cap = (unsigned int) v;
260 DBG3("File descriptor cap set to %u", lttng_opt_fd_cap);
261 } else {
262 fprintf(stderr, "unknown option %s", optname);
263 if (arg) {
264 fprintf(stderr, " with arg %s\n", arg);
265 }
266 }
267 break;
268 case 'C':
269 if (lttng_is_setuid_setgid()) {
270 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
271 "-C, --control-port");
272 } else {
273 ret = uri_parse(arg, &control_uri);
274 if (ret < 0) {
275 ERR("Invalid control URI specified");
276 goto end;
277 }
278 if (control_uri->port == 0) {
279 control_uri->port = DEFAULT_NETWORK_CONTROL_PORT;
280 }
281 }
282 break;
283 case 'D':
284 if (lttng_is_setuid_setgid()) {
285 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
286 "-D, -data-port");
287 } else {
288 ret = uri_parse(arg, &data_uri);
289 if (ret < 0) {
290 ERR("Invalid data URI specified");
291 goto end;
292 }
293 if (data_uri->port == 0) {
294 data_uri->port = DEFAULT_NETWORK_DATA_PORT;
295 }
296 }
297 break;
298 case 'L':
299 if (lttng_is_setuid_setgid()) {
300 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
301 "-L, -live-port");
302 } else {
303 ret = uri_parse(arg, &live_uri);
304 if (ret < 0) {
305 ERR("Invalid live URI specified");
306 goto end;
307 }
308 if (live_uri->port == 0) {
309 live_uri->port = DEFAULT_NETWORK_VIEWER_PORT;
310 }
311 }
312 break;
313 case 'd':
314 opt_daemon = 1;
315 break;
316 case 'b':
317 opt_background = 1;
318 break;
319 case 'g':
320 if (lttng_is_setuid_setgid()) {
321 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
322 "-g, --group");
323 } else {
324 tracing_group_name = strdup(arg);
325 if (tracing_group_name == NULL) {
326 ret = -errno;
327 PERROR("strdup");
328 goto end;
329 }
330 tracing_group_name_override = 1;
331 }
332 break;
333 case 'h':
334 ret = utils_show_help(8, "lttng-relayd", help_msg);
335 if (ret) {
336 ERR("Cannot show --help for `lttng-relayd`");
337 perror("exec");
338 }
339 exit(EXIT_FAILURE);
340 case 'V':
341 opt_print_version = 1;
342 break;
343 case 'o':
344 if (lttng_is_setuid_setgid()) {
345 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
346 "-o, --output");
347 } else {
348 ret = asprintf(&opt_output_path, "%s", arg);
349 if (ret < 0) {
350 ret = -errno;
351 PERROR("asprintf opt_output_path");
352 goto end;
353 }
354 }
355 break;
356 case 'w':
357 if (lttng_is_setuid_setgid()) {
358 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
359 "-w, --working-directory");
360 } else {
361 ret = asprintf(&opt_working_directory, "%s", arg);
362 if (ret < 0) {
363 ret = -errno;
364 PERROR("asprintf opt_working_directory");
365 goto end;
366 }
367 }
368 break;
369
370 case 'v':
371 /* Verbose level can increase using multiple -v */
372 if (arg) {
373 lttng_opt_verbose = config_parse_value(arg);
374 } else {
375 /* Only 3 level of verbosity (-vvv). */
376 if (lttng_opt_verbose < 3) {
377 lttng_opt_verbose += 1;
378 }
379 }
380 break;
381 case 's':
382 if (opt_group_output_by != RELAYD_GROUP_OUTPUT_BY_UNKNOWN) {
383 ERR("Cannot set --group-output-by-session, another --group-output-by argument is present");
384 exit(EXIT_FAILURE);
385 }
386 opt_group_output_by = RELAYD_GROUP_OUTPUT_BY_SESSION;
387 break;
388 case 'p':
389 if (opt_group_output_by != RELAYD_GROUP_OUTPUT_BY_UNKNOWN) {
390 ERR("Cannot set --group-output-by-host, another --group-output-by argument is present");
391 exit(EXIT_FAILURE);
392 }
393 opt_group_output_by = RELAYD_GROUP_OUTPUT_BY_HOST;
394 break;
395 case 'x':
396 /* Disallow clear */
397 opt_allow_clear = 0;
398 break;
399 default:
400 /* Unknown option or other error.
401 * Error is printed by getopt, just return */
402 ret = -1;
403 goto end;
404 }
405
406 /* All good. */
407 ret = 0;
408
409 end:
410 return ret;
411 }
412
413 /*
414 * config_entry_handler_cb used to handle options read from a config file.
415 * See config_entry_handler_cb comment in common/config/session-config.h for the
416 * return value conventions.
417 */
418 static int config_entry_handler(const struct config_entry *entry, void *unused)
419 {
420 int ret = 0, i;
421
422 if (!entry || !entry->name || !entry->value) {
423 ret = -EINVAL;
424 goto end;
425 }
426
427 /* Check if the option is to be ignored */
428 for (i = 0; i < sizeof(config_ignore_options) / sizeof(char *); i++) {
429 if (!strcmp(entry->name, config_ignore_options[i])) {
430 goto end;
431 }
432 }
433
434 for (i = 0; i < (sizeof(long_options) / sizeof(struct option)) - 1; i++) {
435 /* Ignore if entry name is not fully matched. */
436 if (strcmp(entry->name, long_options[i].name)) {
437 continue;
438 }
439
440 /*
441 * If the option takes no argument on the command line,
442 * we have to check if the value is "true". We support
443 * non-zero numeric values, true, on and yes.
444 */
445 if (!long_options[i].has_arg) {
446 ret = config_parse_value(entry->value);
447 if (ret <= 0) {
448 if (ret) {
449 WARN("Invalid configuration value \"%s\" for option %s",
450 entry->value, entry->name);
451 }
452 /* False, skip boolean config option. */
453 goto end;
454 }
455 }
456
457 ret = set_option(long_options[i].val, entry->value, entry->name);
458 goto end;
459 }
460
461 WARN("Unrecognized option \"%s\" in daemon configuration file.",
462 entry->name);
463
464 end:
465 return ret;
466 }
467
468 static int parse_env_options(void)
469 {
470 int ret = 0;
471 char *value = NULL;
472
473 value = lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV);
474 if (value) {
475 opt_working_directory = strdup(value);
476 if (!opt_working_directory) {
477 ERR("Failed to allocate working directory string (\"%s\")",
478 value);
479 ret = -1;
480 }
481 }
482 return ret;
483 }
484
485 static int set_options(int argc, char **argv)
486 {
487 int c, ret = 0, option_index = 0, retval = 0;
488 int orig_optopt = optopt, orig_optind = optind;
489 char *default_address, *optstring;
490 const char *config_path = NULL;
491
492 optstring = utils_generate_optstring(long_options,
493 sizeof(long_options) / sizeof(struct option));
494 if (!optstring) {
495 retval = -ENOMEM;
496 goto exit;
497 }
498
499 /* Check for the --config option */
500
501 while ((c = getopt_long(argc, argv, optstring, long_options,
502 &option_index)) != -1) {
503 if (c == '?') {
504 retval = -EINVAL;
505 goto exit;
506 } else if (c != 'f') {
507 continue;
508 }
509
510 if (lttng_is_setuid_setgid()) {
511 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
512 "-f, --config");
513 } else {
514 config_path = utils_expand_path(optarg);
515 if (!config_path) {
516 ERR("Failed to resolve path: %s", optarg);
517 }
518 }
519 }
520
521 ret = config_get_section_entries(config_path, config_section_name,
522 config_entry_handler, NULL);
523 if (ret) {
524 if (ret > 0) {
525 ERR("Invalid configuration option at line %i", ret);
526 }
527 retval = -1;
528 goto exit;
529 }
530
531 /* Reset getopt's global state */
532 optopt = orig_optopt;
533 optind = orig_optind;
534 while (1) {
535 c = getopt_long(argc, argv, optstring, long_options, &option_index);
536 if (c == -1) {
537 break;
538 }
539
540 ret = set_option(c, optarg, long_options[option_index].name);
541 if (ret < 0) {
542 retval = -1;
543 goto exit;
544 }
545 }
546
547 /* assign default values */
548 if (control_uri == NULL) {
549 ret = asprintf(&default_address,
550 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS ":%d",
551 DEFAULT_NETWORK_CONTROL_PORT);
552 if (ret < 0) {
553 PERROR("asprintf default data address");
554 retval = -1;
555 goto exit;
556 }
557
558 ret = uri_parse(default_address, &control_uri);
559 free(default_address);
560 if (ret < 0) {
561 ERR("Invalid control URI specified");
562 retval = -1;
563 goto exit;
564 }
565 }
566 if (data_uri == NULL) {
567 ret = asprintf(&default_address,
568 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS ":%d",
569 DEFAULT_NETWORK_DATA_PORT);
570 if (ret < 0) {
571 PERROR("asprintf default data address");
572 retval = -1;
573 goto exit;
574 }
575
576 ret = uri_parse(default_address, &data_uri);
577 free(default_address);
578 if (ret < 0) {
579 ERR("Invalid data URI specified");
580 retval = -1;
581 goto exit;
582 }
583 }
584 if (live_uri == NULL) {
585 ret = asprintf(&default_address,
586 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS ":%d",
587 DEFAULT_NETWORK_VIEWER_PORT);
588 if (ret < 0) {
589 PERROR("asprintf default viewer control address");
590 retval = -1;
591 goto exit;
592 }
593
594 ret = uri_parse(default_address, &live_uri);
595 free(default_address);
596 if (ret < 0) {
597 ERR("Invalid viewer control URI specified");
598 retval = -1;
599 goto exit;
600 }
601 }
602 if (lttng_opt_fd_cap == 0) {
603 int ret;
604 struct rlimit rlimit;
605
606 ret = getrlimit(RLIMIT_NOFILE, &rlimit);
607 if (ret) {
608 PERROR("Failed to get file descriptor limit");
609 retval = -1;
610 }
611
612 lttng_opt_fd_cap = rlimit.rlim_cur;
613 }
614
615 if (opt_group_output_by == RELAYD_GROUP_OUTPUT_BY_UNKNOWN) {
616 opt_group_output_by = RELAYD_GROUP_OUTPUT_BY_HOST;
617 }
618 if (opt_allow_clear) {
619 /* Check if env variable exists. */
620 const char *value = lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV);
621 if (value) {
622 ret = config_parse_value(value);
623 if (ret < 0) {
624 ERR("Invalid value for %s specified", DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV);
625 retval = -1;
626 goto exit;
627 }
628 opt_allow_clear = !ret;
629 }
630 }
631
632 exit:
633 free(optstring);
634 return retval;
635 }
636
637 static void print_global_objects(void)
638 {
639 print_viewer_streams();
640 print_relay_streams();
641 print_sessions();
642 }
643
644 /*
645 * Cleanup the daemon
646 */
647 static void relayd_cleanup(void)
648 {
649 print_global_objects();
650
651 DBG("Cleaning up");
652
653 if (viewer_streams_ht)
654 lttng_ht_destroy(viewer_streams_ht);
655 if (relay_streams_ht)
656 lttng_ht_destroy(relay_streams_ht);
657 if (sessions_ht)
658 lttng_ht_destroy(sessions_ht);
659
660 free(opt_output_path);
661 free(opt_working_directory);
662
663 if (health_relayd) {
664 health_app_destroy(health_relayd);
665 }
666 /* Close thread quit pipes */
667 if (health_quit_pipe[0] != -1) {
668 (void) fd_tracker_util_pipe_close(
669 the_fd_tracker, health_quit_pipe);
670 }
671 if (thread_quit_pipe[0] != -1) {
672 (void) fd_tracker_util_pipe_close(
673 the_fd_tracker, thread_quit_pipe);
674 }
675 if (sessiond_trace_chunk_registry) {
676 sessiond_trace_chunk_registry_destroy(
677 sessiond_trace_chunk_registry);
678 }
679 if (the_fd_tracker) {
680 fd_tracker_destroy(the_fd_tracker);
681 }
682
683 uri_free(control_uri);
684 uri_free(data_uri);
685 /* Live URI is freed in the live thread. */
686
687 if (tracing_group_name_override) {
688 free((void *) tracing_group_name);
689 }
690 fd_tracker_log(the_fd_tracker);
691 }
692
693 /*
694 * Write to writable pipe used to notify a thread.
695 */
696 static int notify_thread_pipe(int wpipe)
697 {
698 ssize_t ret;
699
700 ret = lttng_write(wpipe, "!", 1);
701 if (ret < 1) {
702 PERROR("write poll pipe");
703 goto end;
704 }
705 ret = 0;
706 end:
707 return ret;
708 }
709
710 static int notify_health_quit_pipe(int *pipe)
711 {
712 ssize_t ret;
713
714 ret = lttng_write(pipe[1], "4", 1);
715 if (ret < 1) {
716 PERROR("write relay health quit");
717 goto end;
718 }
719 ret = 0;
720 end:
721 return ret;
722 }
723
724 /*
725 * Stop all relayd and relayd-live threads.
726 */
727 int lttng_relay_stop_threads(void)
728 {
729 int retval = 0;
730
731 /* Stopping all threads */
732 DBG("Terminating all threads");
733 if (notify_thread_pipe(thread_quit_pipe[1])) {
734 ERR("write error on thread quit pipe");
735 retval = -1;
736 }
737
738 if (notify_health_quit_pipe(health_quit_pipe)) {
739 ERR("write error on health quit pipe");
740 }
741
742 /* Dispatch thread */
743 CMM_STORE_SHARED(dispatch_thread_exit, 1);
744 futex_nto1_wake(&relay_conn_queue.futex);
745
746 if (relayd_live_stop()) {
747 ERR("Error stopping live threads");
748 retval = -1;
749 }
750 return retval;
751 }
752
753 /*
754 * Signal handler for the daemon
755 *
756 * Simply stop all worker threads, leaving main() return gracefully after
757 * joining all threads and calling cleanup().
758 */
759 static void sighandler(int sig)
760 {
761 switch (sig) {
762 case SIGINT:
763 DBG("SIGINT caught");
764 if (lttng_relay_stop_threads()) {
765 ERR("Error stopping threads");
766 }
767 break;
768 case SIGTERM:
769 DBG("SIGTERM caught");
770 if (lttng_relay_stop_threads()) {
771 ERR("Error stopping threads");
772 }
773 break;
774 case SIGUSR1:
775 CMM_STORE_SHARED(recv_child_signal, 1);
776 break;
777 default:
778 break;
779 }
780 }
781
782 /*
783 * Setup signal handler for :
784 * SIGINT, SIGTERM, SIGPIPE
785 */
786 static int set_signal_handler(void)
787 {
788 int ret = 0;
789 struct sigaction sa;
790 sigset_t sigset;
791
792 if ((ret = sigemptyset(&sigset)) < 0) {
793 PERROR("sigemptyset");
794 return ret;
795 }
796
797 sa.sa_mask = sigset;
798 sa.sa_flags = 0;
799
800 sa.sa_handler = sighandler;
801 if ((ret = sigaction(SIGTERM, &sa, NULL)) < 0) {
802 PERROR("sigaction");
803 return ret;
804 }
805
806 if ((ret = sigaction(SIGINT, &sa, NULL)) < 0) {
807 PERROR("sigaction");
808 return ret;
809 }
810
811 if ((ret = sigaction(SIGUSR1, &sa, NULL)) < 0) {
812 PERROR("sigaction");
813 return ret;
814 }
815
816 sa.sa_handler = SIG_IGN;
817 if ((ret = sigaction(SIGPIPE, &sa, NULL)) < 0) {
818 PERROR("sigaction");
819 return ret;
820 }
821
822 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
823
824 return ret;
825 }
826
827 void lttng_relay_notify_ready(void)
828 {
829 /* Notify the parent of the fork() process that we are ready. */
830 if (opt_daemon || opt_background) {
831 if (uatomic_sub_return(&lttng_relay_ready, 1) == 0) {
832 kill(child_ppid, SIGUSR1);
833 }
834 }
835 }
836
837 /*
838 * Init thread quit pipe.
839 *
840 * Return -1 on error or 0 if all pipes are created.
841 */
842 static int init_thread_quit_pipe(void)
843 {
844 return fd_tracker_util_pipe_open_cloexec(
845 the_fd_tracker, "Quit pipe", thread_quit_pipe);
846 }
847
848 /*
849 * Init health quit pipe.
850 *
851 * Return -1 on error or 0 if all pipes are created.
852 */
853 static int init_health_quit_pipe(void)
854 {
855 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker,
856 "Health quit pipe", health_quit_pipe);
857 }
858
859 /*
860 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
861 */
862 static int create_thread_poll_set(struct lttng_poll_event *events, int size)
863 {
864 int ret;
865
866 if (events == NULL || size == 0) {
867 ret = -1;
868 goto error;
869 }
870
871 ret = lttng_poll_create(events, size, LTTNG_CLOEXEC);
872 if (ret < 0) {
873 goto error;
874 }
875
876 /* Add quit pipe */
877 ret = lttng_poll_add(events, thread_quit_pipe[0], LPOLLIN | LPOLLERR);
878 if (ret < 0) {
879 goto error;
880 }
881
882 return 0;
883
884 error:
885 return ret;
886 }
887
888 /*
889 * Check if the thread quit pipe was triggered.
890 *
891 * Return 1 if it was triggered else 0;
892 */
893 static int check_thread_quit_pipe(int fd, uint32_t events)
894 {
895 if (fd == thread_quit_pipe[0] && (events & LPOLLIN)) {
896 return 1;
897 }
898
899 return 0;
900 }
901
902 /*
903 * Create and init socket from uri.
904 */
905 static struct lttcomm_sock *relay_socket_create(struct lttng_uri *uri)
906 {
907 int ret;
908 struct lttcomm_sock *sock = NULL;
909
910 sock = lttcomm_alloc_sock_from_uri(uri);
911 if (sock == NULL) {
912 ERR("Allocating socket");
913 goto error;
914 }
915
916 ret = lttcomm_create_sock(sock);
917 if (ret < 0) {
918 goto error;
919 }
920 DBG("Listening on sock %d", sock->fd);
921
922 ret = sock->ops->bind(sock);
923 if (ret < 0) {
924 PERROR("Failed to bind socket");
925 goto error;
926 }
927
928 ret = sock->ops->listen(sock, -1);
929 if (ret < 0) {
930 goto error;
931
932 }
933
934 return sock;
935
936 error:
937 if (sock) {
938 lttcomm_destroy_sock(sock);
939 }
940 return NULL;
941 }
942
943 /*
944 * This thread manages the listening for new connections on the network
945 */
946 static void *relay_thread_listener(void *data)
947 {
948 int i, ret, pollfd, err = -1;
949 uint32_t revents, nb_fd;
950 struct lttng_poll_event events;
951 struct lttcomm_sock *control_sock, *data_sock;
952
953 DBG("[thread] Relay listener started");
954
955 health_register(health_relayd, HEALTH_RELAYD_TYPE_LISTENER);
956
957 health_code_update();
958
959 control_sock = relay_socket_create(control_uri);
960 if (!control_sock) {
961 goto error_sock_control;
962 }
963
964 data_sock = relay_socket_create(data_uri);
965 if (!data_sock) {
966 goto error_sock_relay;
967 }
968
969 /*
970 * Pass 3 as size here for the thread quit pipe, control and
971 * data socket.
972 */
973 ret = create_thread_poll_set(&events, 3);
974 if (ret < 0) {
975 goto error_create_poll;
976 }
977
978 /* Add the control socket */
979 ret = lttng_poll_add(&events, control_sock->fd, LPOLLIN | LPOLLRDHUP);
980 if (ret < 0) {
981 goto error_poll_add;
982 }
983
984 /* Add the data socket */
985 ret = lttng_poll_add(&events, data_sock->fd, LPOLLIN | LPOLLRDHUP);
986 if (ret < 0) {
987 goto error_poll_add;
988 }
989
990 lttng_relay_notify_ready();
991
992 if (testpoint(relayd_thread_listener)) {
993 goto error_testpoint;
994 }
995
996 while (1) {
997 health_code_update();
998
999 DBG("Listener accepting connections");
1000
1001 restart:
1002 health_poll_entry();
1003 ret = lttng_poll_wait(&events, -1);
1004 health_poll_exit();
1005 if (ret < 0) {
1006 /*
1007 * Restart interrupted system call.
1008 */
1009 if (errno == EINTR) {
1010 goto restart;
1011 }
1012 goto error;
1013 }
1014
1015 nb_fd = ret;
1016
1017 DBG("Relay new connection received");
1018 for (i = 0; i < nb_fd; i++) {
1019 health_code_update();
1020
1021 /* Fetch once the poll data */
1022 revents = LTTNG_POLL_GETEV(&events, i);
1023 pollfd = LTTNG_POLL_GETFD(&events, i);
1024
1025 /* Thread quit pipe has been closed. Killing thread. */
1026 ret = check_thread_quit_pipe(pollfd, revents);
1027 if (ret) {
1028 err = 0;
1029 goto exit;
1030 }
1031
1032 if (revents & LPOLLIN) {
1033 /*
1034 * A new connection is requested, therefore a
1035 * sessiond/consumerd connection is allocated in
1036 * this thread, enqueued to a global queue and
1037 * dequeued (and freed) in the worker thread.
1038 */
1039 int val = 1;
1040 struct relay_connection *new_conn;
1041 struct lttcomm_sock *newsock;
1042 enum connection_type type;
1043
1044 if (pollfd == data_sock->fd) {
1045 type = RELAY_DATA;
1046 newsock = data_sock->ops->accept(data_sock);
1047 DBG("Relay data connection accepted, socket %d",
1048 newsock->fd);
1049 } else {
1050 assert(pollfd == control_sock->fd);
1051 type = RELAY_CONTROL;
1052 newsock = control_sock->ops->accept(control_sock);
1053 DBG("Relay control connection accepted, socket %d",
1054 newsock->fd);
1055 }
1056 if (!newsock) {
1057 PERROR("accepting sock");
1058 goto error;
1059 }
1060
1061 ret = setsockopt(newsock->fd, SOL_SOCKET, SO_REUSEADDR, &val,
1062 sizeof(val));
1063 if (ret < 0) {
1064 PERROR("setsockopt inet");
1065 lttcomm_destroy_sock(newsock);
1066 goto error;
1067 }
1068
1069 ret = socket_apply_keep_alive_config(newsock->fd);
1070 if (ret < 0) {
1071 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
1072 newsock->fd);
1073 lttcomm_destroy_sock(newsock);
1074 goto error;
1075 }
1076
1077 new_conn = connection_create(newsock, type);
1078 if (!new_conn) {
1079 lttcomm_destroy_sock(newsock);
1080 goto error;
1081 }
1082
1083 /* Enqueue request for the dispatcher thread. */
1084 cds_wfcq_enqueue(&relay_conn_queue.head, &relay_conn_queue.tail,
1085 &new_conn->qnode);
1086
1087 /*
1088 * Wake the dispatch queue futex.
1089 * Implicit memory barrier with the
1090 * exchange in cds_wfcq_enqueue.
1091 */
1092 futex_nto1_wake(&relay_conn_queue.futex);
1093 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
1094 ERR("socket poll error");
1095 goto error;
1096 } else {
1097 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
1098 goto error;
1099 }
1100 }
1101 }
1102
1103 exit:
1104 error:
1105 error_poll_add:
1106 error_testpoint:
1107 lttng_poll_clean(&events);
1108 error_create_poll:
1109 if (data_sock->fd >= 0) {
1110 ret = data_sock->ops->close(data_sock);
1111 if (ret) {
1112 PERROR("close");
1113 }
1114 }
1115 lttcomm_destroy_sock(data_sock);
1116 error_sock_relay:
1117 if (control_sock->fd >= 0) {
1118 ret = control_sock->ops->close(control_sock);
1119 if (ret) {
1120 PERROR("close");
1121 }
1122 }
1123 lttcomm_destroy_sock(control_sock);
1124 error_sock_control:
1125 if (err) {
1126 health_error();
1127 ERR("Health error occurred in %s", __func__);
1128 }
1129 health_unregister(health_relayd);
1130 DBG("Relay listener thread cleanup complete");
1131 lttng_relay_stop_threads();
1132 return NULL;
1133 }
1134
1135 /*
1136 * This thread manages the dispatching of the requests to worker threads
1137 */
1138 static void *relay_thread_dispatcher(void *data)
1139 {
1140 int err = -1;
1141 ssize_t ret;
1142 struct cds_wfcq_node *node;
1143 struct relay_connection *new_conn = NULL;
1144
1145 DBG("[thread] Relay dispatcher started");
1146
1147 health_register(health_relayd, HEALTH_RELAYD_TYPE_DISPATCHER);
1148
1149 if (testpoint(relayd_thread_dispatcher)) {
1150 goto error_testpoint;
1151 }
1152
1153 health_code_update();
1154
1155 for (;;) {
1156 health_code_update();
1157
1158 /* Atomically prepare the queue futex */
1159 futex_nto1_prepare(&relay_conn_queue.futex);
1160
1161 if (CMM_LOAD_SHARED(dispatch_thread_exit)) {
1162 break;
1163 }
1164
1165 do {
1166 health_code_update();
1167
1168 /* Dequeue commands */
1169 node = cds_wfcq_dequeue_blocking(&relay_conn_queue.head,
1170 &relay_conn_queue.tail);
1171 if (node == NULL) {
1172 DBG("Woken up but nothing in the relay command queue");
1173 /* Continue thread execution */
1174 break;
1175 }
1176 new_conn = caa_container_of(node, struct relay_connection, qnode);
1177
1178 DBG("Dispatching request waiting on sock %d", new_conn->sock->fd);
1179
1180 /*
1181 * Inform worker thread of the new request. This
1182 * call is blocking so we can be assured that
1183 * the data will be read at some point in time
1184 * or wait to the end of the world :)
1185 */
1186 ret = lttng_write(relay_conn_pipe[1], &new_conn, sizeof(new_conn));
1187 if (ret < 0) {
1188 PERROR("write connection pipe");
1189 connection_put(new_conn);
1190 goto error;
1191 }
1192 } while (node != NULL);
1193
1194 /* Futex wait on queue. Blocking call on futex() */
1195 health_poll_entry();
1196 futex_nto1_wait(&relay_conn_queue.futex);
1197 health_poll_exit();
1198 }
1199
1200 /* Normal exit, no error */
1201 err = 0;
1202
1203 error:
1204 error_testpoint:
1205 if (err) {
1206 health_error();
1207 ERR("Health error occurred in %s", __func__);
1208 }
1209 health_unregister(health_relayd);
1210 DBG("Dispatch thread dying");
1211 lttng_relay_stop_threads();
1212 return NULL;
1213 }
1214
1215 static bool session_streams_have_index(const struct relay_session *session)
1216 {
1217 return session->minor >= 4 && !session->snapshot;
1218 }
1219
1220 /*
1221 * Handle the RELAYD_CREATE_SESSION command.
1222 *
1223 * On success, send back the session id or else return a negative value.
1224 */
1225 static int relay_create_session(const struct lttcomm_relayd_hdr *recv_hdr,
1226 struct relay_connection *conn,
1227 const struct lttng_buffer_view *payload)
1228 {
1229 int ret = 0;
1230 ssize_t send_ret;
1231 struct relay_session *session = NULL;
1232 struct lttcomm_relayd_create_session_reply_2_11 reply = {};
1233 char session_name[LTTNG_NAME_MAX] = {};
1234 char hostname[LTTNG_HOST_NAME_MAX] = {};
1235 uint32_t live_timer = 0;
1236 bool snapshot = false;
1237 bool session_name_contains_creation_timestamp = false;
1238 /* Left nil for peers < 2.11. */
1239 char base_path[LTTNG_PATH_MAX] = {};
1240 lttng_uuid sessiond_uuid = {};
1241 LTTNG_OPTIONAL(uint64_t) id_sessiond = {};
1242 LTTNG_OPTIONAL(uint64_t) current_chunk_id = {};
1243 LTTNG_OPTIONAL(time_t) creation_time = {};
1244 struct lttng_dynamic_buffer reply_payload;
1245
1246 lttng_dynamic_buffer_init(&reply_payload);
1247
1248 if (conn->minor < 4) {
1249 /* From 2.1 to 2.3 */
1250 ret = 0;
1251 } else if (conn->minor >= 4 && conn->minor < 11) {
1252 /* From 2.4 to 2.10 */
1253 ret = cmd_create_session_2_4(payload, session_name,
1254 hostname, &live_timer, &snapshot);
1255 } else {
1256 bool has_current_chunk;
1257 uint64_t current_chunk_id_value;
1258 time_t creation_time_value;
1259 uint64_t id_sessiond_value;
1260
1261 /* From 2.11 to ... */
1262 ret = cmd_create_session_2_11(payload, session_name, hostname,
1263 base_path, &live_timer, &snapshot, &id_sessiond_value,
1264 sessiond_uuid, &has_current_chunk,
1265 &current_chunk_id_value, &creation_time_value,
1266 &session_name_contains_creation_timestamp);
1267 if (lttng_uuid_is_nil(sessiond_uuid)) {
1268 /* The nil UUID is reserved for pre-2.11 clients. */
1269 ERR("Illegal nil UUID announced by peer in create session command");
1270 ret = -1;
1271 goto send_reply;
1272 }
1273 LTTNG_OPTIONAL_SET(&id_sessiond, id_sessiond_value);
1274 LTTNG_OPTIONAL_SET(&creation_time, creation_time_value);
1275 if (has_current_chunk) {
1276 LTTNG_OPTIONAL_SET(&current_chunk_id,
1277 current_chunk_id_value);
1278 }
1279 }
1280
1281 if (ret < 0) {
1282 goto send_reply;
1283 }
1284
1285 session = session_create(session_name, hostname, base_path, live_timer,
1286 snapshot, sessiond_uuid,
1287 id_sessiond.is_set ? &id_sessiond.value : NULL,
1288 current_chunk_id.is_set ? &current_chunk_id.value : NULL,
1289 creation_time.is_set ? &creation_time.value : NULL,
1290 conn->major, conn->minor,
1291 session_name_contains_creation_timestamp);
1292 if (!session) {
1293 ret = -1;
1294 goto send_reply;
1295 }
1296 assert(!conn->session);
1297 conn->session = session;
1298 DBG("Created session %" PRIu64, session->id);
1299
1300 reply.generic.session_id = htobe64(session->id);
1301
1302 send_reply:
1303 if (ret < 0) {
1304 reply.generic.ret_code = htobe32(LTTNG_ERR_FATAL);
1305 } else {
1306 reply.generic.ret_code = htobe32(LTTNG_OK);
1307 }
1308
1309 if (conn->minor < 11) {
1310 /* From 2.1 to 2.10 */
1311 ret = lttng_dynamic_buffer_append(&reply_payload,
1312 &reply.generic, sizeof(reply.generic));
1313 if (ret) {
1314 ERR("Failed to append \"create session\" command reply header to payload buffer");
1315 ret = -1;
1316 goto end;
1317 }
1318 } else {
1319 const uint32_t output_path_length =
1320 session ? strlen(session->output_path) + 1 : 0;
1321
1322 reply.output_path_length = htobe32(output_path_length);
1323 ret = lttng_dynamic_buffer_append(
1324 &reply_payload, &reply, sizeof(reply));
1325 if (ret) {
1326 ERR("Failed to append \"create session\" command reply header to payload buffer");
1327 goto end;
1328 }
1329
1330 if (output_path_length) {
1331 ret = lttng_dynamic_buffer_append(&reply_payload,
1332 session->output_path,
1333 output_path_length);
1334 if (ret) {
1335 ERR("Failed to append \"create session\" command reply path to payload buffer");
1336 goto end;
1337 }
1338 }
1339 }
1340
1341 send_ret = conn->sock->ops->sendmsg(conn->sock, reply_payload.data,
1342 reply_payload.size, 0);
1343 if (send_ret < (ssize_t) reply_payload.size) {
1344 ERR("Failed to send \"create session\" command reply of %zu bytes (ret = %zd)",
1345 reply_payload.size, send_ret);
1346 ret = -1;
1347 }
1348 end:
1349 if (ret < 0 && session) {
1350 session_put(session);
1351 }
1352 lttng_dynamic_buffer_reset(&reply_payload);
1353 return ret;
1354 }
1355
1356 /*
1357 * When we have received all the streams and the metadata for a channel,
1358 * we make them visible to the viewer threads.
1359 */
1360 static void publish_connection_local_streams(struct relay_connection *conn)
1361 {
1362 struct relay_stream *stream;
1363 struct relay_session *session = conn->session;
1364
1365 /*
1366 * We publish all streams belonging to a session atomically wrt
1367 * session lock.
1368 */
1369 pthread_mutex_lock(&session->lock);
1370 rcu_read_lock();
1371 cds_list_for_each_entry_rcu(stream, &session->recv_list,
1372 recv_node) {
1373 stream_publish(stream);
1374 }
1375 rcu_read_unlock();
1376
1377 /*
1378 * Inform the viewer that there are new streams in the session.
1379 */
1380 if (session->viewer_attached) {
1381 uatomic_set(&session->new_streams, 1);
1382 }
1383 pthread_mutex_unlock(&session->lock);
1384 }
1385
1386 static int conform_channel_path(char *channel_path)
1387 {
1388 int ret = 0;
1389
1390 if (strstr("../", channel_path)) {
1391 ERR("Refusing channel path as it walks up the path hierarchy: \"%s\"",
1392 channel_path);
1393 ret = -1;
1394 goto end;
1395 }
1396
1397 if (*channel_path == '/') {
1398 const size_t len = strlen(channel_path);
1399
1400 /*
1401 * Channel paths from peers prior to 2.11 are expressed as an
1402 * absolute path that is, in reality, relative to the relay
1403 * daemon's output directory. Remove the leading slash so it
1404 * is correctly interpreted as a relative path later on.
1405 *
1406 * len (and not len - 1) is used to copy the trailing NULL.
1407 */
1408 bcopy(channel_path + 1, channel_path, len);
1409 }
1410 end:
1411 return ret;
1412 }
1413
1414 /*
1415 * relay_add_stream: allocate a new stream for a session
1416 */
1417 static int relay_add_stream(const struct lttcomm_relayd_hdr *recv_hdr,
1418 struct relay_connection *conn,
1419 const struct lttng_buffer_view *payload)
1420 {
1421 int ret;
1422 ssize_t send_ret;
1423 struct relay_session *session = conn->session;
1424 struct relay_stream *stream = NULL;
1425 struct lttcomm_relayd_status_stream reply;
1426 struct ctf_trace *trace = NULL;
1427 uint64_t stream_handle = -1ULL;
1428 char *path_name = NULL, *channel_name = NULL;
1429 uint64_t tracefile_size = 0, tracefile_count = 0;
1430 LTTNG_OPTIONAL(uint64_t) stream_chunk_id = {};
1431
1432 if (!session || !conn->version_check_done) {
1433 ERR("Trying to add a stream before version check");
1434 ret = -1;
1435 goto end_no_session;
1436 }
1437
1438 if (session->minor == 1) {
1439 /* For 2.1 */
1440 ret = cmd_recv_stream_2_1(payload, &path_name,
1441 &channel_name);
1442 } else if (session->minor > 1 && session->minor < 11) {
1443 /* From 2.2 to 2.10 */
1444 ret = cmd_recv_stream_2_2(payload, &path_name,
1445 &channel_name, &tracefile_size, &tracefile_count);
1446 } else {
1447 /* From 2.11 to ... */
1448 ret = cmd_recv_stream_2_11(payload, &path_name,
1449 &channel_name, &tracefile_size, &tracefile_count,
1450 &stream_chunk_id.value);
1451 stream_chunk_id.is_set = true;
1452 }
1453
1454 if (ret < 0) {
1455 goto send_reply;
1456 }
1457
1458 if (conform_channel_path(path_name)) {
1459 goto send_reply;
1460 }
1461
1462 /*
1463 * Backward compatibility for --group-output-by-session.
1464 * Prior to lttng 2.11, the complete path is passed by the stream.
1465 * Starting at 2.11, lttng-relayd uses chunk. When dealing with producer
1466 * >=2.11 the chunk is responsible for the output path. When dealing
1467 * with producer < 2.11 the chunk output_path is the root output path
1468 * and the stream carries the complete path (path_name).
1469 * To support --group-output-by-session with older producer (<2.11), we
1470 * need to craft the path based on the stream path.
1471 */
1472 if (opt_group_output_by == RELAYD_GROUP_OUTPUT_BY_SESSION) {
1473 if (conn->minor < 4) {
1474 /*
1475 * From 2.1 to 2.3, the session_name is not passed on
1476 * the RELAYD_CREATE_SESSION command. The session name
1477 * is necessary to detect the presence of a base_path
1478 * inside the stream path. Without it we cannot perform
1479 * a valid group-output-by-session transformation.
1480 */
1481 WARN("Unable to perform a --group-by-session transformation for session %" PRIu64
1482 " for stream with path \"%s\" as it is produced by a peer using a protocol older than v2.4",
1483 session->id, path_name);
1484 } else if (conn->minor >= 4 && conn->minor < 11) {
1485 char *group_by_session_path_name;
1486
1487 assert(session->session_name[0] != '\0');
1488
1489 group_by_session_path_name =
1490 backward_compat_group_by_session(
1491 path_name,
1492 session->session_name);
1493 if (!group_by_session_path_name) {
1494 ERR("Failed to apply group by session to stream of session %" PRIu64,
1495 session->id);
1496 goto send_reply;
1497 }
1498
1499 DBG("Transformed session path from \"%s\" to \"%s\" to honor per-session name grouping",
1500 path_name, group_by_session_path_name);
1501
1502 free(path_name);
1503 path_name = group_by_session_path_name;
1504 }
1505 }
1506
1507 trace = ctf_trace_get_by_path_or_create(session, path_name);
1508 if (!trace) {
1509 goto send_reply;
1510 }
1511
1512 /* This stream here has one reference on the trace. */
1513 pthread_mutex_lock(&last_relay_stream_id_lock);
1514 stream_handle = ++last_relay_stream_id;
1515 pthread_mutex_unlock(&last_relay_stream_id_lock);
1516
1517 /* We pass ownership of path_name and channel_name. */
1518 stream = stream_create(trace, stream_handle, path_name,
1519 channel_name, tracefile_size, tracefile_count);
1520 path_name = NULL;
1521 channel_name = NULL;
1522
1523 /*
1524 * Streams are the owners of their trace. Reference to trace is
1525 * kept within stream_create().
1526 */
1527 ctf_trace_put(trace);
1528
1529 send_reply:
1530 memset(&reply, 0, sizeof(reply));
1531 reply.handle = htobe64(stream_handle);
1532 if (!stream) {
1533 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1534 } else {
1535 reply.ret_code = htobe32(LTTNG_OK);
1536 }
1537
1538 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1539 sizeof(struct lttcomm_relayd_status_stream), 0);
1540 if (send_ret < (ssize_t) sizeof(reply)) {
1541 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1542 send_ret);
1543 ret = -1;
1544 }
1545
1546 end_no_session:
1547 free(path_name);
1548 free(channel_name);
1549 return ret;
1550 }
1551
1552 /*
1553 * relay_close_stream: close a specific stream
1554 */
1555 static int relay_close_stream(const struct lttcomm_relayd_hdr *recv_hdr,
1556 struct relay_connection *conn,
1557 const struct lttng_buffer_view *payload)
1558 {
1559 int ret;
1560 ssize_t send_ret;
1561 struct relay_session *session = conn->session;
1562 struct lttcomm_relayd_close_stream stream_info;
1563 struct lttcomm_relayd_generic_reply reply;
1564 struct relay_stream *stream;
1565
1566 DBG("Close stream received");
1567
1568 if (!session || !conn->version_check_done) {
1569 ERR("Trying to close a stream before version check");
1570 ret = -1;
1571 goto end_no_session;
1572 }
1573
1574 if (payload->size < sizeof(stream_info)) {
1575 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1576 sizeof(stream_info), payload->size);
1577 ret = -1;
1578 goto end_no_session;
1579 }
1580 memcpy(&stream_info, payload->data, sizeof(stream_info));
1581 stream_info.stream_id = be64toh(stream_info.stream_id);
1582 stream_info.last_net_seq_num = be64toh(stream_info.last_net_seq_num);
1583
1584 stream = stream_get_by_id(stream_info.stream_id);
1585 if (!stream) {
1586 ret = -1;
1587 goto end;
1588 }
1589
1590 /*
1591 * Set last_net_seq_num before the close flag. Required by data
1592 * pending check.
1593 */
1594 pthread_mutex_lock(&stream->lock);
1595 stream->last_net_seq_num = stream_info.last_net_seq_num;
1596 pthread_mutex_unlock(&stream->lock);
1597
1598 /*
1599 * This is one of the conditions which may trigger a stream close
1600 * with the others being:
1601 * 1) A close command is received for a stream
1602 * 2) The control connection owning the stream is closed
1603 * 3) We have received all of the stream's data _after_ a close
1604 * request.
1605 */
1606 try_stream_close(stream);
1607 if (stream->is_metadata) {
1608 struct relay_viewer_stream *vstream;
1609
1610 vstream = viewer_stream_get_by_id(stream->stream_handle);
1611 if (vstream) {
1612 if (stream->no_new_metadata_notified) {
1613 /*
1614 * Since all the metadata has been sent to the
1615 * viewer and that we have a request to close
1616 * its stream, we can safely teardown the
1617 * corresponding metadata viewer stream.
1618 */
1619 viewer_stream_put(vstream);
1620 }
1621 /* Put local reference. */
1622 viewer_stream_put(vstream);
1623 }
1624 }
1625 stream_put(stream);
1626 ret = 0;
1627
1628 end:
1629 memset(&reply, 0, sizeof(reply));
1630 if (ret < 0) {
1631 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1632 } else {
1633 reply.ret_code = htobe32(LTTNG_OK);
1634 }
1635 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1636 sizeof(struct lttcomm_relayd_generic_reply), 0);
1637 if (send_ret < (ssize_t) sizeof(reply)) {
1638 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1639 send_ret);
1640 ret = -1;
1641 }
1642
1643 end_no_session:
1644 return ret;
1645 }
1646
1647 /*
1648 * relay_reset_metadata: reset a metadata stream
1649 */
1650 static
1651 int relay_reset_metadata(const struct lttcomm_relayd_hdr *recv_hdr,
1652 struct relay_connection *conn,
1653 const struct lttng_buffer_view *payload)
1654 {
1655 int ret;
1656 ssize_t send_ret;
1657 struct relay_session *session = conn->session;
1658 struct lttcomm_relayd_reset_metadata stream_info;
1659 struct lttcomm_relayd_generic_reply reply;
1660 struct relay_stream *stream;
1661
1662 DBG("Reset metadata received");
1663
1664 if (!session || !conn->version_check_done) {
1665 ERR("Trying to reset a metadata stream before version check");
1666 ret = -1;
1667 goto end_no_session;
1668 }
1669
1670 if (payload->size < sizeof(stream_info)) {
1671 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1672 sizeof(stream_info), payload->size);
1673 ret = -1;
1674 goto end_no_session;
1675 }
1676 memcpy(&stream_info, payload->data, sizeof(stream_info));
1677 stream_info.stream_id = be64toh(stream_info.stream_id);
1678 stream_info.version = be64toh(stream_info.version);
1679
1680 DBG("Update metadata to version %" PRIu64, stream_info.version);
1681
1682 /* Unsupported for live sessions for now. */
1683 if (session->live_timer != 0) {
1684 ret = -1;
1685 goto end;
1686 }
1687
1688 stream = stream_get_by_id(stream_info.stream_id);
1689 if (!stream) {
1690 ret = -1;
1691 goto end;
1692 }
1693 pthread_mutex_lock(&stream->lock);
1694 if (!stream->is_metadata) {
1695 ret = -1;
1696 goto end_unlock;
1697 }
1698
1699 ret = stream_reset_file(stream);
1700 if (ret < 0) {
1701 ERR("Failed to reset metadata stream %" PRIu64
1702 ": stream_path = %s, channel = %s",
1703 stream->stream_handle, stream->path_name,
1704 stream->channel_name);
1705 goto end_unlock;
1706 }
1707 end_unlock:
1708 pthread_mutex_unlock(&stream->lock);
1709 stream_put(stream);
1710
1711 end:
1712 memset(&reply, 0, sizeof(reply));
1713 if (ret < 0) {
1714 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1715 } else {
1716 reply.ret_code = htobe32(LTTNG_OK);
1717 }
1718 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1719 sizeof(struct lttcomm_relayd_generic_reply), 0);
1720 if (send_ret < (ssize_t) sizeof(reply)) {
1721 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1722 send_ret);
1723 ret = -1;
1724 }
1725
1726 end_no_session:
1727 return ret;
1728 }
1729
1730 /*
1731 * relay_unknown_command: send -1 if received unknown command
1732 */
1733 static void relay_unknown_command(struct relay_connection *conn)
1734 {
1735 struct lttcomm_relayd_generic_reply reply;
1736 ssize_t send_ret;
1737
1738 memset(&reply, 0, sizeof(reply));
1739 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1740 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1741 if (send_ret < sizeof(reply)) {
1742 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret);
1743 }
1744 }
1745
1746 /*
1747 * relay_start: send an acknowledgment to the client to tell if we are
1748 * ready to receive data. We are ready if a session is established.
1749 */
1750 static int relay_start(const struct lttcomm_relayd_hdr *recv_hdr,
1751 struct relay_connection *conn,
1752 const struct lttng_buffer_view *payload)
1753 {
1754 int ret = 0;
1755 ssize_t send_ret;
1756 struct lttcomm_relayd_generic_reply reply;
1757 struct relay_session *session = conn->session;
1758
1759 if (!session) {
1760 DBG("Trying to start the streaming without a session established");
1761 ret = htobe32(LTTNG_ERR_UNK);
1762 }
1763
1764 memset(&reply, 0, sizeof(reply));
1765 reply.ret_code = htobe32(LTTNG_OK);
1766 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1767 sizeof(reply), 0);
1768 if (send_ret < (ssize_t) sizeof(reply)) {
1769 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1770 send_ret);
1771 ret = -1;
1772 }
1773
1774 return ret;
1775 }
1776
1777 /*
1778 * relay_recv_metadata: receive the metadata for the session.
1779 */
1780 static int relay_recv_metadata(const struct lttcomm_relayd_hdr *recv_hdr,
1781 struct relay_connection *conn,
1782 const struct lttng_buffer_view *payload)
1783 {
1784 int ret = 0;
1785 struct relay_session *session = conn->session;
1786 struct lttcomm_relayd_metadata_payload metadata_payload_header;
1787 struct relay_stream *metadata_stream;
1788 uint64_t metadata_payload_size;
1789 struct lttng_buffer_view packet_view;
1790
1791 if (!session) {
1792 ERR("Metadata sent before version check");
1793 ret = -1;
1794 goto end;
1795 }
1796
1797 if (recv_hdr->data_size < sizeof(struct lttcomm_relayd_metadata_payload)) {
1798 ERR("Incorrect data size");
1799 ret = -1;
1800 goto end;
1801 }
1802 metadata_payload_size = recv_hdr->data_size -
1803 sizeof(struct lttcomm_relayd_metadata_payload);
1804
1805 memcpy(&metadata_payload_header, payload->data,
1806 sizeof(metadata_payload_header));
1807 metadata_payload_header.stream_id = be64toh(
1808 metadata_payload_header.stream_id);
1809 metadata_payload_header.padding_size = be32toh(
1810 metadata_payload_header.padding_size);
1811
1812 metadata_stream = stream_get_by_id(metadata_payload_header.stream_id);
1813 if (!metadata_stream) {
1814 ret = -1;
1815 goto end;
1816 }
1817
1818 packet_view = lttng_buffer_view_from_view(payload,
1819 sizeof(metadata_payload_header), metadata_payload_size);
1820 if (!packet_view.data) {
1821 ERR("Invalid metadata packet length announced by header");
1822 ret = -1;
1823 goto end_put;
1824 }
1825
1826 pthread_mutex_lock(&metadata_stream->lock);
1827 ret = stream_write(metadata_stream, &packet_view,
1828 metadata_payload_header.padding_size);
1829 pthread_mutex_unlock(&metadata_stream->lock);
1830 if (ret){
1831 ret = -1;
1832 goto end_put;
1833 }
1834 end_put:
1835 stream_put(metadata_stream);
1836 end:
1837 return ret;
1838 }
1839
1840 /*
1841 * relay_send_version: send relayd version number
1842 */
1843 static int relay_send_version(const struct lttcomm_relayd_hdr *recv_hdr,
1844 struct relay_connection *conn,
1845 const struct lttng_buffer_view *payload)
1846 {
1847 int ret;
1848 ssize_t send_ret;
1849 struct lttcomm_relayd_version reply, msg;
1850 bool compatible = true;
1851
1852 conn->version_check_done = true;
1853
1854 /* Get version from the other side. */
1855 if (payload->size < sizeof(msg)) {
1856 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1857 sizeof(msg), payload->size);
1858 ret = -1;
1859 goto end;
1860 }
1861
1862 memcpy(&msg, payload->data, sizeof(msg));
1863 msg.major = be32toh(msg.major);
1864 msg.minor = be32toh(msg.minor);
1865
1866 memset(&reply, 0, sizeof(reply));
1867 reply.major = RELAYD_VERSION_COMM_MAJOR;
1868 reply.minor = RELAYD_VERSION_COMM_MINOR;
1869
1870 /* Major versions must be the same */
1871 if (reply.major != msg.major) {
1872 DBG("Incompatible major versions (%u vs %u), deleting session",
1873 reply.major, msg.major);
1874 compatible = false;
1875 }
1876
1877 conn->major = reply.major;
1878 /* We adapt to the lowest compatible version */
1879 if (reply.minor <= msg.minor) {
1880 conn->minor = reply.minor;
1881 } else {
1882 conn->minor = msg.minor;
1883 }
1884
1885 reply.major = htobe32(reply.major);
1886 reply.minor = htobe32(reply.minor);
1887 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1888 sizeof(reply), 0);
1889 if (send_ret < (ssize_t) sizeof(reply)) {
1890 ERR("Failed to send \"send version\" command reply (ret = %zd)",
1891 send_ret);
1892 ret = -1;
1893 goto end;
1894 } else {
1895 ret = 0;
1896 }
1897
1898 if (!compatible) {
1899 ret = -1;
1900 goto end;
1901 }
1902
1903 DBG("Version check done using protocol %u.%u", conn->major,
1904 conn->minor);
1905
1906 end:
1907 return ret;
1908 }
1909
1910 /*
1911 * Check for data pending for a given stream id from the session daemon.
1912 */
1913 static int relay_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
1914 struct relay_connection *conn,
1915 const struct lttng_buffer_view *payload)
1916 {
1917 struct relay_session *session = conn->session;
1918 struct lttcomm_relayd_data_pending msg;
1919 struct lttcomm_relayd_generic_reply reply;
1920 struct relay_stream *stream;
1921 ssize_t send_ret;
1922 int ret;
1923 uint64_t stream_seq;
1924
1925 DBG("Data pending command received");
1926
1927 if (!session || !conn->version_check_done) {
1928 ERR("Trying to check for data before version check");
1929 ret = -1;
1930 goto end_no_session;
1931 }
1932
1933 if (payload->size < sizeof(msg)) {
1934 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
1935 sizeof(msg), payload->size);
1936 ret = -1;
1937 goto end_no_session;
1938 }
1939 memcpy(&msg, payload->data, sizeof(msg));
1940 msg.stream_id = be64toh(msg.stream_id);
1941 msg.last_net_seq_num = be64toh(msg.last_net_seq_num);
1942
1943 stream = stream_get_by_id(msg.stream_id);
1944 if (stream == NULL) {
1945 ret = -1;
1946 goto end;
1947 }
1948
1949 pthread_mutex_lock(&stream->lock);
1950
1951 if (session_streams_have_index(session)) {
1952 /*
1953 * Ensure that both the index and stream data have been
1954 * flushed up to the requested point.
1955 */
1956 stream_seq = min(stream->prev_data_seq, stream->prev_index_seq);
1957 } else {
1958 stream_seq = stream->prev_data_seq;
1959 }
1960 DBG("Data pending for stream id %" PRIu64 ": prev_data_seq %" PRIu64
1961 ", prev_index_seq %" PRIu64
1962 ", and last_seq %" PRIu64, msg.stream_id,
1963 stream->prev_data_seq, stream->prev_index_seq,
1964 msg.last_net_seq_num);
1965
1966 /* Avoid wrapping issue */
1967 if (((int64_t) (stream_seq - msg.last_net_seq_num)) >= 0) {
1968 /* Data has in fact been written and is NOT pending */
1969 ret = 0;
1970 } else {
1971 /* Data still being streamed thus pending */
1972 ret = 1;
1973 }
1974
1975 stream->data_pending_check_done = true;
1976 pthread_mutex_unlock(&stream->lock);
1977
1978 stream_put(stream);
1979 end:
1980
1981 memset(&reply, 0, sizeof(reply));
1982 reply.ret_code = htobe32(ret);
1983 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1984 if (send_ret < (ssize_t) sizeof(reply)) {
1985 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
1986 send_ret);
1987 ret = -1;
1988 }
1989
1990 end_no_session:
1991 return ret;
1992 }
1993
1994 /*
1995 * Wait for the control socket to reach a quiescent state.
1996 *
1997 * Note that for now, when receiving this command from the session
1998 * daemon, this means that every subsequent commands or data received on
1999 * the control socket has been handled. So, this is why we simply return
2000 * OK here.
2001 */
2002 static int relay_quiescent_control(const struct lttcomm_relayd_hdr *recv_hdr,
2003 struct relay_connection *conn,
2004 const struct lttng_buffer_view *payload)
2005 {
2006 int ret;
2007 ssize_t send_ret;
2008 struct relay_stream *stream;
2009 struct lttcomm_relayd_quiescent_control msg;
2010 struct lttcomm_relayd_generic_reply reply;
2011
2012 DBG("Checking quiescent state on control socket");
2013
2014 if (!conn->session || !conn->version_check_done) {
2015 ERR("Trying to check for data before version check");
2016 ret = -1;
2017 goto end_no_session;
2018 }
2019
2020 if (payload->size < sizeof(msg)) {
2021 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2022 sizeof(msg), payload->size);
2023 ret = -1;
2024 goto end_no_session;
2025 }
2026 memcpy(&msg, payload->data, sizeof(msg));
2027 msg.stream_id = be64toh(msg.stream_id);
2028
2029 stream = stream_get_by_id(msg.stream_id);
2030 if (!stream) {
2031 goto reply;
2032 }
2033 pthread_mutex_lock(&stream->lock);
2034 stream->data_pending_check_done = true;
2035 pthread_mutex_unlock(&stream->lock);
2036
2037 DBG("Relay quiescent control pending flag set to %" PRIu64, msg.stream_id);
2038 stream_put(stream);
2039 reply:
2040 memset(&reply, 0, sizeof(reply));
2041 reply.ret_code = htobe32(LTTNG_OK);
2042 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2043 if (send_ret < (ssize_t) sizeof(reply)) {
2044 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
2045 send_ret);
2046 ret = -1;
2047 } else {
2048 ret = 0;
2049 }
2050
2051 end_no_session:
2052 return ret;
2053 }
2054
2055 /*
2056 * Initialize a data pending command. This means that a consumer is about
2057 * to ask for data pending for each stream it holds. Simply iterate over
2058 * all streams of a session and set the data_pending_check_done flag.
2059 *
2060 * This command returns to the client a LTTNG_OK code.
2061 */
2062 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
2063 struct relay_connection *conn,
2064 const struct lttng_buffer_view *payload)
2065 {
2066 int ret;
2067 ssize_t send_ret;
2068 struct lttng_ht_iter iter;
2069 struct lttcomm_relayd_begin_data_pending msg;
2070 struct lttcomm_relayd_generic_reply reply;
2071 struct relay_stream *stream;
2072
2073 assert(recv_hdr);
2074 assert(conn);
2075
2076 DBG("Init streams for data pending");
2077
2078 if (!conn->session || !conn->version_check_done) {
2079 ERR("Trying to check for data before version check");
2080 ret = -1;
2081 goto end_no_session;
2082 }
2083
2084 if (payload->size < sizeof(msg)) {
2085 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2086 sizeof(msg), payload->size);
2087 ret = -1;
2088 goto end_no_session;
2089 }
2090 memcpy(&msg, payload->data, sizeof(msg));
2091 msg.session_id = be64toh(msg.session_id);
2092
2093 /*
2094 * Iterate over all streams to set the begin data pending flag.
2095 * For now, the streams are indexed by stream handle so we have
2096 * to iterate over all streams to find the one associated with
2097 * the right session_id.
2098 */
2099 rcu_read_lock();
2100 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2101 node.node) {
2102 if (!stream_get(stream)) {
2103 continue;
2104 }
2105 if (stream->trace->session->id == msg.session_id) {
2106 pthread_mutex_lock(&stream->lock);
2107 stream->data_pending_check_done = false;
2108 pthread_mutex_unlock(&stream->lock);
2109 DBG("Set begin data pending flag to stream %" PRIu64,
2110 stream->stream_handle);
2111 }
2112 stream_put(stream);
2113 }
2114 rcu_read_unlock();
2115
2116 memset(&reply, 0, sizeof(reply));
2117 /* All good, send back reply. */
2118 reply.ret_code = htobe32(LTTNG_OK);
2119
2120 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2121 if (send_ret < (ssize_t) sizeof(reply)) {
2122 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2123 send_ret);
2124 ret = -1;
2125 } else {
2126 ret = 0;
2127 }
2128
2129 end_no_session:
2130 return ret;
2131 }
2132
2133 /*
2134 * End data pending command. This will check, for a given session id, if
2135 * each stream associated with it has its data_pending_check_done flag
2136 * set. If not, this means that the client lost track of the stream but
2137 * the data is still being streamed on our side. In this case, we inform
2138 * the client that data is in flight.
2139 *
2140 * Return to the client if there is data in flight or not with a ret_code.
2141 */
2142 static int relay_end_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
2143 struct relay_connection *conn,
2144 const struct lttng_buffer_view *payload)
2145 {
2146 int ret;
2147 ssize_t send_ret;
2148 struct lttng_ht_iter iter;
2149 struct lttcomm_relayd_end_data_pending msg;
2150 struct lttcomm_relayd_generic_reply reply;
2151 struct relay_stream *stream;
2152 uint32_t is_data_inflight = 0;
2153
2154 DBG("End data pending command");
2155
2156 if (!conn->session || !conn->version_check_done) {
2157 ERR("Trying to check for data before version check");
2158 ret = -1;
2159 goto end_no_session;
2160 }
2161
2162 if (payload->size < sizeof(msg)) {
2163 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2164 sizeof(msg), payload->size);
2165 ret = -1;
2166 goto end_no_session;
2167 }
2168 memcpy(&msg, payload->data, sizeof(msg));
2169 msg.session_id = be64toh(msg.session_id);
2170
2171 /*
2172 * Iterate over all streams to see if the begin data pending
2173 * flag is set.
2174 */
2175 rcu_read_lock();
2176 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2177 node.node) {
2178 if (!stream_get(stream)) {
2179 continue;
2180 }
2181 if (stream->trace->session->id != msg.session_id) {
2182 stream_put(stream);
2183 continue;
2184 }
2185 pthread_mutex_lock(&stream->lock);
2186 if (!stream->data_pending_check_done) {
2187 uint64_t stream_seq;
2188
2189 if (session_streams_have_index(conn->session)) {
2190 /*
2191 * Ensure that both the index and stream data have been
2192 * flushed up to the requested point.
2193 */
2194 stream_seq = min(stream->prev_data_seq, stream->prev_index_seq);
2195 } else {
2196 stream_seq = stream->prev_data_seq;
2197 }
2198 if (!stream->closed || !(((int64_t) (stream_seq - stream->last_net_seq_num)) >= 0)) {
2199 is_data_inflight = 1;
2200 DBG("Data is still in flight for stream %" PRIu64,
2201 stream->stream_handle);
2202 pthread_mutex_unlock(&stream->lock);
2203 stream_put(stream);
2204 break;
2205 }
2206 }
2207 pthread_mutex_unlock(&stream->lock);
2208 stream_put(stream);
2209 }
2210 rcu_read_unlock();
2211
2212 memset(&reply, 0, sizeof(reply));
2213 /* All good, send back reply. */
2214 reply.ret_code = htobe32(is_data_inflight);
2215
2216 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2217 if (send_ret < (ssize_t) sizeof(reply)) {
2218 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2219 send_ret);
2220 ret = -1;
2221 } else {
2222 ret = 0;
2223 }
2224
2225 end_no_session:
2226 return ret;
2227 }
2228
2229 /*
2230 * Receive an index for a specific stream.
2231 *
2232 * Return 0 on success else a negative value.
2233 */
2234 static int relay_recv_index(const struct lttcomm_relayd_hdr *recv_hdr,
2235 struct relay_connection *conn,
2236 const struct lttng_buffer_view *payload)
2237 {
2238 int ret;
2239 ssize_t send_ret;
2240 struct relay_session *session = conn->session;
2241 struct lttcomm_relayd_index index_info;
2242 struct lttcomm_relayd_generic_reply reply;
2243 struct relay_stream *stream;
2244 size_t msg_len;
2245
2246 assert(conn);
2247
2248 DBG("Relay receiving index");
2249
2250 if (!session || !conn->version_check_done) {
2251 ERR("Trying to close a stream before version check");
2252 ret = -1;
2253 goto end_no_session;
2254 }
2255
2256 msg_len = lttcomm_relayd_index_len(
2257 lttng_to_index_major(conn->major, conn->minor),
2258 lttng_to_index_minor(conn->major, conn->minor));
2259 if (payload->size < msg_len) {
2260 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2261 msg_len, payload->size);
2262 ret = -1;
2263 goto end_no_session;
2264 }
2265 memcpy(&index_info, payload->data, msg_len);
2266 index_info.relay_stream_id = be64toh(index_info.relay_stream_id);
2267 index_info.net_seq_num = be64toh(index_info.net_seq_num);
2268 index_info.packet_size = be64toh(index_info.packet_size);
2269 index_info.content_size = be64toh(index_info.content_size);
2270 index_info.timestamp_begin = be64toh(index_info.timestamp_begin);
2271 index_info.timestamp_end = be64toh(index_info.timestamp_end);
2272 index_info.events_discarded = be64toh(index_info.events_discarded);
2273 index_info.stream_id = be64toh(index_info.stream_id);
2274
2275 if (conn->minor >= 8) {
2276 index_info.stream_instance_id =
2277 be64toh(index_info.stream_instance_id);
2278 index_info.packet_seq_num = be64toh(index_info.packet_seq_num);
2279 } else {
2280 index_info.stream_instance_id = -1ULL;
2281 index_info.packet_seq_num = -1ULL;
2282 }
2283
2284 stream = stream_get_by_id(index_info.relay_stream_id);
2285 if (!stream) {
2286 ERR("stream_get_by_id not found");
2287 ret = -1;
2288 goto end;
2289 }
2290
2291 pthread_mutex_lock(&stream->lock);
2292 ret = stream_add_index(stream, &index_info);
2293 pthread_mutex_unlock(&stream->lock);
2294 if (ret) {
2295 goto end_stream_put;
2296 }
2297
2298 end_stream_put:
2299 stream_put(stream);
2300 end:
2301 memset(&reply, 0, sizeof(reply));
2302 if (ret < 0) {
2303 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2304 } else {
2305 reply.ret_code = htobe32(LTTNG_OK);
2306 }
2307 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2308 if (send_ret < (ssize_t) sizeof(reply)) {
2309 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret);
2310 ret = -1;
2311 }
2312
2313 end_no_session:
2314 return ret;
2315 }
2316
2317 /*
2318 * Receive the streams_sent message.
2319 *
2320 * Return 0 on success else a negative value.
2321 */
2322 static int relay_streams_sent(const struct lttcomm_relayd_hdr *recv_hdr,
2323 struct relay_connection *conn,
2324 const struct lttng_buffer_view *payload)
2325 {
2326 int ret;
2327 ssize_t send_ret;
2328 struct lttcomm_relayd_generic_reply reply;
2329
2330 assert(conn);
2331
2332 DBG("Relay receiving streams_sent");
2333
2334 if (!conn->session || !conn->version_check_done) {
2335 ERR("Trying to close a stream before version check");
2336 ret = -1;
2337 goto end_no_session;
2338 }
2339
2340 /*
2341 * Publish every pending stream in the connection recv list which are
2342 * now ready to be used by the viewer.
2343 */
2344 publish_connection_local_streams(conn);
2345
2346 memset(&reply, 0, sizeof(reply));
2347 reply.ret_code = htobe32(LTTNG_OK);
2348 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2349 if (send_ret < (ssize_t) sizeof(reply)) {
2350 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2351 send_ret);
2352 ret = -1;
2353 } else {
2354 /* Success. */
2355 ret = 0;
2356 }
2357
2358 end_no_session:
2359 return ret;
2360 }
2361
2362 /*
2363 * relay_rotate_session_stream: rotate a stream to a new tracefile for the
2364 * session rotation feature (not the tracefile rotation feature).
2365 */
2366 static int relay_rotate_session_streams(
2367 const struct lttcomm_relayd_hdr *recv_hdr,
2368 struct relay_connection *conn,
2369 const struct lttng_buffer_view *payload)
2370 {
2371 int ret = 0;
2372 uint32_t i;
2373 ssize_t send_ret;
2374 enum lttng_error_code reply_code = LTTNG_ERR_UNK;
2375 struct relay_session *session = conn->session;
2376 struct lttcomm_relayd_rotate_streams rotate_streams;
2377 struct lttcomm_relayd_generic_reply reply = {};
2378 struct relay_stream *stream = NULL;
2379 const size_t header_len = sizeof(struct lttcomm_relayd_rotate_streams);
2380 struct lttng_trace_chunk *next_trace_chunk = NULL;
2381 struct lttng_buffer_view stream_positions;
2382 char chunk_id_buf[MAX_INT_DEC_LEN(uint64_t)];
2383 const char *chunk_id_str = "none";
2384
2385 if (!session || !conn->version_check_done) {
2386 ERR("Trying to rotate a stream before version check");
2387 ret = -1;
2388 goto end_no_reply;
2389 }
2390
2391 if (session->major == 2 && session->minor < 11) {
2392 ERR("Unsupported feature before 2.11");
2393 ret = -1;
2394 goto end_no_reply;
2395 }
2396
2397 if (payload->size < header_len) {
2398 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2399 header_len, payload->size);
2400 ret = -1;
2401 goto end_no_reply;
2402 }
2403
2404 memcpy(&rotate_streams, payload->data, header_len);
2405
2406 /* Convert header to host endianness. */
2407 rotate_streams = (typeof(rotate_streams)) {
2408 .stream_count = be32toh(rotate_streams.stream_count),
2409 .new_chunk_id = (typeof(rotate_streams.new_chunk_id)) {
2410 .is_set = !!rotate_streams.new_chunk_id.is_set,
2411 .value = be64toh(rotate_streams.new_chunk_id.value),
2412 }
2413 };
2414
2415 if (rotate_streams.new_chunk_id.is_set) {
2416 /*
2417 * Retrieve the trace chunk the stream must transition to. As
2418 * per the protocol, this chunk should have been created
2419 * before this command is received.
2420 */
2421 next_trace_chunk = sessiond_trace_chunk_registry_get_chunk(
2422 sessiond_trace_chunk_registry,
2423 session->sessiond_uuid, session->id,
2424 rotate_streams.new_chunk_id.value);
2425 if (!next_trace_chunk) {
2426 char uuid_str[LTTNG_UUID_STR_LEN];
2427
2428 lttng_uuid_to_str(session->sessiond_uuid, uuid_str);
2429 ERR("Unknown next trace chunk in ROTATE_STREAMS command: sessiond_uuid = {%s}, session_id = %" PRIu64
2430 ", trace_chunk_id = %" PRIu64,
2431 uuid_str, session->id,
2432 rotate_streams.new_chunk_id.value);
2433 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2434 ret = -1;
2435 goto end;
2436 }
2437
2438 ret = snprintf(chunk_id_buf, sizeof(chunk_id_buf), "%" PRIu64,
2439 rotate_streams.new_chunk_id.value);
2440 if (ret < 0 || ret >= sizeof(chunk_id_buf)) {
2441 chunk_id_str = "formatting error";
2442 } else {
2443 chunk_id_str = chunk_id_buf;
2444 }
2445 }
2446
2447 DBG("Rotate %" PRIu32 " streams of session \"%s\" to chunk \"%s\"",
2448 rotate_streams.stream_count, session->session_name,
2449 chunk_id_str);
2450
2451 stream_positions = lttng_buffer_view_from_view(payload,
2452 sizeof(rotate_streams), -1);
2453 if (!stream_positions.data ||
2454 stream_positions.size <
2455 (rotate_streams.stream_count *
2456 sizeof(struct lttcomm_relayd_stream_rotation_position))) {
2457 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2458 ret = -1;
2459 goto end;
2460 }
2461
2462 for (i = 0; i < rotate_streams.stream_count; i++) {
2463 struct lttcomm_relayd_stream_rotation_position *position_comm =
2464 &((typeof(position_comm)) stream_positions.data)[i];
2465 const struct lttcomm_relayd_stream_rotation_position pos = {
2466 .stream_id = be64toh(position_comm->stream_id),
2467 .rotate_at_seq_num = be64toh(
2468 position_comm->rotate_at_seq_num),
2469 };
2470
2471 stream = stream_get_by_id(pos.stream_id);
2472 if (!stream) {
2473 reply_code = LTTNG_ERR_INVALID;
2474 ret = -1;
2475 goto end;
2476 }
2477
2478 pthread_mutex_lock(&stream->lock);
2479 ret = stream_set_pending_rotation(stream, next_trace_chunk,
2480 pos.rotate_at_seq_num);
2481 pthread_mutex_unlock(&stream->lock);
2482 if (ret) {
2483 reply_code = LTTNG_ERR_FILE_CREATION_ERROR;
2484 goto end;
2485 }
2486
2487 stream_put(stream);
2488 stream = NULL;
2489 }
2490
2491 reply_code = LTTNG_OK;
2492 ret = 0;
2493 end:
2494 if (stream) {
2495 stream_put(stream);
2496 }
2497
2498 reply.ret_code = htobe32((uint32_t) reply_code);
2499 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
2500 sizeof(struct lttcomm_relayd_generic_reply), 0);
2501 if (send_ret < (ssize_t) sizeof(reply)) {
2502 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2503 send_ret);
2504 ret = -1;
2505 }
2506 end_no_reply:
2507 lttng_trace_chunk_put(next_trace_chunk);
2508 return ret;
2509 }
2510
2511
2512
2513 /*
2514 * relay_create_trace_chunk: create a new trace chunk
2515 */
2516 static int relay_create_trace_chunk(const struct lttcomm_relayd_hdr *recv_hdr,
2517 struct relay_connection *conn,
2518 const struct lttng_buffer_view *payload)
2519 {
2520 int ret = 0;
2521 ssize_t send_ret;
2522 struct relay_session *session = conn->session;
2523 struct lttcomm_relayd_create_trace_chunk *msg;
2524 struct lttcomm_relayd_generic_reply reply = {};
2525 struct lttng_buffer_view header_view;
2526 struct lttng_buffer_view chunk_name_view;
2527 struct lttng_trace_chunk *chunk = NULL, *published_chunk = NULL;
2528 enum lttng_error_code reply_code = LTTNG_OK;
2529 enum lttng_trace_chunk_status chunk_status;
2530 struct lttng_directory_handle *session_output = NULL;
2531 const char *new_path;
2532
2533 if (!session || !conn->version_check_done) {
2534 ERR("Trying to create a trace chunk before version check");
2535 ret = -1;
2536 goto end_no_reply;
2537 }
2538
2539 if (session->major == 2 && session->minor < 11) {
2540 ERR("Chunk creation command is unsupported before 2.11");
2541 ret = -1;
2542 goto end_no_reply;
2543 }
2544
2545 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
2546 if (!header_view.data) {
2547 ERR("Failed to receive payload of chunk creation command");
2548 ret = -1;
2549 goto end_no_reply;
2550 }
2551
2552 /* Convert to host endianness. */
2553 msg = (typeof(msg)) header_view.data;
2554 msg->chunk_id = be64toh(msg->chunk_id);
2555 msg->creation_timestamp = be64toh(msg->creation_timestamp);
2556 msg->override_name_length = be32toh(msg->override_name_length);
2557
2558 if (session->current_trace_chunk &&
2559 !lttng_trace_chunk_get_name_overridden(session->current_trace_chunk)) {
2560 chunk_status = lttng_trace_chunk_rename_path(session->current_trace_chunk,
2561 DEFAULT_CHUNK_TMP_OLD_DIRECTORY);
2562 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2563 ERR("Failed to rename old chunk");
2564 ret = -1;
2565 reply_code = LTTNG_ERR_UNK;
2566 goto end;
2567 }
2568 }
2569 session->ongoing_rotation = true;
2570 if (!session->current_trace_chunk) {
2571 if (!session->has_rotated) {
2572 new_path = "";
2573 } else {
2574 new_path = NULL;
2575 }
2576 } else {
2577 new_path = DEFAULT_CHUNK_TMP_NEW_DIRECTORY;
2578 }
2579 chunk = lttng_trace_chunk_create(
2580 msg->chunk_id, msg->creation_timestamp, new_path);
2581 if (!chunk) {
2582 ERR("Failed to create trace chunk in trace chunk creation command");
2583 ret = -1;
2584 reply_code = LTTNG_ERR_NOMEM;
2585 goto end;
2586 }
2587
2588 if (msg->override_name_length) {
2589 const char *name;
2590
2591 chunk_name_view = lttng_buffer_view_from_view(payload,
2592 sizeof(*msg),
2593 msg->override_name_length);
2594 name = chunk_name_view.data;
2595 if (!name || name[msg->override_name_length - 1]) {
2596 ERR("Failed to receive payload of chunk creation command");
2597 ret = -1;
2598 reply_code = LTTNG_ERR_INVALID;
2599 goto end;
2600 }
2601
2602 chunk_status = lttng_trace_chunk_override_name(
2603 chunk, chunk_name_view.data);
2604 switch (chunk_status) {
2605 case LTTNG_TRACE_CHUNK_STATUS_OK:
2606 break;
2607 case LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT:
2608 ERR("Failed to set the name of new trace chunk in trace chunk creation command (invalid name)");
2609 reply_code = LTTNG_ERR_INVALID;
2610 ret = -1;
2611 goto end;
2612 default:
2613 ERR("Failed to set the name of new trace chunk in trace chunk creation command (unknown error)");
2614 reply_code = LTTNG_ERR_UNK;
2615 ret = -1;
2616 goto end;
2617 }
2618 }
2619
2620 chunk_status = lttng_trace_chunk_set_credentials_current_user(chunk);
2621 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2622 reply_code = LTTNG_ERR_UNK;
2623 ret = -1;
2624 goto end;
2625 }
2626
2627 session_output = session_create_output_directory_handle(
2628 conn->session);
2629 if (!session_output) {
2630 reply_code = LTTNG_ERR_CREATE_DIR_FAIL;
2631 goto end;
2632 }
2633 chunk_status = lttng_trace_chunk_set_as_owner(chunk, session_output);
2634 lttng_directory_handle_put(session_output);
2635 session_output = NULL;
2636 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2637 reply_code = LTTNG_ERR_UNK;
2638 ret = -1;
2639 goto end;
2640 }
2641
2642 published_chunk = sessiond_trace_chunk_registry_publish_chunk(
2643 sessiond_trace_chunk_registry,
2644 conn->session->sessiond_uuid,
2645 conn->session->id,
2646 chunk);
2647 if (!published_chunk) {
2648 char uuid_str[LTTNG_UUID_STR_LEN];
2649
2650 lttng_uuid_to_str(conn->session->sessiond_uuid, uuid_str);
2651 ERR("Failed to publish chunk: sessiond_uuid = %s, session_id = %" PRIu64 ", chunk_id = %" PRIu64,
2652 uuid_str,
2653 conn->session->id,
2654 msg->chunk_id);
2655 ret = -1;
2656 reply_code = LTTNG_ERR_NOMEM;
2657 goto end;
2658 }
2659
2660 pthread_mutex_lock(&conn->session->lock);
2661 if (conn->session->pending_closure_trace_chunk) {
2662 /*
2663 * Invalid; this means a second create_trace_chunk command was
2664 * received before a close_trace_chunk.
2665 */
2666 ERR("Invalid trace chunk close command received; a trace chunk is already waiting for a trace chunk close command");
2667 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2668 ret = -1;
2669 goto end_unlock_session;
2670 }
2671 conn->session->pending_closure_trace_chunk =
2672 conn->session->current_trace_chunk;
2673 conn->session->current_trace_chunk = published_chunk;
2674 published_chunk = NULL;
2675 if (!conn->session->pending_closure_trace_chunk) {
2676 session->ongoing_rotation = false;
2677 }
2678 end_unlock_session:
2679 pthread_mutex_unlock(&conn->session->lock);
2680 end:
2681 reply.ret_code = htobe32((uint32_t) reply_code);
2682 send_ret = conn->sock->ops->sendmsg(conn->sock,
2683 &reply,
2684 sizeof(struct lttcomm_relayd_generic_reply),
2685 0);
2686 if (send_ret < (ssize_t) sizeof(reply)) {
2687 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
2688 send_ret);
2689 ret = -1;
2690 }
2691 end_no_reply:
2692 lttng_trace_chunk_put(chunk);
2693 lttng_trace_chunk_put(published_chunk);
2694 lttng_directory_handle_put(session_output);
2695 return ret;
2696 }
2697
2698 /*
2699 * relay_close_trace_chunk: close a trace chunk
2700 */
2701 static int relay_close_trace_chunk(const struct lttcomm_relayd_hdr *recv_hdr,
2702 struct relay_connection *conn,
2703 const struct lttng_buffer_view *payload)
2704 {
2705 int ret = 0, buf_ret;
2706 ssize_t send_ret;
2707 struct relay_session *session = conn->session;
2708 struct lttcomm_relayd_close_trace_chunk *msg;
2709 struct lttcomm_relayd_close_trace_chunk_reply reply = {};
2710 struct lttng_buffer_view header_view;
2711 struct lttng_trace_chunk *chunk = NULL;
2712 enum lttng_error_code reply_code = LTTNG_OK;
2713 enum lttng_trace_chunk_status chunk_status;
2714 uint64_t chunk_id;
2715 LTTNG_OPTIONAL(enum lttng_trace_chunk_command_type) close_command = {};
2716 time_t close_timestamp;
2717 char closed_trace_chunk_path[LTTNG_PATH_MAX];
2718 size_t path_length = 0;
2719 const char *chunk_name = NULL;
2720 struct lttng_dynamic_buffer reply_payload;
2721 const char *new_path;
2722
2723 lttng_dynamic_buffer_init(&reply_payload);
2724
2725 if (!session || !conn->version_check_done) {
2726 ERR("Trying to close a trace chunk before version check");
2727 ret = -1;
2728 goto end_no_reply;
2729 }
2730
2731 if (session->major == 2 && session->minor < 11) {
2732 ERR("Chunk close command is unsupported before 2.11");
2733 ret = -1;
2734 goto end_no_reply;
2735 }
2736
2737 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
2738 if (!header_view.data) {
2739 ERR("Failed to receive payload of chunk close command");
2740 ret = -1;
2741 goto end_no_reply;
2742 }
2743
2744 /* Convert to host endianness. */
2745 msg = (typeof(msg)) header_view.data;
2746 chunk_id = be64toh(msg->chunk_id);
2747 close_timestamp = (time_t) be64toh(msg->close_timestamp);
2748 close_command = (typeof(close_command)){
2749 .value = be32toh(msg->close_command.value),
2750 .is_set = msg->close_command.is_set,
2751 };
2752
2753 chunk = sessiond_trace_chunk_registry_get_chunk(
2754 sessiond_trace_chunk_registry,
2755 conn->session->sessiond_uuid,
2756 conn->session->id,
2757 chunk_id);
2758 if (!chunk) {
2759 char uuid_str[LTTNG_UUID_STR_LEN];
2760
2761 lttng_uuid_to_str(conn->session->sessiond_uuid, uuid_str);
2762 ERR("Failed to find chunk to close: sessiond_uuid = %s, session_id = %" PRIu64 ", chunk_id = %" PRIu64,
2763 uuid_str,
2764 conn->session->id,
2765 msg->chunk_id);
2766 ret = -1;
2767 reply_code = LTTNG_ERR_NOMEM;
2768 goto end;
2769 }
2770
2771 pthread_mutex_lock(&session->lock);
2772 if (close_command.is_set &&
2773 close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE) {
2774 /*
2775 * Clear command. It is a protocol error to ask for a
2776 * clear on a relay which does not allow it. Querying
2777 * the configuration allows figuring out whether
2778 * clearing is allowed before doing the clear.
2779 */
2780 if (!opt_allow_clear) {
2781 ret = -1;
2782 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2783 goto end_unlock_session;
2784 }
2785 }
2786 if (session->pending_closure_trace_chunk &&
2787 session->pending_closure_trace_chunk != chunk) {
2788 ERR("Trace chunk close command for session \"%s\" does not target the trace chunk pending closure",
2789 session->session_name);
2790 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2791 ret = -1;
2792 goto end_unlock_session;
2793 }
2794
2795 if (session->current_trace_chunk && session->current_trace_chunk != chunk &&
2796 !lttng_trace_chunk_get_name_overridden(session->current_trace_chunk)) {
2797 if (close_command.is_set &&
2798 close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE &&
2799 !session->has_rotated) {
2800 /* New chunk stays in session output directory. */
2801 new_path = "";
2802 } else {
2803 /* Use chunk name for new chunk. */
2804 new_path = NULL;
2805 }
2806 /* Rename new chunk path. */
2807 chunk_status = lttng_trace_chunk_rename_path(session->current_trace_chunk,
2808 new_path);
2809 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2810 ret = -1;
2811 goto end;
2812 }
2813 session->ongoing_rotation = false;
2814 }
2815 if ((!close_command.is_set ||
2816 close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION) &&
2817 !lttng_trace_chunk_get_name_overridden(chunk)) {
2818 const char *old_path;
2819
2820 if (!session->has_rotated) {
2821 old_path = "";
2822 } else {
2823 old_path = NULL;
2824 }
2825 /* We need to move back the .tmp_old_chunk to its rightful place. */
2826 chunk_status = lttng_trace_chunk_rename_path(chunk, old_path);
2827 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2828 ret = -1;
2829 goto end;
2830 }
2831 }
2832 chunk_status = lttng_trace_chunk_set_close_timestamp(
2833 chunk, close_timestamp);
2834 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2835 ERR("Failed to set trace chunk close timestamp");
2836 ret = -1;
2837 reply_code = LTTNG_ERR_UNK;
2838 goto end_unlock_session;
2839 }
2840
2841 if (close_command.is_set) {
2842 chunk_status = lttng_trace_chunk_set_close_command(
2843 chunk, close_command.value);
2844 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2845 ret = -1;
2846 reply_code = LTTNG_ERR_INVALID;
2847 goto end_unlock_session;
2848 }
2849 }
2850 chunk_status = lttng_trace_chunk_get_name(chunk, &chunk_name, NULL);
2851 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2852 ERR("Failed to get chunk name");
2853 ret = -1;
2854 reply_code = LTTNG_ERR_UNK;
2855 goto end_unlock_session;
2856 }
2857 if (!session->has_rotated && !session->snapshot) {
2858 ret = lttng_strncpy(closed_trace_chunk_path,
2859 session->output_path,
2860 sizeof(closed_trace_chunk_path));
2861 if (ret) {
2862 ERR("Failed to send trace chunk path: path length of %zu bytes exceeds the maximal allowed length of %zu bytes",
2863 strlen(session->output_path),
2864 sizeof(closed_trace_chunk_path));
2865 reply_code = LTTNG_ERR_NOMEM;
2866 ret = -1;
2867 goto end_unlock_session;
2868 }
2869 } else {
2870 if (session->snapshot) {
2871 ret = snprintf(closed_trace_chunk_path,
2872 sizeof(closed_trace_chunk_path),
2873 "%s/%s", session->output_path,
2874 chunk_name);
2875 } else {
2876 ret = snprintf(closed_trace_chunk_path,
2877 sizeof(closed_trace_chunk_path),
2878 "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY
2879 "/%s",
2880 session->output_path, chunk_name);
2881 }
2882 if (ret < 0 || ret == sizeof(closed_trace_chunk_path)) {
2883 ERR("Failed to format closed trace chunk resulting path");
2884 reply_code = ret < 0 ? LTTNG_ERR_UNK : LTTNG_ERR_NOMEM;
2885 ret = -1;
2886 goto end_unlock_session;
2887 }
2888 }
2889 if (close_command.is_set &&
2890 close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED) {
2891 session->has_rotated = true;
2892 }
2893 DBG("Reply chunk path on close: %s", closed_trace_chunk_path);
2894 path_length = strlen(closed_trace_chunk_path) + 1;
2895 if (path_length > UINT32_MAX) {
2896 ERR("Closed trace chunk path exceeds the maximal length allowed by the protocol");
2897 ret = -1;
2898 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2899 goto end_unlock_session;
2900 }
2901
2902 if (session->current_trace_chunk == chunk) {
2903 /*
2904 * After a trace chunk close command, no new streams
2905 * referencing the chunk may be created. Hence, on the
2906 * event that no new trace chunk have been created for
2907 * the session, the reference to the current trace chunk
2908 * is released in order to allow it to be reclaimed when
2909 * the last stream releases its reference to it.
2910 */
2911 lttng_trace_chunk_put(session->current_trace_chunk);
2912 session->current_trace_chunk = NULL;
2913 }
2914 lttng_trace_chunk_put(session->pending_closure_trace_chunk);
2915 session->pending_closure_trace_chunk = NULL;
2916 end_unlock_session:
2917 pthread_mutex_unlock(&session->lock);
2918
2919 end:
2920 reply.generic.ret_code = htobe32((uint32_t) reply_code);
2921 reply.path_length = htobe32((uint32_t) path_length);
2922 buf_ret = lttng_dynamic_buffer_append(
2923 &reply_payload, &reply, sizeof(reply));
2924 if (buf_ret) {
2925 ERR("Failed to append \"close trace chunk\" command reply header to payload buffer");
2926 goto end_no_reply;
2927 }
2928
2929 if (reply_code == LTTNG_OK) {
2930 buf_ret = lttng_dynamic_buffer_append(&reply_payload,
2931 closed_trace_chunk_path, path_length);
2932 if (buf_ret) {
2933 ERR("Failed to append \"close trace chunk\" command reply path to payload buffer");
2934 goto end_no_reply;
2935 }
2936 }
2937
2938 send_ret = conn->sock->ops->sendmsg(conn->sock,
2939 reply_payload.data,
2940 reply_payload.size,
2941 0);
2942 if (send_ret < reply_payload.size) {
2943 ERR("Failed to send \"close trace chunk\" command reply of %zu bytes (ret = %zd)",
2944 reply_payload.size, send_ret);
2945 ret = -1;
2946 goto end_no_reply;
2947 }
2948 end_no_reply:
2949 lttng_trace_chunk_put(chunk);
2950 lttng_dynamic_buffer_reset(&reply_payload);
2951 return ret;
2952 }
2953
2954 /*
2955 * relay_trace_chunk_exists: check if a trace chunk exists
2956 */
2957 static int relay_trace_chunk_exists(const struct lttcomm_relayd_hdr *recv_hdr,
2958 struct relay_connection *conn,
2959 const struct lttng_buffer_view *payload)
2960 {
2961 int ret = 0;
2962 ssize_t send_ret;
2963 struct relay_session *session = conn->session;
2964 struct lttcomm_relayd_trace_chunk_exists *msg;
2965 struct lttcomm_relayd_trace_chunk_exists_reply reply = {};
2966 struct lttng_buffer_view header_view;
2967 uint64_t chunk_id;
2968 bool chunk_exists;
2969
2970 if (!session || !conn->version_check_done) {
2971 ERR("Trying to close a trace chunk before version check");
2972 ret = -1;
2973 goto end_no_reply;
2974 }
2975
2976 if (session->major == 2 && session->minor < 11) {
2977 ERR("Chunk close command is unsupported before 2.11");
2978 ret = -1;
2979 goto end_no_reply;
2980 }
2981
2982 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
2983 if (!header_view.data) {
2984 ERR("Failed to receive payload of chunk close command");
2985 ret = -1;
2986 goto end_no_reply;
2987 }
2988
2989 /* Convert to host endianness. */
2990 msg = (typeof(msg)) header_view.data;
2991 chunk_id = be64toh(msg->chunk_id);
2992
2993 ret = sessiond_trace_chunk_registry_chunk_exists(
2994 sessiond_trace_chunk_registry,
2995 conn->session->sessiond_uuid,
2996 conn->session->id,
2997 chunk_id, &chunk_exists);
2998 /*
2999 * If ret is not 0, send the reply and report the error to the caller.
3000 * It is a protocol (or internal) error and the session/connection
3001 * should be torn down.
3002 */
3003 reply = (typeof(reply)){
3004 .generic.ret_code = htobe32((uint32_t)
3005 (ret == 0 ? LTTNG_OK : LTTNG_ERR_INVALID_PROTOCOL)),
3006 .trace_chunk_exists = ret == 0 ? chunk_exists : 0,
3007 };
3008 send_ret = conn->sock->ops->sendmsg(
3009 conn->sock, &reply, sizeof(reply), 0);
3010 if (send_ret < (ssize_t) sizeof(reply)) {
3011 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
3012 send_ret);
3013 ret = -1;
3014 }
3015 end_no_reply:
3016 return ret;
3017 }
3018
3019 /*
3020 * relay_get_configuration: query whether feature is available
3021 */
3022 static int relay_get_configuration(const struct lttcomm_relayd_hdr *recv_hdr,
3023 struct relay_connection *conn,
3024 const struct lttng_buffer_view *payload)
3025 {
3026 int ret = 0;
3027 ssize_t send_ret;
3028 struct lttcomm_relayd_get_configuration *msg;
3029 struct lttcomm_relayd_get_configuration_reply reply = {};
3030 struct lttng_buffer_view header_view;
3031 uint64_t query_flags = 0;
3032 uint64_t result_flags = 0;
3033
3034 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
3035 if (!header_view.data) {
3036 ERR("Failed to receive payload of chunk close command");
3037 ret = -1;
3038 goto end_no_reply;
3039 }
3040
3041 /* Convert to host endianness. */
3042 msg = (typeof(msg)) header_view.data;
3043 query_flags = be64toh(msg->query_flags);
3044
3045 if (query_flags) {
3046 ret = LTTNG_ERR_INVALID_PROTOCOL;
3047 goto reply;
3048 }
3049 if (opt_allow_clear) {
3050 result_flags |= LTTCOMM_RELAYD_CONFIGURATION_FLAG_CLEAR_ALLOWED;
3051 }
3052 ret = 0;
3053 reply:
3054 reply = (typeof(reply)){
3055 .generic.ret_code = htobe32((uint32_t)
3056 (ret == 0 ? LTTNG_OK : LTTNG_ERR_INVALID_PROTOCOL)),
3057 .relayd_configuration_flags = htobe64(result_flags),
3058 };
3059 send_ret = conn->sock->ops->sendmsg(
3060 conn->sock, &reply, sizeof(reply), 0);
3061 if (send_ret < (ssize_t) sizeof(reply)) {
3062 ERR("Failed to send \"get configuration\" command reply (ret = %zd)",
3063 send_ret);
3064 ret = -1;
3065 }
3066 end_no_reply:
3067 return ret;
3068 }
3069
3070 #define DBG_CMD(cmd_name, conn) \
3071 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
3072
3073 static int relay_process_control_command(struct relay_connection *conn,
3074 const struct lttcomm_relayd_hdr *header,
3075 const struct lttng_buffer_view *payload)
3076 {
3077 int ret = 0;
3078
3079 switch (header->cmd) {
3080 case RELAYD_CREATE_SESSION:
3081 DBG_CMD("RELAYD_CREATE_SESSION", conn);
3082 ret = relay_create_session(header, conn, payload);
3083 break;
3084 case RELAYD_ADD_STREAM:
3085 DBG_CMD("RELAYD_ADD_STREAM", conn);
3086 ret = relay_add_stream(header, conn, payload);
3087 break;
3088 case RELAYD_START_DATA:
3089 DBG_CMD("RELAYD_START_DATA", conn);
3090 ret = relay_start(header, conn, payload);
3091 break;
3092 case RELAYD_SEND_METADATA:
3093 DBG_CMD("RELAYD_SEND_METADATA", conn);
3094 ret = relay_recv_metadata(header, conn, payload);
3095 break;
3096 case RELAYD_VERSION:
3097 DBG_CMD("RELAYD_VERSION", conn);
3098 ret = relay_send_version(header, conn, payload);
3099 break;
3100 case RELAYD_CLOSE_STREAM:
3101 DBG_CMD("RELAYD_CLOSE_STREAM", conn);
3102 ret = relay_close_stream(header, conn, payload);
3103 break;
3104 case RELAYD_DATA_PENDING:
3105 DBG_CMD("RELAYD_DATA_PENDING", conn);
3106 ret = relay_data_pending(header, conn, payload);
3107 break;
3108 case RELAYD_QUIESCENT_CONTROL:
3109 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn);
3110 ret = relay_quiescent_control(header, conn, payload);
3111 break;
3112 case RELAYD_BEGIN_DATA_PENDING:
3113 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn);
3114 ret = relay_begin_data_pending(header, conn, payload);
3115 break;
3116 case RELAYD_END_DATA_PENDING:
3117 DBG_CMD("RELAYD_END_DATA_PENDING", conn);
3118 ret = relay_end_data_pending(header, conn, payload);
3119 break;
3120 case RELAYD_SEND_INDEX:
3121 DBG_CMD("RELAYD_SEND_INDEX", conn);
3122 ret = relay_recv_index(header, conn, payload);
3123 break;
3124 case RELAYD_STREAMS_SENT:
3125 DBG_CMD("RELAYD_STREAMS_SENT", conn);
3126 ret = relay_streams_sent(header, conn, payload);
3127 break;
3128 case RELAYD_RESET_METADATA:
3129 DBG_CMD("RELAYD_RESET_METADATA", conn);
3130 ret = relay_reset_metadata(header, conn, payload);
3131 break;
3132 case RELAYD_ROTATE_STREAMS:
3133 DBG_CMD("RELAYD_ROTATE_STREAMS", conn);
3134 ret = relay_rotate_session_streams(header, conn, payload);
3135 break;
3136 case RELAYD_CREATE_TRACE_CHUNK:
3137 DBG_CMD("RELAYD_CREATE_TRACE_CHUNK", conn);
3138 ret = relay_create_trace_chunk(header, conn, payload);
3139 break;
3140 case RELAYD_CLOSE_TRACE_CHUNK:
3141 DBG_CMD("RELAYD_CLOSE_TRACE_CHUNK", conn);
3142 ret = relay_close_trace_chunk(header, conn, payload);
3143 break;
3144 case RELAYD_TRACE_CHUNK_EXISTS:
3145 DBG_CMD("RELAYD_TRACE_CHUNK_EXISTS", conn);
3146 ret = relay_trace_chunk_exists(header, conn, payload);
3147 break;
3148 case RELAYD_GET_CONFIGURATION:
3149 DBG_CMD("RELAYD_GET_CONFIGURATION", conn);
3150 ret = relay_get_configuration(header, conn, payload);
3151 break;
3152 case RELAYD_UPDATE_SYNC_INFO:
3153 default:
3154 ERR("Received unknown command (%u)", header->cmd);
3155 relay_unknown_command(conn);
3156 ret = -1;
3157 goto end;
3158 }
3159
3160 end:
3161 return ret;
3162 }