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