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