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