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