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