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