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