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