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