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