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