Fix: thread exit vs futex wait/wakeup race
[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 for (;;) {
973 health_code_update();
974
975 /* Atomically prepare the queue futex */
976 futex_nto1_prepare(&relay_conn_queue.futex);
977
978 if (CMM_LOAD_SHARED(dispatch_thread_exit)) {
979 break;
980 }
981
982 do {
983 health_code_update();
984
985 /* Dequeue commands */
986 node = cds_wfcq_dequeue_blocking(&relay_conn_queue.head,
987 &relay_conn_queue.tail);
988 if (node == NULL) {
989 DBG("Woken up but nothing in the relay command queue");
990 /* Continue thread execution */
991 break;
992 }
993 new_conn = caa_container_of(node, struct relay_connection, qnode);
994
995 DBG("Dispatching request waiting on sock %d", new_conn->sock->fd);
996
997 /*
998 * Inform worker thread of the new request. This
999 * call is blocking so we can be assured that
1000 * the data will be read at some point in time
1001 * or wait to the end of the world :)
1002 */
1003 ret = lttng_write(relay_conn_pipe[1], &new_conn, sizeof(new_conn));
1004 if (ret < 0) {
1005 PERROR("write connection pipe");
1006 connection_put(new_conn);
1007 goto error;
1008 }
1009 } while (node != NULL);
1010
1011 /* Futex wait on queue. Blocking call on futex() */
1012 health_poll_entry();
1013 futex_nto1_wait(&relay_conn_queue.futex);
1014 health_poll_exit();
1015 }
1016
1017 /* Normal exit, no error */
1018 err = 0;
1019
1020 error:
1021 error_testpoint:
1022 if (err) {
1023 health_error();
1024 ERR("Health error occurred in %s", __func__);
1025 }
1026 health_unregister(health_relayd);
1027 DBG("Dispatch thread dying");
1028 lttng_relay_stop_threads();
1029 return NULL;
1030 }
1031
1032 /*
1033 * Set index data from the control port to a given index object.
1034 */
1035 static int set_index_control_data(struct relay_index *index,
1036 struct lttcomm_relayd_index *data,
1037 struct relay_connection *conn)
1038 {
1039 struct ctf_packet_index index_data;
1040
1041 /*
1042 * The index on disk is encoded in big endian, so we don't need
1043 * to convert the data received on the network. The data_offset
1044 * value is NEVER modified here and is updated by the data
1045 * thread.
1046 */
1047 index_data.packet_size = data->packet_size;
1048 index_data.content_size = data->content_size;
1049 index_data.timestamp_begin = data->timestamp_begin;
1050 index_data.timestamp_end = data->timestamp_end;
1051 index_data.events_discarded = data->events_discarded;
1052 index_data.stream_id = data->stream_id;
1053
1054 if (conn->minor >= 8) {
1055 index->index_data.stream_instance_id = data->stream_instance_id;
1056 index->index_data.packet_seq_num = data->packet_seq_num;
1057 }
1058
1059 return relay_index_set_data(index, &index_data);
1060 }
1061
1062 /*
1063 * Handle the RELAYD_CREATE_SESSION command.
1064 *
1065 * On success, send back the session id or else return a negative value.
1066 */
1067 static int relay_create_session(struct lttcomm_relayd_hdr *recv_hdr,
1068 struct relay_connection *conn)
1069 {
1070 int ret = 0, send_ret;
1071 struct relay_session *session;
1072 struct lttcomm_relayd_status_session reply;
1073 char session_name[LTTNG_NAME_MAX];
1074 char hostname[LTTNG_HOST_NAME_MAX];
1075 uint32_t live_timer = 0;
1076 bool snapshot = false;
1077
1078 memset(session_name, 0, LTTNG_NAME_MAX);
1079 memset(hostname, 0, LTTNG_HOST_NAME_MAX);
1080
1081 memset(&reply, 0, sizeof(reply));
1082
1083 switch (conn->minor) {
1084 case 1:
1085 case 2:
1086 case 3:
1087 break;
1088 case 4: /* LTTng sessiond 2.4 */
1089 default:
1090 ret = cmd_create_session_2_4(conn, session_name,
1091 hostname, &live_timer, &snapshot);
1092 }
1093 if (ret < 0) {
1094 goto send_reply;
1095 }
1096
1097 session = session_create(session_name, hostname, live_timer,
1098 snapshot, conn->major, conn->minor);
1099 if (!session) {
1100 ret = -1;
1101 goto send_reply;
1102 }
1103 assert(!conn->session);
1104 conn->session = session;
1105 DBG("Created session %" PRIu64, session->id);
1106
1107 reply.session_id = htobe64(session->id);
1108
1109 send_reply:
1110 if (ret < 0) {
1111 reply.ret_code = htobe32(LTTNG_ERR_FATAL);
1112 } else {
1113 reply.ret_code = htobe32(LTTNG_OK);
1114 }
1115
1116 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1117 if (send_ret < 0) {
1118 ERR("Relayd sending session id");
1119 ret = send_ret;
1120 }
1121
1122 return ret;
1123 }
1124
1125 /*
1126 * When we have received all the streams and the metadata for a channel,
1127 * we make them visible to the viewer threads.
1128 */
1129 static void publish_connection_local_streams(struct relay_connection *conn)
1130 {
1131 struct relay_stream *stream;
1132 struct relay_session *session = conn->session;
1133
1134 /*
1135 * We publish all streams belonging to a session atomically wrt
1136 * session lock.
1137 */
1138 pthread_mutex_lock(&session->lock);
1139 rcu_read_lock();
1140 cds_list_for_each_entry_rcu(stream, &session->recv_list,
1141 recv_node) {
1142 stream_publish(stream);
1143 }
1144 rcu_read_unlock();
1145
1146 /*
1147 * Inform the viewer that there are new streams in the session.
1148 */
1149 if (session->viewer_attached) {
1150 uatomic_set(&session->new_streams, 1);
1151 }
1152 pthread_mutex_unlock(&session->lock);
1153 }
1154
1155 /*
1156 * relay_add_stream: allocate a new stream for a session
1157 */
1158 static int relay_add_stream(struct lttcomm_relayd_hdr *recv_hdr,
1159 struct relay_connection *conn)
1160 {
1161 int ret;
1162 ssize_t send_ret;
1163 struct relay_session *session = conn->session;
1164 struct relay_stream *stream = NULL;
1165 struct lttcomm_relayd_status_stream reply;
1166 struct ctf_trace *trace = NULL;
1167 uint64_t stream_handle = -1ULL;
1168 char *path_name = NULL, *channel_name = NULL;
1169 uint64_t tracefile_size = 0, tracefile_count = 0;
1170
1171 if (!session || conn->version_check_done == 0) {
1172 ERR("Trying to add a stream before version check");
1173 ret = -1;
1174 goto end_no_session;
1175 }
1176
1177 switch (session->minor) {
1178 case 1: /* LTTng sessiond 2.1. Allocates path_name and channel_name. */
1179 ret = cmd_recv_stream_2_1(conn, &path_name,
1180 &channel_name);
1181 break;
1182 case 2: /* LTTng sessiond 2.2. Allocates path_name and channel_name. */
1183 default:
1184 ret = cmd_recv_stream_2_2(conn, &path_name,
1185 &channel_name, &tracefile_size, &tracefile_count);
1186 break;
1187 }
1188 if (ret < 0) {
1189 goto send_reply;
1190 }
1191
1192 trace = ctf_trace_get_by_path_or_create(session, path_name);
1193 if (!trace) {
1194 goto send_reply;
1195 }
1196 /* This stream here has one reference on the trace. */
1197
1198 pthread_mutex_lock(&last_relay_stream_id_lock);
1199 stream_handle = ++last_relay_stream_id;
1200 pthread_mutex_unlock(&last_relay_stream_id_lock);
1201
1202 /* We pass ownership of path_name and channel_name. */
1203 stream = stream_create(trace, stream_handle, path_name,
1204 channel_name, tracefile_size, tracefile_count);
1205 path_name = NULL;
1206 channel_name = NULL;
1207
1208 /*
1209 * Streams are the owners of their trace. Reference to trace is
1210 * kept within stream_create().
1211 */
1212 ctf_trace_put(trace);
1213
1214 send_reply:
1215 memset(&reply, 0, sizeof(reply));
1216 reply.handle = htobe64(stream_handle);
1217 if (!stream) {
1218 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1219 } else {
1220 reply.ret_code = htobe32(LTTNG_OK);
1221 }
1222
1223 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1224 sizeof(struct lttcomm_relayd_status_stream), 0);
1225 if (send_ret < 0) {
1226 ERR("Relay sending stream id");
1227 ret = (int) send_ret;
1228 }
1229
1230 end_no_session:
1231 free(path_name);
1232 free(channel_name);
1233 return ret;
1234 }
1235
1236 /*
1237 * relay_close_stream: close a specific stream
1238 */
1239 static int relay_close_stream(struct lttcomm_relayd_hdr *recv_hdr,
1240 struct relay_connection *conn)
1241 {
1242 int ret, send_ret;
1243 struct relay_session *session = conn->session;
1244 struct lttcomm_relayd_close_stream stream_info;
1245 struct lttcomm_relayd_generic_reply reply;
1246 struct relay_stream *stream;
1247
1248 DBG("Close stream received");
1249
1250 if (!session || conn->version_check_done == 0) {
1251 ERR("Trying to close a stream before version check");
1252 ret = -1;
1253 goto end_no_session;
1254 }
1255
1256 ret = conn->sock->ops->recvmsg(conn->sock, &stream_info,
1257 sizeof(struct lttcomm_relayd_close_stream), 0);
1258 if (ret < sizeof(struct lttcomm_relayd_close_stream)) {
1259 if (ret == 0) {
1260 /* Orderly shutdown. Not necessary to print an error. */
1261 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1262 } else {
1263 ERR("Relay didn't receive valid add_stream struct size : %d", ret);
1264 }
1265 ret = -1;
1266 goto end_no_session;
1267 }
1268
1269 stream = stream_get_by_id(be64toh(stream_info.stream_id));
1270 if (!stream) {
1271 ret = -1;
1272 goto end;
1273 }
1274
1275 /*
1276 * Set last_net_seq_num before the close flag. Required by data
1277 * pending check.
1278 */
1279 pthread_mutex_lock(&stream->lock);
1280 stream->last_net_seq_num = be64toh(stream_info.last_net_seq_num);
1281 pthread_mutex_unlock(&stream->lock);
1282
1283 /*
1284 * This is one of the conditions which may trigger a stream close
1285 * with the others being:
1286 * 1) A close command is received for a stream
1287 * 2) The control connection owning the stream is closed
1288 * 3) We have received all of the stream's data _after_ a close
1289 * request.
1290 */
1291 try_stream_close(stream);
1292 if (stream->is_metadata) {
1293 struct relay_viewer_stream *vstream;
1294
1295 vstream = viewer_stream_get_by_id(stream->stream_handle);
1296 if (vstream) {
1297 if (vstream->metadata_sent == stream->metadata_received) {
1298 /*
1299 * Since all the metadata has been sent to the
1300 * viewer and that we have a request to close
1301 * its stream, we can safely teardown the
1302 * corresponding metadata viewer stream.
1303 */
1304 viewer_stream_put(vstream);
1305 }
1306 /* Put local reference. */
1307 viewer_stream_put(vstream);
1308 }
1309 }
1310 stream_put(stream);
1311
1312 end:
1313 memset(&reply, 0, sizeof(reply));
1314 if (ret < 0) {
1315 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1316 } else {
1317 reply.ret_code = htobe32(LTTNG_OK);
1318 }
1319 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1320 sizeof(struct lttcomm_relayd_generic_reply), 0);
1321 if (send_ret < 0) {
1322 ERR("Relay sending stream id");
1323 ret = send_ret;
1324 }
1325
1326 end_no_session:
1327 return ret;
1328 }
1329
1330 /*
1331 * relay_reset_metadata: reset a metadata stream
1332 */
1333 static
1334 int relay_reset_metadata(struct lttcomm_relayd_hdr *recv_hdr,
1335 struct relay_connection *conn)
1336 {
1337 int ret, send_ret;
1338 struct relay_session *session = conn->session;
1339 struct lttcomm_relayd_reset_metadata stream_info;
1340 struct lttcomm_relayd_generic_reply reply;
1341 struct relay_stream *stream;
1342
1343 DBG("Reset metadata received");
1344
1345 if (!session || conn->version_check_done == 0) {
1346 ERR("Trying to reset a metadata stream before version check");
1347 ret = -1;
1348 goto end_no_session;
1349 }
1350
1351 ret = conn->sock->ops->recvmsg(conn->sock, &stream_info,
1352 sizeof(struct lttcomm_relayd_reset_metadata), 0);
1353 if (ret < sizeof(struct lttcomm_relayd_reset_metadata)) {
1354 if (ret == 0) {
1355 /* Orderly shutdown. Not necessary to print an error. */
1356 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1357 } else {
1358 ERR("Relay didn't receive valid reset_metadata struct "
1359 "size : %d", ret);
1360 }
1361 ret = -1;
1362 goto end_no_session;
1363 }
1364 DBG("Update metadata to version %" PRIu64, be64toh(stream_info.version));
1365
1366 /* Unsupported for live sessions for now. */
1367 if (session->live_timer != 0) {
1368 ret = -1;
1369 goto end;
1370 }
1371
1372 stream = stream_get_by_id(be64toh(stream_info.stream_id));
1373 if (!stream) {
1374 ret = -1;
1375 goto end;
1376 }
1377 pthread_mutex_lock(&stream->lock);
1378 if (!stream->is_metadata) {
1379 ret = -1;
1380 goto end_unlock;
1381 }
1382
1383 ret = utils_rotate_stream_file(stream->path_name, stream->channel_name,
1384 0, 0, -1, -1, stream->stream_fd->fd, NULL,
1385 &stream->stream_fd->fd);
1386 if (ret < 0) {
1387 ERR("Failed to rotate metadata file %s of channel %s",
1388 stream->path_name, stream->channel_name);
1389 goto end_unlock;
1390 }
1391
1392 end_unlock:
1393 pthread_mutex_unlock(&stream->lock);
1394 stream_put(stream);
1395
1396 end:
1397 memset(&reply, 0, sizeof(reply));
1398 if (ret < 0) {
1399 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1400 } else {
1401 reply.ret_code = htobe32(LTTNG_OK);
1402 }
1403 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1404 sizeof(struct lttcomm_relayd_generic_reply), 0);
1405 if (send_ret < 0) {
1406 ERR("Relay sending reset metadata reply");
1407 ret = send_ret;
1408 }
1409
1410 end_no_session:
1411 return ret;
1412 }
1413
1414 /*
1415 * relay_unknown_command: send -1 if received unknown command
1416 */
1417 static void relay_unknown_command(struct relay_connection *conn)
1418 {
1419 struct lttcomm_relayd_generic_reply reply;
1420 int ret;
1421
1422 memset(&reply, 0, sizeof(reply));
1423 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1424 ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1425 sizeof(struct lttcomm_relayd_generic_reply), 0);
1426 if (ret < 0) {
1427 ERR("Relay sending unknown command");
1428 }
1429 }
1430
1431 /*
1432 * relay_start: send an acknowledgment to the client to tell if we are
1433 * ready to receive data. We are ready if a session is established.
1434 */
1435 static int relay_start(struct lttcomm_relayd_hdr *recv_hdr,
1436 struct relay_connection *conn)
1437 {
1438 int ret = htobe32(LTTNG_OK);
1439 struct lttcomm_relayd_generic_reply reply;
1440 struct relay_session *session = conn->session;
1441
1442 if (!session) {
1443 DBG("Trying to start the streaming without a session established");
1444 ret = htobe32(LTTNG_ERR_UNK);
1445 }
1446
1447 memset(&reply, 0, sizeof(reply));
1448 reply.ret_code = ret;
1449 ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1450 sizeof(struct lttcomm_relayd_generic_reply), 0);
1451 if (ret < 0) {
1452 ERR("Relay sending start ack");
1453 }
1454
1455 return ret;
1456 }
1457
1458 /*
1459 * Append padding to the file pointed by the file descriptor fd.
1460 */
1461 static int write_padding_to_file(int fd, uint32_t size)
1462 {
1463 ssize_t ret = 0;
1464 char *zeros;
1465
1466 if (size == 0) {
1467 goto end;
1468 }
1469
1470 zeros = zmalloc(size);
1471 if (zeros == NULL) {
1472 PERROR("zmalloc zeros for padding");
1473 ret = -1;
1474 goto end;
1475 }
1476
1477 ret = lttng_write(fd, zeros, size);
1478 if (ret < size) {
1479 PERROR("write padding to file");
1480 }
1481
1482 free(zeros);
1483
1484 end:
1485 return ret;
1486 }
1487
1488 /*
1489 * relay_recv_metadata: receive the metadata for the session.
1490 */
1491 static int relay_recv_metadata(struct lttcomm_relayd_hdr *recv_hdr,
1492 struct relay_connection *conn)
1493 {
1494 int ret = 0;
1495 ssize_t size_ret;
1496 struct relay_session *session = conn->session;
1497 struct lttcomm_relayd_metadata_payload *metadata_struct;
1498 struct relay_stream *metadata_stream;
1499 uint64_t data_size, payload_size;
1500
1501 if (!session) {
1502 ERR("Metadata sent before version check");
1503 ret = -1;
1504 goto end;
1505 }
1506
1507 data_size = payload_size = be64toh(recv_hdr->data_size);
1508 if (data_size < sizeof(struct lttcomm_relayd_metadata_payload)) {
1509 ERR("Incorrect data size");
1510 ret = -1;
1511 goto end;
1512 }
1513 payload_size -= sizeof(struct lttcomm_relayd_metadata_payload);
1514
1515 if (data_buffer_size < data_size) {
1516 /* In case the realloc fails, we can free the memory */
1517 char *tmp_data_ptr;
1518
1519 tmp_data_ptr = realloc(data_buffer, data_size);
1520 if (!tmp_data_ptr) {
1521 ERR("Allocating data buffer");
1522 free(data_buffer);
1523 ret = -1;
1524 goto end;
1525 }
1526 data_buffer = tmp_data_ptr;
1527 data_buffer_size = data_size;
1528 }
1529 memset(data_buffer, 0, data_size);
1530 DBG2("Relay receiving metadata, waiting for %" PRIu64 " bytes", data_size);
1531 size_ret = conn->sock->ops->recvmsg(conn->sock, data_buffer, data_size, 0);
1532 if (size_ret < 0 || size_ret != data_size) {
1533 if (size_ret == 0) {
1534 /* Orderly shutdown. Not necessary to print an error. */
1535 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1536 } else {
1537 ERR("Relay didn't receive the whole metadata");
1538 }
1539 ret = -1;
1540 goto end;
1541 }
1542 metadata_struct = (struct lttcomm_relayd_metadata_payload *) data_buffer;
1543
1544 metadata_stream = stream_get_by_id(be64toh(metadata_struct->stream_id));
1545 if (!metadata_stream) {
1546 ret = -1;
1547 goto end;
1548 }
1549
1550 pthread_mutex_lock(&metadata_stream->lock);
1551
1552 size_ret = lttng_write(metadata_stream->stream_fd->fd, metadata_struct->payload,
1553 payload_size);
1554 if (size_ret < payload_size) {
1555 ERR("Relay error writing metadata on file");
1556 ret = -1;
1557 goto end_put;
1558 }
1559
1560 size_ret = write_padding_to_file(metadata_stream->stream_fd->fd,
1561 be32toh(metadata_struct->padding_size));
1562 if (size_ret < 0) {
1563 goto end_put;
1564 }
1565
1566 metadata_stream->metadata_received +=
1567 payload_size + be32toh(metadata_struct->padding_size);
1568 DBG2("Relay metadata written. Updated metadata_received %" PRIu64,
1569 metadata_stream->metadata_received);
1570
1571 end_put:
1572 pthread_mutex_unlock(&metadata_stream->lock);
1573 stream_put(metadata_stream);
1574 end:
1575 return ret;
1576 }
1577
1578 /*
1579 * relay_send_version: send relayd version number
1580 */
1581 static int relay_send_version(struct lttcomm_relayd_hdr *recv_hdr,
1582 struct relay_connection *conn)
1583 {
1584 int ret;
1585 struct lttcomm_relayd_version reply, msg;
1586
1587 conn->version_check_done = 1;
1588
1589 /* Get version from the other side. */
1590 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
1591 if (ret < 0 || ret != sizeof(msg)) {
1592 if (ret == 0) {
1593 /* Orderly shutdown. Not necessary to print an error. */
1594 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1595 } else {
1596 ERR("Relay failed to receive the version values.");
1597 }
1598 ret = -1;
1599 goto end;
1600 }
1601
1602 memset(&reply, 0, sizeof(reply));
1603 reply.major = RELAYD_VERSION_COMM_MAJOR;
1604 reply.minor = RELAYD_VERSION_COMM_MINOR;
1605
1606 /* Major versions must be the same */
1607 if (reply.major != be32toh(msg.major)) {
1608 DBG("Incompatible major versions (%u vs %u), deleting session",
1609 reply.major, be32toh(msg.major));
1610 connection_put(conn);
1611 ret = 0;
1612 goto end;
1613 }
1614
1615 conn->major = reply.major;
1616 /* We adapt to the lowest compatible version */
1617 if (reply.minor <= be32toh(msg.minor)) {
1618 conn->minor = reply.minor;
1619 } else {
1620 conn->minor = be32toh(msg.minor);
1621 }
1622
1623 reply.major = htobe32(reply.major);
1624 reply.minor = htobe32(reply.minor);
1625 ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1626 sizeof(struct lttcomm_relayd_version), 0);
1627 if (ret < 0) {
1628 ERR("Relay sending version");
1629 }
1630
1631 DBG("Version check done using protocol %u.%u", conn->major,
1632 conn->minor);
1633
1634 end:
1635 return ret;
1636 }
1637
1638 /*
1639 * Check for data pending for a given stream id from the session daemon.
1640 */
1641 static int relay_data_pending(struct lttcomm_relayd_hdr *recv_hdr,
1642 struct relay_connection *conn)
1643 {
1644 struct relay_session *session = conn->session;
1645 struct lttcomm_relayd_data_pending msg;
1646 struct lttcomm_relayd_generic_reply reply;
1647 struct relay_stream *stream;
1648 int ret;
1649 uint64_t last_net_seq_num, stream_id;
1650
1651 DBG("Data pending command received");
1652
1653 if (!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 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 last_net_seq_num = be64toh(msg.last_net_seq_num);
1674
1675 stream = stream_get_by_id(stream_id);
1676 if (stream == NULL) {
1677 ret = -1;
1678 goto end;
1679 }
1680
1681 pthread_mutex_lock(&stream->lock);
1682
1683 DBG("Data pending for stream id %" PRIu64 " prev_seq %" PRIu64
1684 " and last_seq %" PRIu64, stream_id, stream->prev_seq,
1685 last_net_seq_num);
1686
1687 /* Avoid wrapping issue */
1688 if (((int64_t) (stream->prev_seq - last_net_seq_num)) >= 0) {
1689 /* Data has in fact been written and is NOT pending */
1690 ret = 0;
1691 } else {
1692 /* Data still being streamed thus pending */
1693 ret = 1;
1694 }
1695
1696 stream->data_pending_check_done = true;
1697 pthread_mutex_unlock(&stream->lock);
1698
1699 stream_put(stream);
1700 end:
1701
1702 memset(&reply, 0, sizeof(reply));
1703 reply.ret_code = htobe32(ret);
1704 ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1705 if (ret < 0) {
1706 ERR("Relay data pending ret code failed");
1707 }
1708
1709 end_no_session:
1710 return ret;
1711 }
1712
1713 /*
1714 * Wait for the control socket to reach a quiescent state.
1715 *
1716 * Note that for now, when receiving this command from the session
1717 * daemon, this means that every subsequent commands or data received on
1718 * the control socket has been handled. So, this is why we simply return
1719 * OK here.
1720 */
1721 static int relay_quiescent_control(struct lttcomm_relayd_hdr *recv_hdr,
1722 struct relay_connection *conn)
1723 {
1724 int ret;
1725 uint64_t stream_id;
1726 struct relay_stream *stream;
1727 struct lttcomm_relayd_quiescent_control msg;
1728 struct lttcomm_relayd_generic_reply reply;
1729
1730 DBG("Checking quiescent state on control socket");
1731
1732 if (!conn->session || conn->version_check_done == 0) {
1733 ERR("Trying to check for data before version check");
1734 ret = -1;
1735 goto end_no_session;
1736 }
1737
1738 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
1739 if (ret < sizeof(msg)) {
1740 if (ret == 0) {
1741 /* Orderly shutdown. Not necessary to print an error. */
1742 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1743 } else {
1744 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1745 ret);
1746 }
1747 ret = -1;
1748 goto end_no_session;
1749 }
1750
1751 stream_id = be64toh(msg.stream_id);
1752 stream = stream_get_by_id(stream_id);
1753 if (!stream) {
1754 goto reply;
1755 }
1756 pthread_mutex_lock(&stream->lock);
1757 stream->data_pending_check_done = true;
1758 pthread_mutex_unlock(&stream->lock);
1759 DBG("Relay quiescent control pending flag set to %" PRIu64, stream_id);
1760 stream_put(stream);
1761 reply:
1762 memset(&reply, 0, sizeof(reply));
1763 reply.ret_code = htobe32(LTTNG_OK);
1764 ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1765 if (ret < 0) {
1766 ERR("Relay data quiescent control ret code failed");
1767 }
1768
1769 end_no_session:
1770 return ret;
1771 }
1772
1773 /*
1774 * Initialize a data pending command. This means that a consumer is about
1775 * to ask for data pending for each stream it holds. Simply iterate over
1776 * all streams of a session and set the data_pending_check_done flag.
1777 *
1778 * This command returns to the client a LTTNG_OK code.
1779 */
1780 static int relay_begin_data_pending(struct lttcomm_relayd_hdr *recv_hdr,
1781 struct relay_connection *conn)
1782 {
1783 int ret;
1784 struct lttng_ht_iter iter;
1785 struct lttcomm_relayd_begin_data_pending msg;
1786 struct lttcomm_relayd_generic_reply reply;
1787 struct relay_stream *stream;
1788 uint64_t session_id;
1789
1790 assert(recv_hdr);
1791 assert(conn);
1792
1793 DBG("Init streams for data pending");
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 begin 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 set the begin data pending flag.
1818 * For now, the streams are indexed by stream handle so we have
1819 * to iterate over all streams to find the one associated with
1820 * the right session_id.
1821 */
1822 rcu_read_lock();
1823 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
1824 node.node) {
1825 if (!stream_get(stream)) {
1826 continue;
1827 }
1828 if (stream->trace->session->id == session_id) {
1829 pthread_mutex_lock(&stream->lock);
1830 stream->data_pending_check_done = false;
1831 pthread_mutex_unlock(&stream->lock);
1832 DBG("Set begin data pending flag to stream %" PRIu64,
1833 stream->stream_handle);
1834 }
1835 stream_put(stream);
1836 }
1837 rcu_read_unlock();
1838
1839 memset(&reply, 0, sizeof(reply));
1840 /* All good, send back reply. */
1841 reply.ret_code = htobe32(LTTNG_OK);
1842
1843 ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1844 if (ret < 0) {
1845 ERR("Relay begin data pending send reply failed");
1846 }
1847
1848 end_no_session:
1849 return ret;
1850 }
1851
1852 /*
1853 * End data pending command. This will check, for a given session id, if
1854 * each stream associated with it has its data_pending_check_done flag
1855 * set. If not, this means that the client lost track of the stream but
1856 * the data is still being streamed on our side. In this case, we inform
1857 * the client that data is in flight.
1858 *
1859 * Return to the client if there is data in flight or not with a ret_code.
1860 */
1861 static int relay_end_data_pending(struct lttcomm_relayd_hdr *recv_hdr,
1862 struct relay_connection *conn)
1863 {
1864 int ret;
1865 struct lttng_ht_iter iter;
1866 struct lttcomm_relayd_end_data_pending msg;
1867 struct lttcomm_relayd_generic_reply reply;
1868 struct relay_stream *stream;
1869 uint64_t session_id;
1870 uint32_t is_data_inflight = 0;
1871
1872 DBG("End data pending command");
1873
1874 if (!conn->session || conn->version_check_done == 0) {
1875 ERR("Trying to check for data before version check");
1876 ret = -1;
1877 goto end_no_session;
1878 }
1879
1880 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
1881 if (ret < sizeof(msg)) {
1882 if (ret == 0) {
1883 /* Orderly shutdown. Not necessary to print an error. */
1884 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1885 } else {
1886 ERR("Relay didn't receive valid end data_pending struct size: %d",
1887 ret);
1888 }
1889 ret = -1;
1890 goto end_no_session;
1891 }
1892
1893 session_id = be64toh(msg.session_id);
1894
1895 /*
1896 * Iterate over all streams to see if the begin data pending
1897 * flag is set.
1898 */
1899 rcu_read_lock();
1900 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
1901 node.node) {
1902 if (!stream_get(stream)) {
1903 continue;
1904 }
1905 if (stream->trace->session->id != session_id) {
1906 stream_put(stream);
1907 continue;
1908 }
1909 pthread_mutex_lock(&stream->lock);
1910 if (!stream->data_pending_check_done) {
1911 if (!stream->closed || !(((int64_t) (stream->prev_seq - stream->last_net_seq_num)) >= 0)) {
1912 is_data_inflight = 1;
1913 DBG("Data is still in flight for stream %" PRIu64,
1914 stream->stream_handle);
1915 pthread_mutex_unlock(&stream->lock);
1916 stream_put(stream);
1917 break;
1918 }
1919 }
1920 pthread_mutex_unlock(&stream->lock);
1921 stream_put(stream);
1922 }
1923 rcu_read_unlock();
1924
1925 memset(&reply, 0, sizeof(reply));
1926 /* All good, send back reply. */
1927 reply.ret_code = htobe32(is_data_inflight);
1928
1929 ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1930 if (ret < 0) {
1931 ERR("Relay end data pending send reply failed");
1932 }
1933
1934 end_no_session:
1935 return ret;
1936 }
1937
1938 /*
1939 * Receive an index for a specific stream.
1940 *
1941 * Return 0 on success else a negative value.
1942 */
1943 static int relay_recv_index(struct lttcomm_relayd_hdr *recv_hdr,
1944 struct relay_connection *conn)
1945 {
1946 int ret, send_ret;
1947 struct relay_session *session = conn->session;
1948 struct lttcomm_relayd_index index_info;
1949 struct relay_index *index;
1950 struct lttcomm_relayd_generic_reply reply;
1951 struct relay_stream *stream;
1952 uint64_t net_seq_num;
1953 size_t msg_len;
1954
1955 assert(conn);
1956
1957 DBG("Relay receiving index");
1958
1959 if (!session || conn->version_check_done == 0) {
1960 ERR("Trying to close a stream before version check");
1961 ret = -1;
1962 goto end_no_session;
1963 }
1964
1965 msg_len = lttcomm_relayd_index_len(
1966 lttng_to_index_major(conn->major, conn->minor),
1967 lttng_to_index_minor(conn->major, conn->minor));
1968 ret = conn->sock->ops->recvmsg(conn->sock, &index_info,
1969 msg_len, 0);
1970 if (ret < msg_len) {
1971 if (ret == 0) {
1972 /* Orderly shutdown. Not necessary to print an error. */
1973 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1974 } else {
1975 ERR("Relay didn't receive valid index struct size : %d", ret);
1976 }
1977 ret = -1;
1978 goto end_no_session;
1979 }
1980
1981 net_seq_num = be64toh(index_info.net_seq_num);
1982
1983 stream = stream_get_by_id(be64toh(index_info.relay_stream_id));
1984 if (!stream) {
1985 ERR("stream_get_by_id not found");
1986 ret = -1;
1987 goto end;
1988 }
1989 pthread_mutex_lock(&stream->lock);
1990
1991 /* Live beacon handling */
1992 if (index_info.packet_size == 0) {
1993 DBG("Received live beacon for stream %" PRIu64,
1994 stream->stream_handle);
1995
1996 /*
1997 * Only flag a stream inactive when it has already
1998 * received data and no indexes are in flight.
1999 */
2000 if (stream->index_received_seqcount > 0
2001 && stream->indexes_in_flight == 0) {
2002 stream->beacon_ts_end =
2003 be64toh(index_info.timestamp_end);
2004 }
2005 ret = 0;
2006 goto end_stream_put;
2007 } else {
2008 stream->beacon_ts_end = -1ULL;
2009 }
2010
2011 if (stream->ctf_stream_id == -1ULL) {
2012 stream->ctf_stream_id = be64toh(index_info.stream_id);
2013 }
2014 index = relay_index_get_by_id_or_create(stream, net_seq_num);
2015 if (!index) {
2016 ret = -1;
2017 ERR("relay_index_get_by_id_or_create index NULL");
2018 goto end_stream_put;
2019 }
2020 if (set_index_control_data(index, &index_info, conn)) {
2021 ERR("set_index_control_data error");
2022 relay_index_put(index);
2023 ret = -1;
2024 goto end_stream_put;
2025 }
2026 ret = relay_index_try_flush(index);
2027 if (ret == 0) {
2028 tracefile_array_commit_seq(stream->tfa);
2029 stream->index_received_seqcount++;
2030 } else if (ret > 0) {
2031 /* no flush. */
2032 ret = 0;
2033 } else {
2034 ERR("relay_index_try_flush error %d", ret);
2035 relay_index_put(index);
2036 ret = -1;
2037 }
2038
2039 end_stream_put:
2040 pthread_mutex_unlock(&stream->lock);
2041 stream_put(stream);
2042
2043 end:
2044
2045 memset(&reply, 0, sizeof(reply));
2046 if (ret < 0) {
2047 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2048 } else {
2049 reply.ret_code = htobe32(LTTNG_OK);
2050 }
2051 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2052 if (send_ret < 0) {
2053 ERR("Relay sending close index id reply");
2054 ret = send_ret;
2055 }
2056
2057 end_no_session:
2058 return ret;
2059 }
2060
2061 /*
2062 * Receive the streams_sent message.
2063 *
2064 * Return 0 on success else a negative value.
2065 */
2066 static int relay_streams_sent(struct lttcomm_relayd_hdr *recv_hdr,
2067 struct relay_connection *conn)
2068 {
2069 int ret, send_ret;
2070 struct lttcomm_relayd_generic_reply reply;
2071
2072 assert(conn);
2073
2074 DBG("Relay receiving streams_sent");
2075
2076 if (!conn->session || conn->version_check_done == 0) {
2077 ERR("Trying to close a stream before version check");
2078 ret = -1;
2079 goto end_no_session;
2080 }
2081
2082 /*
2083 * Publish every pending stream in the connection recv list which are
2084 * now ready to be used by the viewer.
2085 */
2086 publish_connection_local_streams(conn);
2087
2088 memset(&reply, 0, sizeof(reply));
2089 reply.ret_code = htobe32(LTTNG_OK);
2090 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2091 if (send_ret < 0) {
2092 ERR("Relay sending sent_stream reply");
2093 ret = send_ret;
2094 } else {
2095 /* Success. */
2096 ret = 0;
2097 }
2098
2099 end_no_session:
2100 return ret;
2101 }
2102
2103 /*
2104 * Process the commands received on the control socket
2105 */
2106 static int relay_process_control(struct lttcomm_relayd_hdr *recv_hdr,
2107 struct relay_connection *conn)
2108 {
2109 int ret = 0;
2110
2111 switch (be32toh(recv_hdr->cmd)) {
2112 case RELAYD_CREATE_SESSION:
2113 ret = relay_create_session(recv_hdr, conn);
2114 break;
2115 case RELAYD_ADD_STREAM:
2116 ret = relay_add_stream(recv_hdr, conn);
2117 break;
2118 case RELAYD_START_DATA:
2119 ret = relay_start(recv_hdr, conn);
2120 break;
2121 case RELAYD_SEND_METADATA:
2122 ret = relay_recv_metadata(recv_hdr, conn);
2123 break;
2124 case RELAYD_VERSION:
2125 ret = relay_send_version(recv_hdr, conn);
2126 break;
2127 case RELAYD_CLOSE_STREAM:
2128 ret = relay_close_stream(recv_hdr, conn);
2129 break;
2130 case RELAYD_DATA_PENDING:
2131 ret = relay_data_pending(recv_hdr, conn);
2132 break;
2133 case RELAYD_QUIESCENT_CONTROL:
2134 ret = relay_quiescent_control(recv_hdr, conn);
2135 break;
2136 case RELAYD_BEGIN_DATA_PENDING:
2137 ret = relay_begin_data_pending(recv_hdr, conn);
2138 break;
2139 case RELAYD_END_DATA_PENDING:
2140 ret = relay_end_data_pending(recv_hdr, conn);
2141 break;
2142 case RELAYD_SEND_INDEX:
2143 ret = relay_recv_index(recv_hdr, conn);
2144 break;
2145 case RELAYD_STREAMS_SENT:
2146 ret = relay_streams_sent(recv_hdr, conn);
2147 break;
2148 case RELAYD_RESET_METADATA:
2149 ret = relay_reset_metadata(recv_hdr, conn);
2150 break;
2151 case RELAYD_UPDATE_SYNC_INFO:
2152 default:
2153 ERR("Received unknown command (%u)", be32toh(recv_hdr->cmd));
2154 relay_unknown_command(conn);
2155 ret = -1;
2156 goto end;
2157 }
2158
2159 end:
2160 return ret;
2161 }
2162
2163 /*
2164 * Handle index for a data stream.
2165 *
2166 * Called with the stream lock held.
2167 *
2168 * Return 0 on success else a negative value.
2169 */
2170 static int handle_index_data(struct relay_stream *stream, uint64_t net_seq_num,
2171 int rotate_index)
2172 {
2173 int ret = 0;
2174 uint64_t data_offset;
2175 struct relay_index *index;
2176
2177 /* Get data offset because we are about to update the index. */
2178 data_offset = htobe64(stream->tracefile_size_current);
2179
2180 DBG("handle_index_data: stream %" PRIu64 " net_seq_num %" PRIu64 " data offset %" PRIu64,
2181 stream->stream_handle, net_seq_num, stream->tracefile_size_current);
2182
2183 /*
2184 * Lookup for an existing index for that stream id/sequence
2185 * number. If it exists, the control thread has already received the
2186 * data for it, thus we need to write it to disk.
2187 */
2188 index = relay_index_get_by_id_or_create(stream, net_seq_num);
2189 if (!index) {
2190 ret = -1;
2191 goto end;
2192 }
2193
2194 if (rotate_index || !stream->index_file) {
2195 uint32_t major, minor;
2196
2197 /* Put ref on previous index_file. */
2198 if (stream->index_file) {
2199 lttng_index_file_put(stream->index_file);
2200 stream->index_file = NULL;
2201 }
2202 major = stream->trace->session->major;
2203 minor = stream->trace->session->minor;
2204 stream->index_file = lttng_index_file_create(stream->path_name,
2205 stream->channel_name,
2206 -1, -1, stream->tracefile_size,
2207 tracefile_array_get_file_index_head(stream->tfa),
2208 lttng_to_index_major(major, minor),
2209 lttng_to_index_minor(major, minor));
2210 if (!stream->index_file) {
2211 ret = -1;
2212 /* Put self-ref for this index due to error. */
2213 relay_index_put(index);
2214 index = NULL;
2215 goto end;
2216 }
2217 }
2218
2219 if (relay_index_set_file(index, stream->index_file, data_offset)) {
2220 ret = -1;
2221 /* Put self-ref for this index due to error. */
2222 relay_index_put(index);
2223 index = NULL;
2224 goto end;
2225 }
2226
2227 ret = relay_index_try_flush(index);
2228 if (ret == 0) {
2229 tracefile_array_commit_seq(stream->tfa);
2230 stream->index_received_seqcount++;
2231 } else if (ret > 0) {
2232 /* No flush. */
2233 ret = 0;
2234 } else {
2235 /* Put self-ref for this index due to error. */
2236 relay_index_put(index);
2237 index = NULL;
2238 ret = -1;
2239 }
2240 end:
2241 return ret;
2242 }
2243
2244 /*
2245 * relay_process_data: Process the data received on the data socket
2246 */
2247 static int relay_process_data(struct relay_connection *conn)
2248 {
2249 int ret = 0, rotate_index = 0;
2250 ssize_t size_ret;
2251 struct relay_stream *stream;
2252 struct lttcomm_relayd_data_hdr data_hdr;
2253 uint64_t stream_id;
2254 uint64_t net_seq_num;
2255 uint32_t data_size;
2256 struct relay_session *session;
2257 bool new_stream = false, close_requested = false;
2258 size_t chunk_size = RECV_DATA_BUFFER_SIZE;
2259 size_t recv_off = 0;
2260 char data_buffer[chunk_size];
2261
2262 ret = conn->sock->ops->recvmsg(conn->sock, &data_hdr,
2263 sizeof(struct lttcomm_relayd_data_hdr), 0);
2264 if (ret <= 0) {
2265 if (ret == 0) {
2266 /* Orderly shutdown. Not necessary to print an error. */
2267 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
2268 } else {
2269 ERR("Unable to receive data header on sock %d", conn->sock->fd);
2270 }
2271 ret = -1;
2272 goto end;
2273 }
2274
2275 stream_id = be64toh(data_hdr.stream_id);
2276 stream = stream_get_by_id(stream_id);
2277 if (!stream) {
2278 ERR("relay_process_data: Cannot find stream %" PRIu64, stream_id);
2279 ret = -1;
2280 goto end;
2281 }
2282 session = stream->trace->session;
2283 data_size = be32toh(data_hdr.data_size);
2284
2285 net_seq_num = be64toh(data_hdr.net_seq_num);
2286
2287 DBG3("Receiving data of size %u for stream id %" PRIu64 " seqnum %" PRIu64,
2288 data_size, stream_id, net_seq_num);
2289
2290 pthread_mutex_lock(&stream->lock);
2291
2292 /* Check if a rotation is needed. */
2293 if (stream->tracefile_size > 0 &&
2294 (stream->tracefile_size_current + data_size) >
2295 stream->tracefile_size) {
2296 uint64_t old_id, new_id;
2297
2298 old_id = tracefile_array_get_file_index_head(stream->tfa);
2299 tracefile_array_file_rotate(stream->tfa);
2300
2301 /* new_id is updated by utils_rotate_stream_file. */
2302 new_id = old_id;
2303
2304 ret = utils_rotate_stream_file(stream->path_name,
2305 stream->channel_name, stream->tracefile_size,
2306 stream->tracefile_count, -1,
2307 -1, stream->stream_fd->fd,
2308 &new_id, &stream->stream_fd->fd);
2309 if (ret < 0) {
2310 ERR("Rotating stream output file");
2311 goto end_stream_unlock;
2312 }
2313 /*
2314 * Reset current size because we just performed a stream
2315 * rotation.
2316 */
2317 stream->tracefile_size_current = 0;
2318 rotate_index = 1;
2319 }
2320
2321 /*
2322 * Index are handled in protocol version 2.4 and above. Also,
2323 * snapshot and index are NOT supported.
2324 */
2325 if (session->minor >= 4 && !session->snapshot) {
2326 ret = handle_index_data(stream, net_seq_num, rotate_index);
2327 if (ret < 0) {
2328 ERR("handle_index_data: fail stream %" PRIu64 " net_seq_num %" PRIu64 " ret %d",
2329 stream->stream_handle, net_seq_num, ret);
2330 goto end_stream_unlock;
2331 }
2332 }
2333
2334 for (recv_off = 0; recv_off < data_size; recv_off += chunk_size) {
2335 size_t recv_size = min(data_size - recv_off, chunk_size);
2336
2337 ret = conn->sock->ops->recvmsg(conn->sock, data_buffer, recv_size, 0);
2338 if (ret <= 0) {
2339 if (ret == 0) {
2340 /* Orderly shutdown. Not necessary to print an error. */
2341 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
2342 } else {
2343 ERR("Socket %d error %d", conn->sock->fd, ret);
2344 }
2345 ret = -1;
2346 goto end_stream_unlock;
2347 }
2348
2349 /* Write data to stream output fd. */
2350 size_ret = lttng_write(stream->stream_fd->fd, data_buffer,
2351 recv_size);
2352 if (size_ret < recv_size) {
2353 ERR("Relay error writing data to file");
2354 ret = -1;
2355 goto end_stream_unlock;
2356 }
2357
2358 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64,
2359 size_ret, stream->stream_handle);
2360 }
2361
2362 ret = write_padding_to_file(stream->stream_fd->fd,
2363 be32toh(data_hdr.padding_size));
2364 if (ret < 0) {
2365 ERR("write_padding_to_file: fail stream %" PRIu64 " net_seq_num %" PRIu64 " ret %d",
2366 stream->stream_handle, net_seq_num, ret);
2367 goto end_stream_unlock;
2368 }
2369 stream->tracefile_size_current +=
2370 data_size + be32toh(data_hdr.padding_size);
2371 if (stream->prev_seq == -1ULL) {
2372 new_stream = true;
2373 }
2374
2375 stream->prev_seq = net_seq_num;
2376
2377 end_stream_unlock:
2378 close_requested = stream->close_requested;
2379 pthread_mutex_unlock(&stream->lock);
2380 if (close_requested) {
2381 try_stream_close(stream);
2382 }
2383
2384 if (new_stream) {
2385 pthread_mutex_lock(&session->lock);
2386 uatomic_set(&session->new_streams, 1);
2387 pthread_mutex_unlock(&session->lock);
2388 }
2389 stream_put(stream);
2390 end:
2391 return ret;
2392 }
2393
2394 static void cleanup_connection_pollfd(struct lttng_poll_event *events, int pollfd)
2395 {
2396 int ret;
2397
2398 (void) lttng_poll_del(events, pollfd);
2399
2400 ret = close(pollfd);
2401 if (ret < 0) {
2402 ERR("Closing pollfd %d", pollfd);
2403 }
2404 }
2405
2406 static void relay_thread_close_connection(struct lttng_poll_event *events,
2407 int pollfd, struct relay_connection *conn)
2408 {
2409 const char *type_str;
2410
2411 switch (conn->type) {
2412 case RELAY_DATA:
2413 type_str = "Data";
2414 break;
2415 case RELAY_CONTROL:
2416 type_str = "Control";
2417 break;
2418 case RELAY_VIEWER_COMMAND:
2419 type_str = "Viewer Command";
2420 break;
2421 case RELAY_VIEWER_NOTIFICATION:
2422 type_str = "Viewer Notification";
2423 break;
2424 default:
2425 type_str = "Unknown";
2426 }
2427 cleanup_connection_pollfd(events, pollfd);
2428 connection_put(conn);
2429 DBG("%s connection closed with %d", type_str, pollfd);
2430 }
2431
2432 /*
2433 * This thread does the actual work
2434 */
2435 static void *relay_thread_worker(void *data)
2436 {
2437 int ret, err = -1, last_seen_data_fd = -1;
2438 uint32_t nb_fd;
2439 struct lttng_poll_event events;
2440 struct lttng_ht *relay_connections_ht;
2441 struct lttng_ht_iter iter;
2442 struct lttcomm_relayd_hdr recv_hdr;
2443 struct relay_connection *destroy_conn = NULL;
2444
2445 DBG("[thread] Relay worker started");
2446
2447 rcu_register_thread();
2448
2449 health_register(health_relayd, HEALTH_RELAYD_TYPE_WORKER);
2450
2451 if (testpoint(relayd_thread_worker)) {
2452 goto error_testpoint;
2453 }
2454
2455 health_code_update();
2456
2457 /* table of connections indexed on socket */
2458 relay_connections_ht = lttng_ht_new(0, LTTNG_HT_TYPE_ULONG);
2459 if (!relay_connections_ht) {
2460 goto relay_connections_ht_error;
2461 }
2462
2463 ret = create_thread_poll_set(&events, 2);
2464 if (ret < 0) {
2465 goto error_poll_create;
2466 }
2467
2468 ret = lttng_poll_add(&events, relay_conn_pipe[0], LPOLLIN | LPOLLRDHUP);
2469 if (ret < 0) {
2470 goto error;
2471 }
2472
2473 restart:
2474 while (1) {
2475 int idx = -1, i, seen_control = 0, last_notdel_data_fd = -1;
2476
2477 health_code_update();
2478
2479 /* Infinite blocking call, waiting for transmission */
2480 DBG3("Relayd worker thread polling...");
2481 health_poll_entry();
2482 ret = lttng_poll_wait(&events, -1);
2483 health_poll_exit();
2484 if (ret < 0) {
2485 /*
2486 * Restart interrupted system call.
2487 */
2488 if (errno == EINTR) {
2489 goto restart;
2490 }
2491 goto error;
2492 }
2493
2494 nb_fd = ret;
2495
2496 /*
2497 * Process control. The control connection is
2498 * prioritized so we don't starve it with high
2499 * throughput tracing data on the data connection.
2500 */
2501 for (i = 0; i < nb_fd; i++) {
2502 /* Fetch once the poll data */
2503 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
2504 int pollfd = LTTNG_POLL_GETFD(&events, i);
2505
2506 health_code_update();
2507
2508 if (!revents) {
2509 /*
2510 * No activity for this FD (poll
2511 * implementation).
2512 */
2513 continue;
2514 }
2515
2516 /* Thread quit pipe has been closed. Killing thread. */
2517 ret = check_thread_quit_pipe(pollfd, revents);
2518 if (ret) {
2519 err = 0;
2520 goto exit;
2521 }
2522
2523 /* Inspect the relay conn pipe for new connection */
2524 if (pollfd == relay_conn_pipe[0]) {
2525 if (revents & LPOLLIN) {
2526 struct relay_connection *conn;
2527
2528 ret = lttng_read(relay_conn_pipe[0], &conn, sizeof(conn));
2529 if (ret < 0) {
2530 goto error;
2531 }
2532 lttng_poll_add(&events, conn->sock->fd,
2533 LPOLLIN | LPOLLRDHUP);
2534 connection_ht_add(relay_connections_ht, conn);
2535 DBG("Connection socket %d added", conn->sock->fd);
2536 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2537 ERR("Relay connection pipe error");
2538 goto error;
2539 } else {
2540 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
2541 goto error;
2542 }
2543 } else {
2544 struct relay_connection *ctrl_conn;
2545
2546 ctrl_conn = connection_get_by_sock(relay_connections_ht, pollfd);
2547 /* If not found, there is a synchronization issue. */
2548 assert(ctrl_conn);
2549
2550 if (ctrl_conn->type == RELAY_DATA) {
2551 if (revents & LPOLLIN) {
2552 /*
2553 * Flag the last seen data fd not deleted. It will be
2554 * used as the last seen fd if any fd gets deleted in
2555 * this first loop.
2556 */
2557 last_notdel_data_fd = pollfd;
2558 }
2559 goto put_ctrl_connection;
2560 }
2561 assert(ctrl_conn->type == RELAY_CONTROL);
2562
2563 if (revents & LPOLLIN) {
2564 ret = ctrl_conn->sock->ops->recvmsg(ctrl_conn->sock,
2565 &recv_hdr, sizeof(recv_hdr), 0);
2566 if (ret <= 0) {
2567 /* Connection closed */
2568 relay_thread_close_connection(&events, pollfd,
2569 ctrl_conn);
2570 } else {
2571 ret = relay_process_control(&recv_hdr, ctrl_conn);
2572 if (ret < 0) {
2573 /* Clear the session on error. */
2574 relay_thread_close_connection(&events,
2575 pollfd, ctrl_conn);
2576 }
2577 seen_control = 1;
2578 }
2579 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2580 relay_thread_close_connection(&events,
2581 pollfd, ctrl_conn);
2582 if (last_seen_data_fd == pollfd) {
2583 last_seen_data_fd = last_notdel_data_fd;
2584 }
2585 } else {
2586 ERR("Unexpected poll events %u for control sock %d",
2587 revents, pollfd);
2588 connection_put(ctrl_conn);
2589 goto error;
2590 }
2591 put_ctrl_connection:
2592 connection_put(ctrl_conn);
2593 }
2594 }
2595
2596 /*
2597 * The last loop handled a control request, go back to poll to make
2598 * sure we prioritise the control socket.
2599 */
2600 if (seen_control) {
2601 continue;
2602 }
2603
2604 if (last_seen_data_fd >= 0) {
2605 for (i = 0; i < nb_fd; i++) {
2606 int pollfd = LTTNG_POLL_GETFD(&events, i);
2607
2608 health_code_update();
2609
2610 if (last_seen_data_fd == pollfd) {
2611 idx = i;
2612 break;
2613 }
2614 }
2615 }
2616
2617 /* Process data connection. */
2618 for (i = idx + 1; i < nb_fd; i++) {
2619 /* Fetch the poll data. */
2620 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
2621 int pollfd = LTTNG_POLL_GETFD(&events, i);
2622 struct relay_connection *data_conn;
2623
2624 health_code_update();
2625
2626 if (!revents) {
2627 /* No activity for this FD (poll implementation). */
2628 continue;
2629 }
2630
2631 /* Skip the command pipe. It's handled in the first loop. */
2632 if (pollfd == relay_conn_pipe[0]) {
2633 continue;
2634 }
2635
2636 data_conn = connection_get_by_sock(relay_connections_ht, pollfd);
2637 if (!data_conn) {
2638 /* Skip it. Might be removed before. */
2639 continue;
2640 }
2641 if (data_conn->type == RELAY_CONTROL) {
2642 goto put_data_connection;
2643 }
2644 assert(data_conn->type == RELAY_DATA);
2645
2646 if (revents & LPOLLIN) {
2647 ret = relay_process_data(data_conn);
2648 /* Connection closed */
2649 if (ret < 0) {
2650 relay_thread_close_connection(&events, pollfd,
2651 data_conn);
2652 /*
2653 * Every goto restart call sets the last seen fd where
2654 * here we don't really care since we gracefully
2655 * continue the loop after the connection is deleted.
2656 */
2657 } else {
2658 /* Keep last seen port. */
2659 last_seen_data_fd = pollfd;
2660 connection_put(data_conn);
2661 goto restart;
2662 }
2663 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2664 relay_thread_close_connection(&events, pollfd,
2665 data_conn);
2666 } else {
2667 ERR("Unknown poll events %u for data sock %d",
2668 revents, pollfd);
2669 }
2670 put_data_connection:
2671 connection_put(data_conn);
2672 }
2673 last_seen_data_fd = -1;
2674 }
2675
2676 /* Normal exit, no error */
2677 ret = 0;
2678
2679 exit:
2680 error:
2681 /* Cleanup reamaining connection object. */
2682 rcu_read_lock();
2683 cds_lfht_for_each_entry(relay_connections_ht->ht, &iter.iter,
2684 destroy_conn,
2685 sock_n.node) {
2686 health_code_update();
2687
2688 if (session_abort(destroy_conn->session)) {
2689 assert(0);
2690 }
2691
2692 /*
2693 * No need to grab another ref, because we own
2694 * destroy_conn.
2695 */
2696 relay_thread_close_connection(&events, destroy_conn->sock->fd,
2697 destroy_conn);
2698 }
2699 rcu_read_unlock();
2700
2701 lttng_poll_clean(&events);
2702 error_poll_create:
2703 lttng_ht_destroy(relay_connections_ht);
2704 relay_connections_ht_error:
2705 /* Close relay conn pipes */
2706 utils_close_pipe(relay_conn_pipe);
2707 if (err) {
2708 DBG("Thread exited with error");
2709 }
2710 DBG("Worker thread cleanup complete");
2711 error_testpoint:
2712 if (err) {
2713 health_error();
2714 ERR("Health error occurred in %s", __func__);
2715 }
2716 health_unregister(health_relayd);
2717 rcu_unregister_thread();
2718 lttng_relay_stop_threads();
2719 return NULL;
2720 }
2721
2722 /*
2723 * Create the relay command pipe to wake thread_manage_apps.
2724 * Closed in cleanup().
2725 */
2726 static int create_relay_conn_pipe(void)
2727 {
2728 int ret;
2729
2730 ret = utils_create_pipe_cloexec(relay_conn_pipe);
2731
2732 return ret;
2733 }
2734
2735 /*
2736 * main
2737 */
2738 int main(int argc, char **argv)
2739 {
2740 int ret = 0, retval = 0;
2741 void *status;
2742
2743 /* Parse arguments */
2744 progname = argv[0];
2745 if (set_options(argc, argv)) {
2746 retval = -1;
2747 goto exit_options;
2748 }
2749
2750 if (set_signal_handler()) {
2751 retval = -1;
2752 goto exit_options;
2753 }
2754
2755 /* Try to create directory if -o, --output is specified. */
2756 if (opt_output_path) {
2757 if (*opt_output_path != '/') {
2758 ERR("Please specify an absolute path for -o, --output PATH");
2759 retval = -1;
2760 goto exit_options;
2761 }
2762
2763 ret = utils_mkdir_recursive(opt_output_path, S_IRWXU | S_IRWXG,
2764 -1, -1);
2765 if (ret < 0) {
2766 ERR("Unable to create %s", opt_output_path);
2767 retval = -1;
2768 goto exit_options;
2769 }
2770 }
2771
2772 /* Daemonize */
2773 if (opt_daemon || opt_background) {
2774 int i;
2775
2776 ret = lttng_daemonize(&child_ppid, &recv_child_signal,
2777 !opt_background);
2778 if (ret < 0) {
2779 retval = -1;
2780 goto exit_options;
2781 }
2782
2783 /*
2784 * We are in the child. Make sure all other file
2785 * descriptors are closed, in case we are called with
2786 * more opened file descriptors than the standard ones.
2787 */
2788 for (i = 3; i < sysconf(_SC_OPEN_MAX); i++) {
2789 (void) close(i);
2790 }
2791 }
2792
2793 /* Initialize thread health monitoring */
2794 health_relayd = health_app_create(NR_HEALTH_RELAYD_TYPES);
2795 if (!health_relayd) {
2796 PERROR("health_app_create error");
2797 retval = -1;
2798 goto exit_health_app_create;
2799 }
2800
2801 /* Create thread quit pipe */
2802 if (init_thread_quit_pipe()) {
2803 retval = -1;
2804 goto exit_init_data;
2805 }
2806
2807 /* Setup the thread apps communication pipe. */
2808 if (create_relay_conn_pipe()) {
2809 retval = -1;
2810 goto exit_init_data;
2811 }
2812
2813 /* Init relay command queue. */
2814 cds_wfcq_init(&relay_conn_queue.head, &relay_conn_queue.tail);
2815
2816 /* Initialize communication library */
2817 lttcomm_init();
2818 lttcomm_inet_init();
2819
2820 /* tables of sessions indexed by session ID */
2821 sessions_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
2822 if (!sessions_ht) {
2823 retval = -1;
2824 goto exit_init_data;
2825 }
2826
2827 /* tables of streams indexed by stream ID */
2828 relay_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
2829 if (!relay_streams_ht) {
2830 retval = -1;
2831 goto exit_init_data;
2832 }
2833
2834 /* tables of streams indexed by stream ID */
2835 viewer_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
2836 if (!viewer_streams_ht) {
2837 retval = -1;
2838 goto exit_init_data;
2839 }
2840
2841 ret = utils_create_pipe(health_quit_pipe);
2842 if (ret) {
2843 retval = -1;
2844 goto exit_health_quit_pipe;
2845 }
2846
2847 /* Create thread to manage the client socket */
2848 ret = pthread_create(&health_thread, default_pthread_attr(),
2849 thread_manage_health, (void *) NULL);
2850 if (ret) {
2851 errno = ret;
2852 PERROR("pthread_create health");
2853 retval = -1;
2854 goto exit_health_thread;
2855 }
2856
2857 /* Setup the dispatcher thread */
2858 ret = pthread_create(&dispatcher_thread, default_pthread_attr(),
2859 relay_thread_dispatcher, (void *) NULL);
2860 if (ret) {
2861 errno = ret;
2862 PERROR("pthread_create dispatcher");
2863 retval = -1;
2864 goto exit_dispatcher_thread;
2865 }
2866
2867 /* Setup the worker thread */
2868 ret = pthread_create(&worker_thread, default_pthread_attr(),
2869 relay_thread_worker, NULL);
2870 if (ret) {
2871 errno = ret;
2872 PERROR("pthread_create worker");
2873 retval = -1;
2874 goto exit_worker_thread;
2875 }
2876
2877 /* Setup the listener thread */
2878 ret = pthread_create(&listener_thread, default_pthread_attr(),
2879 relay_thread_listener, (void *) NULL);
2880 if (ret) {
2881 errno = ret;
2882 PERROR("pthread_create listener");
2883 retval = -1;
2884 goto exit_listener_thread;
2885 }
2886
2887 ret = relayd_live_create(live_uri);
2888 if (ret) {
2889 ERR("Starting live viewer threads");
2890 retval = -1;
2891 goto exit_live;
2892 }
2893
2894 /*
2895 * This is where we start awaiting program completion (e.g. through
2896 * signal that asks threads to teardown).
2897 */
2898
2899 ret = relayd_live_join();
2900 if (ret) {
2901 retval = -1;
2902 }
2903 exit_live:
2904
2905 ret = pthread_join(listener_thread, &status);
2906 if (ret) {
2907 errno = ret;
2908 PERROR("pthread_join listener_thread");
2909 retval = -1;
2910 }
2911
2912 exit_listener_thread:
2913 ret = pthread_join(worker_thread, &status);
2914 if (ret) {
2915 errno = ret;
2916 PERROR("pthread_join worker_thread");
2917 retval = -1;
2918 }
2919
2920 exit_worker_thread:
2921 ret = pthread_join(dispatcher_thread, &status);
2922 if (ret) {
2923 errno = ret;
2924 PERROR("pthread_join dispatcher_thread");
2925 retval = -1;
2926 }
2927 exit_dispatcher_thread:
2928
2929 ret = pthread_join(health_thread, &status);
2930 if (ret) {
2931 errno = ret;
2932 PERROR("pthread_join health_thread");
2933 retval = -1;
2934 }
2935 exit_health_thread:
2936
2937 utils_close_pipe(health_quit_pipe);
2938 exit_health_quit_pipe:
2939
2940 exit_init_data:
2941 health_app_destroy(health_relayd);
2942 exit_health_app_create:
2943 exit_options:
2944 /*
2945 * Wait for all pending call_rcu work to complete before tearing
2946 * down data structures. call_rcu worker may be trying to
2947 * perform lookups in those structures.
2948 */
2949 rcu_barrier();
2950 relayd_cleanup();
2951
2952 /* Ensure all prior call_rcu are done. */
2953 rcu_barrier();
2954
2955 if (!retval) {
2956 exit(EXIT_SUCCESS);
2957 } else {
2958 exit(EXIT_FAILURE);
2959 }
2960 }
This page took 0.13182 seconds and 6 git commands to generate.