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