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