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