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