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