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