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