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