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