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