lttng-relayd: use TCP keep-alive mechanism to detect dead-peer
[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
1597 conn->version_check_done = 1;
1598
1599 /* Get version from the other side. */
1600 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
1601 if (ret < 0 || ret != sizeof(msg)) {
1602 if (ret == 0) {
1603 /* Orderly shutdown. Not necessary to print an error. */
1604 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1605 } else {
1606 ERR("Relay failed to receive the version values.");
1607 }
1608 ret = -1;
1609 goto end;
1610 }
1611
1612 memset(&reply, 0, sizeof(reply));
1613 reply.major = RELAYD_VERSION_COMM_MAJOR;
1614 reply.minor = RELAYD_VERSION_COMM_MINOR;
1615
1616 /* Major versions must be the same */
1617 if (reply.major != be32toh(msg.major)) {
1618 DBG("Incompatible major versions (%u vs %u), deleting session",
1619 reply.major, be32toh(msg.major));
1620 connection_put(conn);
1621 ret = 0;
1622 goto end;
1623 }
1624
1625 conn->major = reply.major;
1626 /* We adapt to the lowest compatible version */
1627 if (reply.minor <= be32toh(msg.minor)) {
1628 conn->minor = reply.minor;
1629 } else {
1630 conn->minor = be32toh(msg.minor);
1631 }
1632
1633 reply.major = htobe32(reply.major);
1634 reply.minor = htobe32(reply.minor);
1635 ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1636 sizeof(struct lttcomm_relayd_version), 0);
1637 if (ret < 0) {
1638 ERR("Relay sending version");
1639 }
1640
1641 DBG("Version check done using protocol %u.%u", conn->major,
1642 conn->minor);
1643
1644 end:
1645 return ret;
1646 }
1647
1648 /*
1649 * Check for data pending for a given stream id from the session daemon.
1650 */
1651 static int relay_data_pending(struct lttcomm_relayd_hdr *recv_hdr,
1652 struct relay_connection *conn)
1653 {
1654 struct relay_session *session = conn->session;
1655 struct lttcomm_relayd_data_pending msg;
1656 struct lttcomm_relayd_generic_reply reply;
1657 struct relay_stream *stream;
1658 int ret;
1659 uint64_t last_net_seq_num, stream_id;
1660
1661 DBG("Data pending command received");
1662
1663 if (!session || conn->version_check_done == 0) {
1664 ERR("Trying to check for data before version check");
1665 ret = -1;
1666 goto end_no_session;
1667 }
1668
1669 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
1670 if (ret < sizeof(msg)) {
1671 if (ret == 0) {
1672 /* Orderly shutdown. Not necessary to print an error. */
1673 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1674 } else {
1675 ERR("Relay didn't receive valid data_pending struct size : %d",
1676 ret);
1677 }
1678 ret = -1;
1679 goto end_no_session;
1680 }
1681
1682 stream_id = be64toh(msg.stream_id);
1683 last_net_seq_num = be64toh(msg.last_net_seq_num);
1684
1685 stream = stream_get_by_id(stream_id);
1686 if (stream == NULL) {
1687 ret = -1;
1688 goto end;
1689 }
1690
1691 pthread_mutex_lock(&stream->lock);
1692
1693 DBG("Data pending for stream id %" PRIu64 " prev_seq %" PRIu64
1694 " and last_seq %" PRIu64, stream_id, stream->prev_seq,
1695 last_net_seq_num);
1696
1697 /* Avoid wrapping issue */
1698 if (((int64_t) (stream->prev_seq - last_net_seq_num)) >= 0) {
1699 /* Data has in fact been written and is NOT pending */
1700 ret = 0;
1701 } else {
1702 /* Data still being streamed thus pending */
1703 ret = 1;
1704 }
1705
1706 stream->data_pending_check_done = true;
1707 pthread_mutex_unlock(&stream->lock);
1708
1709 stream_put(stream);
1710 end:
1711
1712 memset(&reply, 0, sizeof(reply));
1713 reply.ret_code = htobe32(ret);
1714 ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1715 if (ret < 0) {
1716 ERR("Relay data pending ret code failed");
1717 }
1718
1719 end_no_session:
1720 return ret;
1721 }
1722
1723 /*
1724 * Wait for the control socket to reach a quiescent state.
1725 *
1726 * Note that for now, when receiving this command from the session
1727 * daemon, this means that every subsequent commands or data received on
1728 * the control socket has been handled. So, this is why we simply return
1729 * OK here.
1730 */
1731 static int relay_quiescent_control(struct lttcomm_relayd_hdr *recv_hdr,
1732 struct relay_connection *conn)
1733 {
1734 int ret;
1735 uint64_t stream_id;
1736 struct relay_stream *stream;
1737 struct lttcomm_relayd_quiescent_control msg;
1738 struct lttcomm_relayd_generic_reply reply;
1739
1740 DBG("Checking quiescent state on control socket");
1741
1742 if (!conn->session || conn->version_check_done == 0) {
1743 ERR("Trying to check for data before version check");
1744 ret = -1;
1745 goto end_no_session;
1746 }
1747
1748 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
1749 if (ret < sizeof(msg)) {
1750 if (ret == 0) {
1751 /* Orderly shutdown. Not necessary to print an error. */
1752 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1753 } else {
1754 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1755 ret);
1756 }
1757 ret = -1;
1758 goto end_no_session;
1759 }
1760
1761 stream_id = be64toh(msg.stream_id);
1762 stream = stream_get_by_id(stream_id);
1763 if (!stream) {
1764 goto reply;
1765 }
1766 pthread_mutex_lock(&stream->lock);
1767 stream->data_pending_check_done = true;
1768 pthread_mutex_unlock(&stream->lock);
1769 DBG("Relay quiescent control pending flag set to %" PRIu64, stream_id);
1770 stream_put(stream);
1771 reply:
1772 memset(&reply, 0, sizeof(reply));
1773 reply.ret_code = htobe32(LTTNG_OK);
1774 ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1775 if (ret < 0) {
1776 ERR("Relay data quiescent control ret code failed");
1777 }
1778
1779 end_no_session:
1780 return ret;
1781 }
1782
1783 /*
1784 * Initialize a data pending command. This means that a consumer is about
1785 * to ask for data pending for each stream it holds. Simply iterate over
1786 * all streams of a session and set the data_pending_check_done flag.
1787 *
1788 * This command returns to the client a LTTNG_OK code.
1789 */
1790 static int relay_begin_data_pending(struct lttcomm_relayd_hdr *recv_hdr,
1791 struct relay_connection *conn)
1792 {
1793 int ret;
1794 struct lttng_ht_iter iter;
1795 struct lttcomm_relayd_begin_data_pending msg;
1796 struct lttcomm_relayd_generic_reply reply;
1797 struct relay_stream *stream;
1798 uint64_t session_id;
1799
1800 assert(recv_hdr);
1801 assert(conn);
1802
1803 DBG("Init streams for data pending");
1804
1805 if (!conn->session || conn->version_check_done == 0) {
1806 ERR("Trying to check for data before version check");
1807 ret = -1;
1808 goto end_no_session;
1809 }
1810
1811 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
1812 if (ret < sizeof(msg)) {
1813 if (ret == 0) {
1814 /* Orderly shutdown. Not necessary to print an error. */
1815 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1816 } else {
1817 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1818 ret);
1819 }
1820 ret = -1;
1821 goto end_no_session;
1822 }
1823
1824 session_id = be64toh(msg.session_id);
1825
1826 /*
1827 * Iterate over all streams to set the begin data pending flag.
1828 * For now, the streams are indexed by stream handle so we have
1829 * to iterate over all streams to find the one associated with
1830 * the right session_id.
1831 */
1832 rcu_read_lock();
1833 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
1834 node.node) {
1835 if (!stream_get(stream)) {
1836 continue;
1837 }
1838 if (stream->trace->session->id == session_id) {
1839 pthread_mutex_lock(&stream->lock);
1840 stream->data_pending_check_done = false;
1841 pthread_mutex_unlock(&stream->lock);
1842 DBG("Set begin data pending flag to stream %" PRIu64,
1843 stream->stream_handle);
1844 }
1845 stream_put(stream);
1846 }
1847 rcu_read_unlock();
1848
1849 memset(&reply, 0, sizeof(reply));
1850 /* All good, send back reply. */
1851 reply.ret_code = htobe32(LTTNG_OK);
1852
1853 ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1854 if (ret < 0) {
1855 ERR("Relay begin data pending send reply failed");
1856 }
1857
1858 end_no_session:
1859 return ret;
1860 }
1861
1862 /*
1863 * End data pending command. This will check, for a given session id, if
1864 * each stream associated with it has its data_pending_check_done flag
1865 * set. If not, this means that the client lost track of the stream but
1866 * the data is still being streamed on our side. In this case, we inform
1867 * the client that data is in flight.
1868 *
1869 * Return to the client if there is data in flight or not with a ret_code.
1870 */
1871 static int relay_end_data_pending(struct lttcomm_relayd_hdr *recv_hdr,
1872 struct relay_connection *conn)
1873 {
1874 int ret;
1875 struct lttng_ht_iter iter;
1876 struct lttcomm_relayd_end_data_pending msg;
1877 struct lttcomm_relayd_generic_reply reply;
1878 struct relay_stream *stream;
1879 uint64_t session_id;
1880 uint32_t is_data_inflight = 0;
1881
1882 DBG("End data pending command");
1883
1884 if (!conn->session || conn->version_check_done == 0) {
1885 ERR("Trying to check for data before version check");
1886 ret = -1;
1887 goto end_no_session;
1888 }
1889
1890 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
1891 if (ret < sizeof(msg)) {
1892 if (ret == 0) {
1893 /* Orderly shutdown. Not necessary to print an error. */
1894 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1895 } else {
1896 ERR("Relay didn't receive valid end data_pending struct size: %d",
1897 ret);
1898 }
1899 ret = -1;
1900 goto end_no_session;
1901 }
1902
1903 session_id = be64toh(msg.session_id);
1904
1905 /*
1906 * Iterate over all streams to see if the begin data pending
1907 * flag is set.
1908 */
1909 rcu_read_lock();
1910 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
1911 node.node) {
1912 if (!stream_get(stream)) {
1913 continue;
1914 }
1915 if (stream->trace->session->id != session_id) {
1916 stream_put(stream);
1917 continue;
1918 }
1919 pthread_mutex_lock(&stream->lock);
1920 if (!stream->data_pending_check_done) {
1921 if (!stream->closed || !(((int64_t) (stream->prev_seq - stream->last_net_seq_num)) >= 0)) {
1922 is_data_inflight = 1;
1923 DBG("Data is still in flight for stream %" PRIu64,
1924 stream->stream_handle);
1925 pthread_mutex_unlock(&stream->lock);
1926 stream_put(stream);
1927 break;
1928 }
1929 }
1930 pthread_mutex_unlock(&stream->lock);
1931 stream_put(stream);
1932 }
1933 rcu_read_unlock();
1934
1935 memset(&reply, 0, sizeof(reply));
1936 /* All good, send back reply. */
1937 reply.ret_code = htobe32(is_data_inflight);
1938
1939 ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1940 if (ret < 0) {
1941 ERR("Relay end data pending send reply failed");
1942 }
1943
1944 end_no_session:
1945 return ret;
1946 }
1947
1948 /*
1949 * Receive an index for a specific stream.
1950 *
1951 * Return 0 on success else a negative value.
1952 */
1953 static int relay_recv_index(struct lttcomm_relayd_hdr *recv_hdr,
1954 struct relay_connection *conn)
1955 {
1956 int ret, send_ret;
1957 struct relay_session *session = conn->session;
1958 struct lttcomm_relayd_index index_info;
1959 struct relay_index *index;
1960 struct lttcomm_relayd_generic_reply reply;
1961 struct relay_stream *stream;
1962 uint64_t net_seq_num;
1963 size_t msg_len;
1964
1965 assert(conn);
1966
1967 DBG("Relay receiving index");
1968
1969 if (!session || conn->version_check_done == 0) {
1970 ERR("Trying to close a stream before version check");
1971 ret = -1;
1972 goto end_no_session;
1973 }
1974
1975 msg_len = lttcomm_relayd_index_len(
1976 lttng_to_index_major(conn->major, conn->minor),
1977 lttng_to_index_minor(conn->major, conn->minor));
1978 ret = conn->sock->ops->recvmsg(conn->sock, &index_info,
1979 msg_len, 0);
1980 if (ret < msg_len) {
1981 if (ret == 0) {
1982 /* Orderly shutdown. Not necessary to print an error. */
1983 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1984 } else {
1985 ERR("Relay didn't receive valid index struct size : %d", ret);
1986 }
1987 ret = -1;
1988 goto end_no_session;
1989 }
1990
1991 net_seq_num = be64toh(index_info.net_seq_num);
1992
1993 stream = stream_get_by_id(be64toh(index_info.relay_stream_id));
1994 if (!stream) {
1995 ERR("stream_get_by_id not found");
1996 ret = -1;
1997 goto end;
1998 }
1999 pthread_mutex_lock(&stream->lock);
2000
2001 /* Live beacon handling */
2002 if (index_info.packet_size == 0) {
2003 DBG("Received live beacon for stream %" PRIu64,
2004 stream->stream_handle);
2005
2006 /*
2007 * Only flag a stream inactive when it has already
2008 * received data and no indexes are in flight.
2009 */
2010 if (stream->index_received_seqcount > 0
2011 && stream->indexes_in_flight == 0) {
2012 stream->beacon_ts_end =
2013 be64toh(index_info.timestamp_end);
2014 }
2015 ret = 0;
2016 goto end_stream_put;
2017 } else {
2018 stream->beacon_ts_end = -1ULL;
2019 }
2020
2021 if (stream->ctf_stream_id == -1ULL) {
2022 stream->ctf_stream_id = be64toh(index_info.stream_id);
2023 }
2024 index = relay_index_get_by_id_or_create(stream, net_seq_num);
2025 if (!index) {
2026 ret = -1;
2027 ERR("relay_index_get_by_id_or_create index NULL");
2028 goto end_stream_put;
2029 }
2030 if (set_index_control_data(index, &index_info, conn)) {
2031 ERR("set_index_control_data error");
2032 relay_index_put(index);
2033 ret = -1;
2034 goto end_stream_put;
2035 }
2036 ret = relay_index_try_flush(index);
2037 if (ret == 0) {
2038 tracefile_array_commit_seq(stream->tfa);
2039 stream->index_received_seqcount++;
2040 } else if (ret > 0) {
2041 /* no flush. */
2042 ret = 0;
2043 } else {
2044 ERR("relay_index_try_flush error %d", ret);
2045 relay_index_put(index);
2046 ret = -1;
2047 }
2048
2049 end_stream_put:
2050 pthread_mutex_unlock(&stream->lock);
2051 stream_put(stream);
2052
2053 end:
2054
2055 memset(&reply, 0, sizeof(reply));
2056 if (ret < 0) {
2057 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2058 } else {
2059 reply.ret_code = htobe32(LTTNG_OK);
2060 }
2061 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2062 if (send_ret < 0) {
2063 ERR("Relay sending close index id reply");
2064 ret = send_ret;
2065 }
2066
2067 end_no_session:
2068 return ret;
2069 }
2070
2071 /*
2072 * Receive the streams_sent message.
2073 *
2074 * Return 0 on success else a negative value.
2075 */
2076 static int relay_streams_sent(struct lttcomm_relayd_hdr *recv_hdr,
2077 struct relay_connection *conn)
2078 {
2079 int ret, send_ret;
2080 struct lttcomm_relayd_generic_reply reply;
2081
2082 assert(conn);
2083
2084 DBG("Relay receiving streams_sent");
2085
2086 if (!conn->session || conn->version_check_done == 0) {
2087 ERR("Trying to close a stream before version check");
2088 ret = -1;
2089 goto end_no_session;
2090 }
2091
2092 /*
2093 * Publish every pending stream in the connection recv list which are
2094 * now ready to be used by the viewer.
2095 */
2096 publish_connection_local_streams(conn);
2097
2098 memset(&reply, 0, sizeof(reply));
2099 reply.ret_code = htobe32(LTTNG_OK);
2100 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2101 if (send_ret < 0) {
2102 ERR("Relay sending sent_stream reply");
2103 ret = send_ret;
2104 } else {
2105 /* Success. */
2106 ret = 0;
2107 }
2108
2109 end_no_session:
2110 return ret;
2111 }
2112
2113 /*
2114 * Process the commands received on the control socket
2115 */
2116 static int relay_process_control(struct lttcomm_relayd_hdr *recv_hdr,
2117 struct relay_connection *conn)
2118 {
2119 int ret = 0;
2120
2121 switch (be32toh(recv_hdr->cmd)) {
2122 case RELAYD_CREATE_SESSION:
2123 ret = relay_create_session(recv_hdr, conn);
2124 break;
2125 case RELAYD_ADD_STREAM:
2126 ret = relay_add_stream(recv_hdr, conn);
2127 break;
2128 case RELAYD_START_DATA:
2129 ret = relay_start(recv_hdr, conn);
2130 break;
2131 case RELAYD_SEND_METADATA:
2132 ret = relay_recv_metadata(recv_hdr, conn);
2133 break;
2134 case RELAYD_VERSION:
2135 ret = relay_send_version(recv_hdr, conn);
2136 break;
2137 case RELAYD_CLOSE_STREAM:
2138 ret = relay_close_stream(recv_hdr, conn);
2139 break;
2140 case RELAYD_DATA_PENDING:
2141 ret = relay_data_pending(recv_hdr, conn);
2142 break;
2143 case RELAYD_QUIESCENT_CONTROL:
2144 ret = relay_quiescent_control(recv_hdr, conn);
2145 break;
2146 case RELAYD_BEGIN_DATA_PENDING:
2147 ret = relay_begin_data_pending(recv_hdr, conn);
2148 break;
2149 case RELAYD_END_DATA_PENDING:
2150 ret = relay_end_data_pending(recv_hdr, conn);
2151 break;
2152 case RELAYD_SEND_INDEX:
2153 ret = relay_recv_index(recv_hdr, conn);
2154 break;
2155 case RELAYD_STREAMS_SENT:
2156 ret = relay_streams_sent(recv_hdr, conn);
2157 break;
2158 case RELAYD_RESET_METADATA:
2159 ret = relay_reset_metadata(recv_hdr, conn);
2160 break;
2161 case RELAYD_UPDATE_SYNC_INFO:
2162 default:
2163 ERR("Received unknown command (%u)", be32toh(recv_hdr->cmd));
2164 relay_unknown_command(conn);
2165 ret = -1;
2166 goto end;
2167 }
2168
2169 end:
2170 return ret;
2171 }
2172
2173 /*
2174 * Handle index for a data stream.
2175 *
2176 * Called with the stream lock held.
2177 *
2178 * Return 0 on success else a negative value.
2179 */
2180 static int handle_index_data(struct relay_stream *stream, uint64_t net_seq_num,
2181 int rotate_index)
2182 {
2183 int ret = 0;
2184 uint64_t data_offset;
2185 struct relay_index *index;
2186
2187 /* Get data offset because we are about to update the index. */
2188 data_offset = htobe64(stream->tracefile_size_current);
2189
2190 DBG("handle_index_data: stream %" PRIu64 " net_seq_num %" PRIu64 " data offset %" PRIu64,
2191 stream->stream_handle, net_seq_num, stream->tracefile_size_current);
2192
2193 /*
2194 * Lookup for an existing index for that stream id/sequence
2195 * number. If it exists, the control thread has already received the
2196 * data for it, thus we need to write it to disk.
2197 */
2198 index = relay_index_get_by_id_or_create(stream, net_seq_num);
2199 if (!index) {
2200 ret = -1;
2201 goto end;
2202 }
2203
2204 if (rotate_index || !stream->index_file) {
2205 uint32_t major, minor;
2206
2207 /* Put ref on previous index_file. */
2208 if (stream->index_file) {
2209 lttng_index_file_put(stream->index_file);
2210 stream->index_file = NULL;
2211 }
2212 major = stream->trace->session->major;
2213 minor = stream->trace->session->minor;
2214 stream->index_file = lttng_index_file_create(stream->path_name,
2215 stream->channel_name,
2216 -1, -1, stream->tracefile_size,
2217 tracefile_array_get_file_index_head(stream->tfa),
2218 lttng_to_index_major(major, minor),
2219 lttng_to_index_minor(major, minor));
2220 if (!stream->index_file) {
2221 ret = -1;
2222 /* Put self-ref for this index due to error. */
2223 relay_index_put(index);
2224 index = NULL;
2225 goto end;
2226 }
2227 }
2228
2229 if (relay_index_set_file(index, stream->index_file, data_offset)) {
2230 ret = -1;
2231 /* Put self-ref for this index due to error. */
2232 relay_index_put(index);
2233 index = NULL;
2234 goto end;
2235 }
2236
2237 ret = relay_index_try_flush(index);
2238 if (ret == 0) {
2239 tracefile_array_commit_seq(stream->tfa);
2240 stream->index_received_seqcount++;
2241 } else if (ret > 0) {
2242 /* No flush. */
2243 ret = 0;
2244 } else {
2245 /* Put self-ref for this index due to error. */
2246 relay_index_put(index);
2247 index = NULL;
2248 ret = -1;
2249 }
2250 end:
2251 return ret;
2252 }
2253
2254 /*
2255 * relay_process_data: Process the data received on the data socket
2256 */
2257 static int relay_process_data(struct relay_connection *conn)
2258 {
2259 int ret = 0, rotate_index = 0;
2260 ssize_t size_ret;
2261 struct relay_stream *stream;
2262 struct lttcomm_relayd_data_hdr data_hdr;
2263 uint64_t stream_id;
2264 uint64_t net_seq_num;
2265 uint32_t data_size;
2266 struct relay_session *session;
2267 bool new_stream = false, close_requested = false;
2268 size_t chunk_size = RECV_DATA_BUFFER_SIZE;
2269 size_t recv_off = 0;
2270 char data_buffer[chunk_size];
2271
2272 ret = conn->sock->ops->recvmsg(conn->sock, &data_hdr,
2273 sizeof(struct lttcomm_relayd_data_hdr), 0);
2274 if (ret <= 0) {
2275 if (ret == 0) {
2276 /* Orderly shutdown. Not necessary to print an error. */
2277 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
2278 } else {
2279 ERR("Unable to receive data header on sock %d", conn->sock->fd);
2280 }
2281 ret = -1;
2282 goto end;
2283 }
2284
2285 stream_id = be64toh(data_hdr.stream_id);
2286 stream = stream_get_by_id(stream_id);
2287 if (!stream) {
2288 ERR("relay_process_data: Cannot find stream %" PRIu64, stream_id);
2289 ret = -1;
2290 goto end;
2291 }
2292 session = stream->trace->session;
2293 data_size = be32toh(data_hdr.data_size);
2294
2295 net_seq_num = be64toh(data_hdr.net_seq_num);
2296
2297 DBG3("Receiving data of size %u for stream id %" PRIu64 " seqnum %" PRIu64,
2298 data_size, stream_id, net_seq_num);
2299
2300 pthread_mutex_lock(&stream->lock);
2301
2302 /* Check if a rotation is needed. */
2303 if (stream->tracefile_size > 0 &&
2304 (stream->tracefile_size_current + data_size) >
2305 stream->tracefile_size) {
2306 uint64_t old_id, new_id;
2307
2308 old_id = tracefile_array_get_file_index_head(stream->tfa);
2309 tracefile_array_file_rotate(stream->tfa);
2310
2311 /* new_id is updated by utils_rotate_stream_file. */
2312 new_id = old_id;
2313
2314 ret = utils_rotate_stream_file(stream->path_name,
2315 stream->channel_name, stream->tracefile_size,
2316 stream->tracefile_count, -1,
2317 -1, stream->stream_fd->fd,
2318 &new_id, &stream->stream_fd->fd);
2319 if (ret < 0) {
2320 ERR("Rotating stream output file");
2321 goto end_stream_unlock;
2322 }
2323 /*
2324 * Reset current size because we just performed a stream
2325 * rotation.
2326 */
2327 stream->tracefile_size_current = 0;
2328 rotate_index = 1;
2329 }
2330
2331 /*
2332 * Index are handled in protocol version 2.4 and above. Also,
2333 * snapshot and index are NOT supported.
2334 */
2335 if (session->minor >= 4 && !session->snapshot) {
2336 ret = handle_index_data(stream, net_seq_num, rotate_index);
2337 if (ret < 0) {
2338 ERR("handle_index_data: fail stream %" PRIu64 " net_seq_num %" PRIu64 " ret %d",
2339 stream->stream_handle, net_seq_num, ret);
2340 goto end_stream_unlock;
2341 }
2342 }
2343
2344 for (recv_off = 0; recv_off < data_size; recv_off += chunk_size) {
2345 size_t recv_size = min(data_size - recv_off, chunk_size);
2346
2347 ret = conn->sock->ops->recvmsg(conn->sock, data_buffer, recv_size, 0);
2348 if (ret <= 0) {
2349 if (ret == 0) {
2350 /* Orderly shutdown. Not necessary to print an error. */
2351 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
2352 } else {
2353 ERR("Socket %d error %d", conn->sock->fd, ret);
2354 }
2355 ret = -1;
2356 goto end_stream_unlock;
2357 }
2358
2359 /* Write data to stream output fd. */
2360 size_ret = lttng_write(stream->stream_fd->fd, data_buffer,
2361 recv_size);
2362 if (size_ret < recv_size) {
2363 ERR("Relay error writing data to file");
2364 ret = -1;
2365 goto end_stream_unlock;
2366 }
2367
2368 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64,
2369 size_ret, stream->stream_handle);
2370 }
2371
2372 ret = write_padding_to_file(stream->stream_fd->fd,
2373 be32toh(data_hdr.padding_size));
2374 if (ret < 0) {
2375 ERR("write_padding_to_file: fail stream %" PRIu64 " net_seq_num %" PRIu64 " ret %d",
2376 stream->stream_handle, net_seq_num, ret);
2377 goto end_stream_unlock;
2378 }
2379 stream->tracefile_size_current +=
2380 data_size + be32toh(data_hdr.padding_size);
2381 if (stream->prev_seq == -1ULL) {
2382 new_stream = true;
2383 }
2384
2385 stream->prev_seq = net_seq_num;
2386
2387 end_stream_unlock:
2388 close_requested = stream->close_requested;
2389 pthread_mutex_unlock(&stream->lock);
2390 if (close_requested) {
2391 try_stream_close(stream);
2392 }
2393
2394 if (new_stream) {
2395 pthread_mutex_lock(&session->lock);
2396 uatomic_set(&session->new_streams, 1);
2397 pthread_mutex_unlock(&session->lock);
2398 }
2399 stream_put(stream);
2400 end:
2401 return ret;
2402 }
2403
2404 static void cleanup_connection_pollfd(struct lttng_poll_event *events, int pollfd)
2405 {
2406 int ret;
2407
2408 (void) lttng_poll_del(events, pollfd);
2409
2410 ret = close(pollfd);
2411 if (ret < 0) {
2412 ERR("Closing pollfd %d", pollfd);
2413 }
2414 }
2415
2416 static void relay_thread_close_connection(struct lttng_poll_event *events,
2417 int pollfd, struct relay_connection *conn)
2418 {
2419 const char *type_str;
2420
2421 switch (conn->type) {
2422 case RELAY_DATA:
2423 type_str = "Data";
2424 break;
2425 case RELAY_CONTROL:
2426 type_str = "Control";
2427 break;
2428 case RELAY_VIEWER_COMMAND:
2429 type_str = "Viewer Command";
2430 break;
2431 case RELAY_VIEWER_NOTIFICATION:
2432 type_str = "Viewer Notification";
2433 break;
2434 default:
2435 type_str = "Unknown";
2436 }
2437 cleanup_connection_pollfd(events, pollfd);
2438 connection_put(conn);
2439 DBG("%s connection closed with %d", type_str, pollfd);
2440 }
2441
2442 /*
2443 * This thread does the actual work
2444 */
2445 static void *relay_thread_worker(void *data)
2446 {
2447 int ret, err = -1, last_seen_data_fd = -1;
2448 uint32_t nb_fd;
2449 struct lttng_poll_event events;
2450 struct lttng_ht *relay_connections_ht;
2451 struct lttng_ht_iter iter;
2452 struct lttcomm_relayd_hdr recv_hdr;
2453 struct relay_connection *destroy_conn = NULL;
2454
2455 DBG("[thread] Relay worker started");
2456
2457 rcu_register_thread();
2458
2459 health_register(health_relayd, HEALTH_RELAYD_TYPE_WORKER);
2460
2461 if (testpoint(relayd_thread_worker)) {
2462 goto error_testpoint;
2463 }
2464
2465 health_code_update();
2466
2467 /* table of connections indexed on socket */
2468 relay_connections_ht = lttng_ht_new(0, LTTNG_HT_TYPE_ULONG);
2469 if (!relay_connections_ht) {
2470 goto relay_connections_ht_error;
2471 }
2472
2473 ret = create_thread_poll_set(&events, 2);
2474 if (ret < 0) {
2475 goto error_poll_create;
2476 }
2477
2478 ret = lttng_poll_add(&events, relay_conn_pipe[0], LPOLLIN | LPOLLRDHUP);
2479 if (ret < 0) {
2480 goto error;
2481 }
2482
2483 restart:
2484 while (1) {
2485 int idx = -1, i, seen_control = 0, last_notdel_data_fd = -1;
2486
2487 health_code_update();
2488
2489 /* Infinite blocking call, waiting for transmission */
2490 DBG3("Relayd worker thread polling...");
2491 health_poll_entry();
2492 ret = lttng_poll_wait(&events, -1);
2493 health_poll_exit();
2494 if (ret < 0) {
2495 /*
2496 * Restart interrupted system call.
2497 */
2498 if (errno == EINTR) {
2499 goto restart;
2500 }
2501 goto error;
2502 }
2503
2504 nb_fd = ret;
2505
2506 /*
2507 * Process control. The control connection is
2508 * prioritized so we don't starve it with high
2509 * throughput tracing data on the data connection.
2510 */
2511 for (i = 0; i < nb_fd; i++) {
2512 /* Fetch once the poll data */
2513 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
2514 int pollfd = LTTNG_POLL_GETFD(&events, i);
2515
2516 health_code_update();
2517
2518 if (!revents) {
2519 /*
2520 * No activity for this FD (poll
2521 * implementation).
2522 */
2523 continue;
2524 }
2525
2526 /* Thread quit pipe has been closed. Killing thread. */
2527 ret = check_thread_quit_pipe(pollfd, revents);
2528 if (ret) {
2529 err = 0;
2530 goto exit;
2531 }
2532
2533 /* Inspect the relay conn pipe for new connection */
2534 if (pollfd == relay_conn_pipe[0]) {
2535 if (revents & LPOLLIN) {
2536 struct relay_connection *conn;
2537
2538 ret = lttng_read(relay_conn_pipe[0], &conn, sizeof(conn));
2539 if (ret < 0) {
2540 goto error;
2541 }
2542 lttng_poll_add(&events, conn->sock->fd,
2543 LPOLLIN | LPOLLRDHUP);
2544 connection_ht_add(relay_connections_ht, conn);
2545 DBG("Connection socket %d added", conn->sock->fd);
2546 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2547 ERR("Relay connection pipe error");
2548 goto error;
2549 } else {
2550 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
2551 goto error;
2552 }
2553 } else {
2554 struct relay_connection *ctrl_conn;
2555
2556 ctrl_conn = connection_get_by_sock(relay_connections_ht, pollfd);
2557 /* If not found, there is a synchronization issue. */
2558 assert(ctrl_conn);
2559
2560 if (ctrl_conn->type == RELAY_DATA) {
2561 if (revents & LPOLLIN) {
2562 /*
2563 * Flag the last seen data fd not deleted. It will be
2564 * used as the last seen fd if any fd gets deleted in
2565 * this first loop.
2566 */
2567 last_notdel_data_fd = pollfd;
2568 }
2569 goto put_ctrl_connection;
2570 }
2571 assert(ctrl_conn->type == RELAY_CONTROL);
2572
2573 if (revents & LPOLLIN) {
2574 ret = ctrl_conn->sock->ops->recvmsg(ctrl_conn->sock,
2575 &recv_hdr, sizeof(recv_hdr), 0);
2576 if (ret <= 0) {
2577 /* Connection closed */
2578 relay_thread_close_connection(&events, pollfd,
2579 ctrl_conn);
2580 } else {
2581 ret = relay_process_control(&recv_hdr, ctrl_conn);
2582 if (ret < 0) {
2583 /* Clear the session on error. */
2584 relay_thread_close_connection(&events,
2585 pollfd, ctrl_conn);
2586 }
2587 seen_control = 1;
2588 }
2589 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2590 relay_thread_close_connection(&events,
2591 pollfd, ctrl_conn);
2592 if (last_seen_data_fd == pollfd) {
2593 last_seen_data_fd = last_notdel_data_fd;
2594 }
2595 } else {
2596 ERR("Unexpected poll events %u for control sock %d",
2597 revents, pollfd);
2598 connection_put(ctrl_conn);
2599 goto error;
2600 }
2601 put_ctrl_connection:
2602 connection_put(ctrl_conn);
2603 }
2604 }
2605
2606 /*
2607 * The last loop handled a control request, go back to poll to make
2608 * sure we prioritise the control socket.
2609 */
2610 if (seen_control) {
2611 continue;
2612 }
2613
2614 if (last_seen_data_fd >= 0) {
2615 for (i = 0; i < nb_fd; i++) {
2616 int pollfd = LTTNG_POLL_GETFD(&events, i);
2617
2618 health_code_update();
2619
2620 if (last_seen_data_fd == pollfd) {
2621 idx = i;
2622 break;
2623 }
2624 }
2625 }
2626
2627 /* Process data connection. */
2628 for (i = idx + 1; i < nb_fd; i++) {
2629 /* Fetch the poll data. */
2630 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
2631 int pollfd = LTTNG_POLL_GETFD(&events, i);
2632 struct relay_connection *data_conn;
2633
2634 health_code_update();
2635
2636 if (!revents) {
2637 /* No activity for this FD (poll implementation). */
2638 continue;
2639 }
2640
2641 /* Skip the command pipe. It's handled in the first loop. */
2642 if (pollfd == relay_conn_pipe[0]) {
2643 continue;
2644 }
2645
2646 data_conn = connection_get_by_sock(relay_connections_ht, pollfd);
2647 if (!data_conn) {
2648 /* Skip it. Might be removed before. */
2649 continue;
2650 }
2651 if (data_conn->type == RELAY_CONTROL) {
2652 goto put_data_connection;
2653 }
2654 assert(data_conn->type == RELAY_DATA);
2655
2656 if (revents & LPOLLIN) {
2657 ret = relay_process_data(data_conn);
2658 /* Connection closed */
2659 if (ret < 0) {
2660 relay_thread_close_connection(&events, pollfd,
2661 data_conn);
2662 /*
2663 * Every goto restart call sets the last seen fd where
2664 * here we don't really care since we gracefully
2665 * continue the loop after the connection is deleted.
2666 */
2667 } else {
2668 /* Keep last seen port. */
2669 last_seen_data_fd = pollfd;
2670 connection_put(data_conn);
2671 goto restart;
2672 }
2673 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2674 relay_thread_close_connection(&events, pollfd,
2675 data_conn);
2676 } else {
2677 ERR("Unknown poll events %u for data sock %d",
2678 revents, pollfd);
2679 }
2680 put_data_connection:
2681 connection_put(data_conn);
2682 }
2683 last_seen_data_fd = -1;
2684 }
2685
2686 /* Normal exit, no error */
2687 ret = 0;
2688
2689 exit:
2690 error:
2691 /* Cleanup reamaining connection object. */
2692 rcu_read_lock();
2693 cds_lfht_for_each_entry(relay_connections_ht->ht, &iter.iter,
2694 destroy_conn,
2695 sock_n.node) {
2696 health_code_update();
2697
2698 if (session_abort(destroy_conn->session)) {
2699 assert(0);
2700 }
2701
2702 /*
2703 * No need to grab another ref, because we own
2704 * destroy_conn.
2705 */
2706 relay_thread_close_connection(&events, destroy_conn->sock->fd,
2707 destroy_conn);
2708 }
2709 rcu_read_unlock();
2710
2711 lttng_poll_clean(&events);
2712 error_poll_create:
2713 lttng_ht_destroy(relay_connections_ht);
2714 relay_connections_ht_error:
2715 /* Close relay conn pipes */
2716 utils_close_pipe(relay_conn_pipe);
2717 if (err) {
2718 DBG("Thread exited with error");
2719 }
2720 DBG("Worker thread cleanup complete");
2721 error_testpoint:
2722 if (err) {
2723 health_error();
2724 ERR("Health error occurred in %s", __func__);
2725 }
2726 health_unregister(health_relayd);
2727 rcu_unregister_thread();
2728 lttng_relay_stop_threads();
2729 return NULL;
2730 }
2731
2732 /*
2733 * Create the relay command pipe to wake thread_manage_apps.
2734 * Closed in cleanup().
2735 */
2736 static int create_relay_conn_pipe(void)
2737 {
2738 int ret;
2739
2740 ret = utils_create_pipe_cloexec(relay_conn_pipe);
2741
2742 return ret;
2743 }
2744
2745 /*
2746 * main
2747 */
2748 int main(int argc, char **argv)
2749 {
2750 int ret = 0, retval = 0;
2751 void *status;
2752
2753 /* Parse arguments */
2754 progname = argv[0];
2755 if (set_options(argc, argv)) {
2756 retval = -1;
2757 goto exit_options;
2758 }
2759
2760 if (set_signal_handler()) {
2761 retval = -1;
2762 goto exit_options;
2763 }
2764
2765 /* Try to create directory if -o, --output is specified. */
2766 if (opt_output_path) {
2767 if (*opt_output_path != '/') {
2768 ERR("Please specify an absolute path for -o, --output PATH");
2769 retval = -1;
2770 goto exit_options;
2771 }
2772
2773 ret = utils_mkdir_recursive(opt_output_path, S_IRWXU | S_IRWXG,
2774 -1, -1);
2775 if (ret < 0) {
2776 ERR("Unable to create %s", opt_output_path);
2777 retval = -1;
2778 goto exit_options;
2779 }
2780 }
2781
2782 /* Daemonize */
2783 if (opt_daemon || opt_background) {
2784 int i;
2785
2786 ret = lttng_daemonize(&child_ppid, &recv_child_signal,
2787 !opt_background);
2788 if (ret < 0) {
2789 retval = -1;
2790 goto exit_options;
2791 }
2792
2793 /*
2794 * We are in the child. Make sure all other file
2795 * descriptors are closed, in case we are called with
2796 * more opened file descriptors than the standard ones.
2797 */
2798 for (i = 3; i < sysconf(_SC_OPEN_MAX); i++) {
2799 (void) close(i);
2800 }
2801 }
2802
2803 /* Initialize thread health monitoring */
2804 health_relayd = health_app_create(NR_HEALTH_RELAYD_TYPES);
2805 if (!health_relayd) {
2806 PERROR("health_app_create error");
2807 retval = -1;
2808 goto exit_health_app_create;
2809 }
2810
2811 /* Create thread quit pipe */
2812 if (init_thread_quit_pipe()) {
2813 retval = -1;
2814 goto exit_init_data;
2815 }
2816
2817 /* Setup the thread apps communication pipe. */
2818 if (create_relay_conn_pipe()) {
2819 retval = -1;
2820 goto exit_init_data;
2821 }
2822
2823 /* Init relay command queue. */
2824 cds_wfcq_init(&relay_conn_queue.head, &relay_conn_queue.tail);
2825
2826 /* Initialize communication library */
2827 lttcomm_init();
2828 lttcomm_inet_init();
2829
2830 /* tables of sessions indexed by session ID */
2831 sessions_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
2832 if (!sessions_ht) {
2833 retval = -1;
2834 goto exit_init_data;
2835 }
2836
2837 /* tables of streams indexed by stream ID */
2838 relay_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
2839 if (!relay_streams_ht) {
2840 retval = -1;
2841 goto exit_init_data;
2842 }
2843
2844 /* tables of streams indexed by stream ID */
2845 viewer_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
2846 if (!viewer_streams_ht) {
2847 retval = -1;
2848 goto exit_init_data;
2849 }
2850
2851 ret = utils_create_pipe(health_quit_pipe);
2852 if (ret) {
2853 retval = -1;
2854 goto exit_health_quit_pipe;
2855 }
2856
2857 /* Create thread to manage the client socket */
2858 ret = pthread_create(&health_thread, default_pthread_attr(),
2859 thread_manage_health, (void *) NULL);
2860 if (ret) {
2861 errno = ret;
2862 PERROR("pthread_create health");
2863 retval = -1;
2864 goto exit_health_thread;
2865 }
2866
2867 /* Setup the dispatcher thread */
2868 ret = pthread_create(&dispatcher_thread, default_pthread_attr(),
2869 relay_thread_dispatcher, (void *) NULL);
2870 if (ret) {
2871 errno = ret;
2872 PERROR("pthread_create dispatcher");
2873 retval = -1;
2874 goto exit_dispatcher_thread;
2875 }
2876
2877 /* Setup the worker thread */
2878 ret = pthread_create(&worker_thread, default_pthread_attr(),
2879 relay_thread_worker, NULL);
2880 if (ret) {
2881 errno = ret;
2882 PERROR("pthread_create worker");
2883 retval = -1;
2884 goto exit_worker_thread;
2885 }
2886
2887 /* Setup the listener thread */
2888 ret = pthread_create(&listener_thread, default_pthread_attr(),
2889 relay_thread_listener, (void *) NULL);
2890 if (ret) {
2891 errno = ret;
2892 PERROR("pthread_create listener");
2893 retval = -1;
2894 goto exit_listener_thread;
2895 }
2896
2897 ret = relayd_live_create(live_uri);
2898 if (ret) {
2899 ERR("Starting live viewer threads");
2900 retval = -1;
2901 goto exit_live;
2902 }
2903
2904 /*
2905 * This is where we start awaiting program completion (e.g. through
2906 * signal that asks threads to teardown).
2907 */
2908
2909 ret = relayd_live_join();
2910 if (ret) {
2911 retval = -1;
2912 }
2913 exit_live:
2914
2915 ret = pthread_join(listener_thread, &status);
2916 if (ret) {
2917 errno = ret;
2918 PERROR("pthread_join listener_thread");
2919 retval = -1;
2920 }
2921
2922 exit_listener_thread:
2923 ret = pthread_join(worker_thread, &status);
2924 if (ret) {
2925 errno = ret;
2926 PERROR("pthread_join worker_thread");
2927 retval = -1;
2928 }
2929
2930 exit_worker_thread:
2931 ret = pthread_join(dispatcher_thread, &status);
2932 if (ret) {
2933 errno = ret;
2934 PERROR("pthread_join dispatcher_thread");
2935 retval = -1;
2936 }
2937 exit_dispatcher_thread:
2938
2939 ret = pthread_join(health_thread, &status);
2940 if (ret) {
2941 errno = ret;
2942 PERROR("pthread_join health_thread");
2943 retval = -1;
2944 }
2945 exit_health_thread:
2946
2947 utils_close_pipe(health_quit_pipe);
2948 exit_health_quit_pipe:
2949
2950 exit_init_data:
2951 health_app_destroy(health_relayd);
2952 exit_health_app_create:
2953 exit_options:
2954 /*
2955 * Wait for all pending call_rcu work to complete before tearing
2956 * down data structures. call_rcu worker may be trying to
2957 * perform lookups in those structures.
2958 */
2959 rcu_barrier();
2960 relayd_cleanup();
2961
2962 /* Ensure all prior call_rcu are done. */
2963 rcu_barrier();
2964
2965 if (!retval) {
2966 exit(EXIT_SUCCESS);
2967 } else {
2968 exit(EXIT_FAILURE);
2969 }
2970 }
This page took 0.138385 seconds and 4 git commands to generate.