d38cdfecb9c6cd6069d848c5e4cfb5566dc9a04e
[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 fprintf(stderr, "name: %s\n", session_name);
1106 session = session_create(session_name, hostname, live_timer,
1107 snapshot, conn->major, conn->minor);
1108 if (!session) {
1109 ret = -1;
1110 goto send_reply;
1111 }
1112 assert(!conn->session);
1113 conn->session = session;
1114 DBG("Created session %" PRIu64, session->id);
1115
1116 reply.session_id = htobe64(session->id);
1117
1118 send_reply:
1119 if (ret < 0) {
1120 reply.ret_code = htobe32(LTTNG_ERR_FATAL);
1121 } else {
1122 reply.ret_code = htobe32(LTTNG_OK);
1123 }
1124
1125 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1126 if (send_ret < 0) {
1127 ERR("Relayd sending session id");
1128 ret = send_ret;
1129 }
1130
1131 return ret;
1132 }
1133
1134 /*
1135 * When we have received all the streams and the metadata for a channel,
1136 * we make them visible to the viewer threads.
1137 */
1138 static void publish_connection_local_streams(struct relay_connection *conn)
1139 {
1140 struct relay_stream *stream;
1141 struct relay_session *session = conn->session;
1142
1143 /*
1144 * We publish all streams belonging to a session atomically wrt
1145 * session lock.
1146 */
1147 pthread_mutex_lock(&session->lock);
1148 rcu_read_lock();
1149 cds_list_for_each_entry_rcu(stream, &session->recv_list,
1150 recv_node) {
1151 stream_publish(stream);
1152 }
1153 rcu_read_unlock();
1154
1155 /*
1156 * Inform the viewer that there are new streams in the session.
1157 */
1158 if (session->viewer_attached) {
1159 uatomic_set(&session->new_streams, 1);
1160 }
1161 pthread_mutex_unlock(&session->lock);
1162 }
1163
1164 /*
1165 * relay_add_stream: allocate a new stream for a session
1166 */
1167 static int relay_add_stream(struct lttcomm_relayd_hdr *recv_hdr,
1168 struct relay_connection *conn)
1169 {
1170 int ret;
1171 ssize_t send_ret;
1172 struct relay_session *session = conn->session;
1173 struct relay_stream *stream = NULL;
1174 struct lttcomm_relayd_status_stream reply;
1175 struct ctf_trace *trace = NULL;
1176 uint64_t stream_handle = -1ULL;
1177 char *path_name = NULL, *channel_name = NULL;
1178 uint64_t tracefile_size = 0, tracefile_count = 0;
1179
1180 if (!session || conn->version_check_done == 0) {
1181 ERR("Trying to add a stream before version check");
1182 ret = -1;
1183 goto end_no_session;
1184 }
1185
1186 switch (session->minor) {
1187 case 1: /* LTTng sessiond 2.1. Allocates path_name and channel_name. */
1188 ret = cmd_recv_stream_2_1(conn, &path_name,
1189 &channel_name);
1190 break;
1191 case 2: /* LTTng sessiond 2.2. Allocates path_name and channel_name. */
1192 case 3: /* LTTng sessiond 2.3. Allocates path_name and channel_name. */
1193 case 4: /* LTTng sessiond 2.4. Allocates path_name and channel_name. */
1194 case 5: /* LTTng sessiond 2.5. Allocates path_name and channel_name. */
1195 case 6: /* LTTng sessiond 2.6. Allocates path_name and channel_name. */
1196 case 7: /* LTTng sessiond 2.7. Allocates path_name and channel_name. */
1197 case 8: /* LTTng sessiond 2.8. Allocates path_name and channel_name. */
1198 case 9: /* LTTng sessiond 2.9. Allocates path_name and channel_name. */
1199 case 10: /* LTTng sessiond 2.10. Allocates path_name and channel_name. */
1200 ret = cmd_recv_stream_2_2(conn, &path_name,
1201 &channel_name, &tracefile_size, &tracefile_count);
1202 break;
1203 case 11: /* LTTng sessiond 2.11. Allocates path_name and channel_name. */
1204 default:
1205 ret = cmd_recv_stream_2_11(conn, &path_name,
1206 &channel_name, &tracefile_size, &tracefile_count,
1207 session);
1208 break;
1209 }
1210 if (ret < 0) {
1211 goto send_reply;
1212 }
1213
1214 trace = ctf_trace_get_by_path_or_create(session, path_name);
1215 if (!trace) {
1216 goto send_reply;
1217 }
1218 /* This stream here has one reference on the trace. */
1219
1220 pthread_mutex_lock(&last_relay_stream_id_lock);
1221 stream_handle = ++last_relay_stream_id;
1222 pthread_mutex_unlock(&last_relay_stream_id_lock);
1223
1224 /* We pass ownership of path_name and channel_name. */
1225 stream = stream_create(trace, stream_handle, path_name,
1226 channel_name, tracefile_size, tracefile_count);
1227 path_name = NULL;
1228 channel_name = NULL;
1229
1230 /*
1231 * Streams are the owners of their trace. Reference to trace is
1232 * kept within stream_create().
1233 */
1234 ctf_trace_put(trace);
1235
1236 send_reply:
1237 memset(&reply, 0, sizeof(reply));
1238 reply.handle = htobe64(stream_handle);
1239 if (!stream) {
1240 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1241 } else {
1242 reply.ret_code = htobe32(LTTNG_OK);
1243 }
1244
1245 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1246 sizeof(struct lttcomm_relayd_status_stream), 0);
1247 if (send_ret < 0) {
1248 ERR("Relay sending stream id");
1249 ret = (int) send_ret;
1250 }
1251
1252 end_no_session:
1253 free(path_name);
1254 free(channel_name);
1255 return ret;
1256 }
1257
1258 /*
1259 * relay_close_stream: close a specific stream
1260 */
1261 static int relay_close_stream(struct lttcomm_relayd_hdr *recv_hdr,
1262 struct relay_connection *conn)
1263 {
1264 int ret, send_ret;
1265 struct relay_session *session = conn->session;
1266 struct lttcomm_relayd_close_stream stream_info;
1267 struct lttcomm_relayd_generic_reply reply;
1268 struct relay_stream *stream;
1269
1270 DBG("Close stream received");
1271
1272 if (!session || conn->version_check_done == 0) {
1273 ERR("Trying to close a stream before version check");
1274 ret = -1;
1275 goto end_no_session;
1276 }
1277
1278 ret = conn->sock->ops->recvmsg(conn->sock, &stream_info,
1279 sizeof(struct lttcomm_relayd_close_stream), 0);
1280 if (ret < sizeof(struct lttcomm_relayd_close_stream)) {
1281 if (ret == 0) {
1282 /* Orderly shutdown. Not necessary to print an error. */
1283 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1284 } else {
1285 ERR("Relay didn't receive valid add_stream struct size : %d", ret);
1286 }
1287 ret = -1;
1288 goto end_no_session;
1289 }
1290
1291 stream = stream_get_by_id(be64toh(stream_info.stream_id));
1292 if (!stream) {
1293 ret = -1;
1294 goto end;
1295 }
1296
1297 /*
1298 * Set last_net_seq_num before the close flag. Required by data
1299 * pending check.
1300 */
1301 pthread_mutex_lock(&stream->lock);
1302 stream->last_net_seq_num = be64toh(stream_info.last_net_seq_num);
1303 pthread_mutex_unlock(&stream->lock);
1304
1305 /*
1306 * This is one of the conditions which may trigger a stream close
1307 * with the others being:
1308 * 1) A close command is received for a stream
1309 * 2) The control connection owning the stream is closed
1310 * 3) We have received all of the stream's data _after_ a close
1311 * request.
1312 */
1313 try_stream_close(stream);
1314 if (stream->is_metadata) {
1315 struct relay_viewer_stream *vstream;
1316
1317 vstream = viewer_stream_get_by_id(stream->stream_handle);
1318 if (vstream) {
1319 if (vstream->metadata_sent == stream->metadata_received) {
1320 /*
1321 * Since all the metadata has been sent to the
1322 * viewer and that we have a request to close
1323 * its stream, we can safely teardown the
1324 * corresponding metadata viewer stream.
1325 */
1326 viewer_stream_put(vstream);
1327 }
1328 /* Put local reference. */
1329 viewer_stream_put(vstream);
1330 }
1331 }
1332 stream_put(stream);
1333
1334 end:
1335 memset(&reply, 0, sizeof(reply));
1336 if (ret < 0) {
1337 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1338 } else {
1339 reply.ret_code = htobe32(LTTNG_OK);
1340 }
1341 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1342 sizeof(struct lttcomm_relayd_generic_reply), 0);
1343 if (send_ret < 0) {
1344 ERR("Relay sending stream id");
1345 ret = send_ret;
1346 }
1347
1348 end_no_session:
1349 return ret;
1350 }
1351
1352 /*
1353 * relay_reset_metadata: reset a metadata stream
1354 */
1355 static
1356 int relay_reset_metadata(struct lttcomm_relayd_hdr *recv_hdr,
1357 struct relay_connection *conn)
1358 {
1359 int ret, send_ret;
1360 struct relay_session *session = conn->session;
1361 struct lttcomm_relayd_reset_metadata stream_info;
1362 struct lttcomm_relayd_generic_reply reply;
1363 struct relay_stream *stream;
1364
1365 DBG("Reset metadata received");
1366
1367 if (!session || conn->version_check_done == 0) {
1368 ERR("Trying to reset a metadata stream before version check");
1369 ret = -1;
1370 goto end_no_session;
1371 }
1372
1373 ret = conn->sock->ops->recvmsg(conn->sock, &stream_info,
1374 sizeof(struct lttcomm_relayd_reset_metadata), 0);
1375 if (ret < sizeof(struct lttcomm_relayd_reset_metadata)) {
1376 if (ret == 0) {
1377 /* Orderly shutdown. Not necessary to print an error. */
1378 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1379 } else {
1380 ERR("Relay didn't receive valid reset_metadata struct "
1381 "size : %d", ret);
1382 }
1383 ret = -1;
1384 goto end_no_session;
1385 }
1386 DBG("Update metadata to version %" PRIu64, be64toh(stream_info.version));
1387
1388 /* Unsupported for live sessions for now. */
1389 if (session->live_timer != 0) {
1390 ret = -1;
1391 goto end;
1392 }
1393
1394 stream = stream_get_by_id(be64toh(stream_info.stream_id));
1395 if (!stream) {
1396 ret = -1;
1397 goto end;
1398 }
1399 pthread_mutex_lock(&stream->lock);
1400 if (!stream->is_metadata) {
1401 ret = -1;
1402 goto end_unlock;
1403 }
1404
1405 ret = utils_rotate_stream_file(stream->path_name, stream->channel_name,
1406 0, 0, -1, -1, stream->stream_fd->fd, NULL,
1407 &stream->stream_fd->fd);
1408 if (ret < 0) {
1409 ERR("Failed to rotate metadata file %s of channel %s",
1410 stream->path_name, stream->channel_name);
1411 goto end_unlock;
1412 }
1413
1414 end_unlock:
1415 pthread_mutex_unlock(&stream->lock);
1416 stream_put(stream);
1417
1418 end:
1419 memset(&reply, 0, sizeof(reply));
1420 if (ret < 0) {
1421 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1422 } else {
1423 reply.ret_code = htobe32(LTTNG_OK);
1424 }
1425 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1426 sizeof(struct lttcomm_relayd_generic_reply), 0);
1427 if (send_ret < 0) {
1428 ERR("Relay sending reset metadata reply");
1429 ret = send_ret;
1430 }
1431
1432 end_no_session:
1433 return ret;
1434 }
1435
1436 /*
1437 * relay_unknown_command: send -1 if received unknown command
1438 */
1439 static void relay_unknown_command(struct relay_connection *conn)
1440 {
1441 struct lttcomm_relayd_generic_reply reply;
1442 int ret;
1443
1444 memset(&reply, 0, sizeof(reply));
1445 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1446 ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1447 sizeof(struct lttcomm_relayd_generic_reply), 0);
1448 if (ret < 0) {
1449 ERR("Relay sending unknown command");
1450 }
1451 }
1452
1453 /*
1454 * relay_start: send an acknowledgment to the client to tell if we are
1455 * ready to receive data. We are ready if a session is established.
1456 */
1457 static int relay_start(struct lttcomm_relayd_hdr *recv_hdr,
1458 struct relay_connection *conn)
1459 {
1460 int ret = htobe32(LTTNG_OK);
1461 struct lttcomm_relayd_generic_reply reply;
1462 struct relay_session *session = conn->session;
1463
1464 if (!session) {
1465 DBG("Trying to start the streaming without a session established");
1466 ret = htobe32(LTTNG_ERR_UNK);
1467 }
1468
1469 memset(&reply, 0, sizeof(reply));
1470 reply.ret_code = ret;
1471 ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1472 sizeof(struct lttcomm_relayd_generic_reply), 0);
1473 if (ret < 0) {
1474 ERR("Relay sending start ack");
1475 }
1476
1477 return ret;
1478 }
1479
1480 /*
1481 * Append padding to the file pointed by the file descriptor fd.
1482 */
1483 static int write_padding_to_file(int fd, uint32_t size)
1484 {
1485 ssize_t ret = 0;
1486 char *zeros;
1487
1488 if (size == 0) {
1489 goto end;
1490 }
1491
1492 zeros = zmalloc(size);
1493 if (zeros == NULL) {
1494 PERROR("zmalloc zeros for padding");
1495 ret = -1;
1496 goto end;
1497 }
1498
1499 ret = lttng_write(fd, zeros, size);
1500 if (ret < size) {
1501 PERROR("write padding to file");
1502 }
1503
1504 free(zeros);
1505
1506 end:
1507 return ret;
1508 }
1509
1510 static
1511 int rotate_index_file(struct relay_stream *stream)
1512 {
1513 int ret;
1514 uint32_t major, minor;
1515
1516 /* Put ref on previous index_file. */
1517 if (stream->index_file) {
1518 lttng_index_file_put(stream->index_file);
1519 stream->index_file = NULL;
1520 }
1521 major = stream->trace->session->major;
1522 minor = stream->trace->session->minor;
1523 stream->index_file = lttng_index_file_create(stream->path_name,
1524 stream->channel_name,
1525 -1, -1, stream->tracefile_size,
1526 tracefile_array_get_file_index_head(stream->tfa),
1527 lttng_to_index_major(major, minor),
1528 lttng_to_index_minor(major, minor));
1529 if (!stream->index_file) {
1530 ret = -1;
1531 goto end;
1532 }
1533
1534 ret = 0;
1535
1536 end:
1537 return ret;
1538 }
1539
1540 static
1541 int do_rotate_stream(struct relay_stream *stream)
1542 {
1543 int ret;
1544
1545 /* Perform the stream rotation. */
1546 ret = utils_rotate_stream_file(stream->path_name,
1547 stream->channel_name, stream->tracefile_size,
1548 stream->tracefile_count, -1,
1549 -1, stream->stream_fd->fd,
1550 NULL, &stream->stream_fd->fd);
1551 if (ret < 0) {
1552 ERR("Rotating stream output file");
1553 goto end;
1554 }
1555 stream->tracefile_size_current = 0;
1556
1557 /* Rotate also the index if the stream is not a metadata stream. */
1558 if (!stream->is_metadata) {
1559 ret = rotate_index_file(stream);
1560 if (ret < 0) {
1561 ERR("Failed to rotate index file");
1562 goto end;
1563 }
1564 }
1565
1566 stream->rotate_at_seq_num = -1ULL;
1567 end:
1568 return ret;
1569 }
1570
1571 /*
1572 * Check if a stream should perform a rotation (for session rotation).
1573 * Must be called with the stream lock held.
1574 *
1575 * Return 0 on success, a negative value on error.
1576 */
1577 static
1578 int check_rotate_stream(struct relay_stream *stream)
1579 {
1580 int ret;
1581
1582 /* No rotation expected */
1583 if (stream->rotate_at_seq_num == -1ULL) {
1584 ret = 0;
1585 goto end;
1586 }
1587
1588 if (stream->prev_seq < stream->rotate_at_seq_num) {
1589 DBG("Stream %" PRIu64 " no yet ready for rotation",
1590 stream->stream_handle);
1591 fprintf(stderr, "Stream %" PRIu64 " no yet ready for rotation\n",
1592 stream->stream_handle);
1593 ret = 0;
1594 goto end;
1595 } else if (stream->prev_seq > stream->rotate_at_seq_num) {
1596 DBG("Rotation after too much data has been written in tracefile "
1597 "for stream %" PRIu64 ", need to truncate before "
1598 "rotating", stream->stream_handle);
1599 fprintf(stderr, "Rotation after too much data has been written in tracefile "
1600 "for stream %" PRIu64 ", need to truncate before "
1601 "rotating\n", stream->stream_handle);
1602 /* TODO */
1603 } else {
1604 DBG("Stream %" PRIu64 " ready for rotation", stream->stream_handle);
1605 fprintf(stderr, "Stream %" PRIu64 " ready for rotation\n", stream->stream_handle);
1606 }
1607
1608 ret = do_rotate_stream(stream);
1609
1610 end:
1611 return ret;
1612 }
1613
1614 /*
1615 * relay_recv_metadata: receive the metadata for the session.
1616 */
1617 static int relay_recv_metadata(struct lttcomm_relayd_hdr *recv_hdr,
1618 struct relay_connection *conn)
1619 {
1620 int ret = 0;
1621 ssize_t size_ret;
1622 struct relay_session *session = conn->session;
1623 struct lttcomm_relayd_metadata_payload *metadata_struct;
1624 struct relay_stream *metadata_stream;
1625 uint64_t data_size, payload_size;
1626
1627 if (!session) {
1628 ERR("Metadata sent before version check");
1629 ret = -1;
1630 goto end;
1631 }
1632
1633 data_size = payload_size = be64toh(recv_hdr->data_size);
1634 if (data_size < sizeof(struct lttcomm_relayd_metadata_payload)) {
1635 ERR("Incorrect data size");
1636 ret = -1;
1637 goto end;
1638 }
1639 payload_size -= sizeof(struct lttcomm_relayd_metadata_payload);
1640
1641 if (data_buffer_size < data_size) {
1642 /* In case the realloc fails, we can free the memory */
1643 char *tmp_data_ptr;
1644
1645 tmp_data_ptr = realloc(data_buffer, data_size);
1646 if (!tmp_data_ptr) {
1647 ERR("Allocating data buffer");
1648 free(data_buffer);
1649 ret = -1;
1650 goto end;
1651 }
1652 data_buffer = tmp_data_ptr;
1653 data_buffer_size = data_size;
1654 }
1655 memset(data_buffer, 0, data_size);
1656 DBG2("Relay receiving metadata, waiting for %" PRIu64 " bytes", data_size);
1657 size_ret = conn->sock->ops->recvmsg(conn->sock, data_buffer, data_size, 0);
1658 if (size_ret < 0 || size_ret != data_size) {
1659 if (size_ret == 0) {
1660 /* Orderly shutdown. Not necessary to print an error. */
1661 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1662 } else {
1663 ERR("Relay didn't receive the whole metadata");
1664 }
1665 ret = -1;
1666 goto end;
1667 }
1668 metadata_struct = (struct lttcomm_relayd_metadata_payload *) data_buffer;
1669
1670 metadata_stream = stream_get_by_id(be64toh(metadata_struct->stream_id));
1671 if (!metadata_stream) {
1672 ret = -1;
1673 goto end;
1674 }
1675
1676 pthread_mutex_lock(&metadata_stream->lock);
1677
1678 size_ret = lttng_write(metadata_stream->stream_fd->fd, metadata_struct->payload,
1679 payload_size);
1680 if (size_ret < payload_size) {
1681 ERR("Relay error writing metadata on file");
1682 ret = -1;
1683 goto end_put;
1684 }
1685
1686 size_ret = write_padding_to_file(metadata_stream->stream_fd->fd,
1687 be32toh(metadata_struct->padding_size));
1688 if (size_ret < 0) {
1689 goto end_put;
1690 }
1691
1692 metadata_stream->metadata_received +=
1693 payload_size + be32toh(metadata_struct->padding_size);
1694 DBG2("Relay metadata written. Updated metadata_received %" PRIu64,
1695 metadata_stream->metadata_received);
1696
1697 ret = check_rotate_stream(metadata_stream);
1698 if (ret < 0) {
1699 ERR("Check rotate stream");
1700 goto end_put;
1701 }
1702
1703 end_put:
1704 pthread_mutex_unlock(&metadata_stream->lock);
1705 stream_put(metadata_stream);
1706 end:
1707 return ret;
1708 }
1709
1710 /*
1711 * relay_send_version: send relayd version number
1712 */
1713 static int relay_send_version(struct lttcomm_relayd_hdr *recv_hdr,
1714 struct relay_connection *conn)
1715 {
1716 int ret;
1717 struct lttcomm_relayd_version reply, msg;
1718
1719 conn->version_check_done = 1;
1720
1721 /* Get version from the other side. */
1722 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
1723 if (ret < 0 || ret != sizeof(msg)) {
1724 if (ret == 0) {
1725 /* Orderly shutdown. Not necessary to print an error. */
1726 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1727 } else {
1728 ERR("Relay failed to receive the version values.");
1729 }
1730 ret = -1;
1731 goto end;
1732 }
1733
1734 memset(&reply, 0, sizeof(reply));
1735 reply.major = RELAYD_VERSION_COMM_MAJOR;
1736 reply.minor = RELAYD_VERSION_COMM_MINOR;
1737
1738 /* Major versions must be the same */
1739 if (reply.major != be32toh(msg.major)) {
1740 DBG("Incompatible major versions (%u vs %u), deleting session",
1741 reply.major, be32toh(msg.major));
1742 connection_put(conn);
1743 ret = 0;
1744 goto end;
1745 }
1746
1747 conn->major = reply.major;
1748 /* We adapt to the lowest compatible version */
1749 if (reply.minor <= be32toh(msg.minor)) {
1750 conn->minor = reply.minor;
1751 } else {
1752 conn->minor = be32toh(msg.minor);
1753 }
1754
1755 reply.major = htobe32(reply.major);
1756 reply.minor = htobe32(reply.minor);
1757 ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1758 sizeof(struct lttcomm_relayd_version), 0);
1759 if (ret < 0) {
1760 ERR("Relay sending version");
1761 }
1762
1763 DBG("Version check done using protocol %u.%u", conn->major,
1764 conn->minor);
1765
1766 end:
1767 return ret;
1768 }
1769
1770 /*
1771 * Check for data pending for a given stream id from the session daemon.
1772 */
1773 static int relay_data_pending(struct lttcomm_relayd_hdr *recv_hdr,
1774 struct relay_connection *conn)
1775 {
1776 struct relay_session *session = conn->session;
1777 struct lttcomm_relayd_data_pending msg;
1778 struct lttcomm_relayd_generic_reply reply;
1779 struct relay_stream *stream;
1780 int ret;
1781 uint64_t last_net_seq_num, stream_id;
1782
1783 DBG("Data pending command received");
1784
1785 if (!session || conn->version_check_done == 0) {
1786 ERR("Trying to check for data before version check");
1787 ret = -1;
1788 goto end_no_session;
1789 }
1790
1791 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
1792 if (ret < sizeof(msg)) {
1793 if (ret == 0) {
1794 /* Orderly shutdown. Not necessary to print an error. */
1795 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1796 } else {
1797 ERR("Relay didn't receive valid data_pending struct size : %d",
1798 ret);
1799 }
1800 ret = -1;
1801 goto end_no_session;
1802 }
1803
1804 stream_id = be64toh(msg.stream_id);
1805 last_net_seq_num = be64toh(msg.last_net_seq_num);
1806
1807 stream = stream_get_by_id(stream_id);
1808 if (stream == NULL) {
1809 ret = -1;
1810 goto end;
1811 }
1812
1813 pthread_mutex_lock(&stream->lock);
1814
1815 DBG("Data pending for stream id %" PRIu64 " prev_seq %" PRIu64
1816 " and last_seq %" PRIu64, stream_id, stream->prev_seq,
1817 last_net_seq_num);
1818
1819 /* Avoid wrapping issue */
1820 if (((int64_t) (stream->prev_seq - last_net_seq_num)) >= 0) {
1821 /* Data has in fact been written and is NOT pending */
1822 ret = 0;
1823 } else {
1824 /* Data still being streamed thus pending */
1825 ret = 1;
1826 }
1827
1828 stream->data_pending_check_done = true;
1829 pthread_mutex_unlock(&stream->lock);
1830
1831 stream_put(stream);
1832 end:
1833
1834 memset(&reply, 0, sizeof(reply));
1835 reply.ret_code = htobe32(ret);
1836 ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1837 if (ret < 0) {
1838 ERR("Relay data pending ret code failed");
1839 }
1840
1841 end_no_session:
1842 return ret;
1843 }
1844
1845 /*
1846 * Wait for the control socket to reach a quiescent state.
1847 *
1848 * Note that for now, when receiving this command from the session
1849 * daemon, this means that every subsequent commands or data received on
1850 * the control socket has been handled. So, this is why we simply return
1851 * OK here.
1852 */
1853 static int relay_quiescent_control(struct lttcomm_relayd_hdr *recv_hdr,
1854 struct relay_connection *conn)
1855 {
1856 int ret;
1857 uint64_t stream_id;
1858 struct relay_stream *stream;
1859 struct lttcomm_relayd_quiescent_control msg;
1860 struct lttcomm_relayd_generic_reply reply;
1861
1862 DBG("Checking quiescent state on control socket");
1863
1864 if (!conn->session || conn->version_check_done == 0) {
1865 ERR("Trying to check for data before version check");
1866 ret = -1;
1867 goto end_no_session;
1868 }
1869
1870 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
1871 if (ret < sizeof(msg)) {
1872 if (ret == 0) {
1873 /* Orderly shutdown. Not necessary to print an error. */
1874 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1875 } else {
1876 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1877 ret);
1878 }
1879 ret = -1;
1880 goto end_no_session;
1881 }
1882
1883 stream_id = be64toh(msg.stream_id);
1884 stream = stream_get_by_id(stream_id);
1885 if (!stream) {
1886 goto reply;
1887 }
1888 pthread_mutex_lock(&stream->lock);
1889 stream->data_pending_check_done = true;
1890 pthread_mutex_unlock(&stream->lock);
1891 DBG("Relay quiescent control pending flag set to %" PRIu64, stream_id);
1892 stream_put(stream);
1893 reply:
1894 memset(&reply, 0, sizeof(reply));
1895 reply.ret_code = htobe32(LTTNG_OK);
1896 ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1897 if (ret < 0) {
1898 ERR("Relay data quiescent control ret code failed");
1899 }
1900
1901 end_no_session:
1902 return ret;
1903 }
1904
1905 /*
1906 * Initialize a data pending command. This means that a consumer is about
1907 * to ask for data pending for each stream it holds. Simply iterate over
1908 * all streams of a session and set the data_pending_check_done flag.
1909 *
1910 * This command returns to the client a LTTNG_OK code.
1911 */
1912 static int relay_begin_data_pending(struct lttcomm_relayd_hdr *recv_hdr,
1913 struct relay_connection *conn)
1914 {
1915 int ret;
1916 struct lttng_ht_iter iter;
1917 struct lttcomm_relayd_begin_data_pending msg;
1918 struct lttcomm_relayd_generic_reply reply;
1919 struct relay_stream *stream;
1920 uint64_t session_id;
1921
1922 assert(recv_hdr);
1923 assert(conn);
1924
1925 DBG("Init streams for data pending");
1926
1927 if (!conn->session || conn->version_check_done == 0) {
1928 ERR("Trying to check for data before version check");
1929 ret = -1;
1930 goto end_no_session;
1931 }
1932
1933 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
1934 if (ret < sizeof(msg)) {
1935 if (ret == 0) {
1936 /* Orderly shutdown. Not necessary to print an error. */
1937 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1938 } else {
1939 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1940 ret);
1941 }
1942 ret = -1;
1943 goto end_no_session;
1944 }
1945
1946 session_id = be64toh(msg.session_id);
1947
1948 /*
1949 * Iterate over all streams to set the begin data pending flag.
1950 * For now, the streams are indexed by stream handle so we have
1951 * to iterate over all streams to find the one associated with
1952 * the right session_id.
1953 */
1954 rcu_read_lock();
1955 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
1956 node.node) {
1957 if (!stream_get(stream)) {
1958 continue;
1959 }
1960 if (stream->trace->session->id == session_id) {
1961 pthread_mutex_lock(&stream->lock);
1962 stream->data_pending_check_done = false;
1963 pthread_mutex_unlock(&stream->lock);
1964 DBG("Set begin data pending flag to stream %" PRIu64,
1965 stream->stream_handle);
1966 }
1967 stream_put(stream);
1968 }
1969 rcu_read_unlock();
1970
1971 memset(&reply, 0, sizeof(reply));
1972 /* All good, send back reply. */
1973 reply.ret_code = htobe32(LTTNG_OK);
1974
1975 ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1976 if (ret < 0) {
1977 ERR("Relay begin data pending send reply failed");
1978 }
1979
1980 end_no_session:
1981 return ret;
1982 }
1983
1984 /*
1985 * End data pending command. This will check, for a given session id, if
1986 * each stream associated with it has its data_pending_check_done flag
1987 * set. If not, this means that the client lost track of the stream but
1988 * the data is still being streamed on our side. In this case, we inform
1989 * the client that data is in flight.
1990 *
1991 * Return to the client if there is data in flight or not with a ret_code.
1992 */
1993 static int relay_end_data_pending(struct lttcomm_relayd_hdr *recv_hdr,
1994 struct relay_connection *conn)
1995 {
1996 int ret;
1997 struct lttng_ht_iter iter;
1998 struct lttcomm_relayd_end_data_pending msg;
1999 struct lttcomm_relayd_generic_reply reply;
2000 struct relay_stream *stream;
2001 uint64_t session_id;
2002 uint32_t is_data_inflight = 0;
2003
2004 DBG("End data pending command");
2005
2006 if (!conn->session || conn->version_check_done == 0) {
2007 ERR("Trying to check for data before version check");
2008 ret = -1;
2009 goto end_no_session;
2010 }
2011
2012 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
2013 if (ret < sizeof(msg)) {
2014 if (ret == 0) {
2015 /* Orderly shutdown. Not necessary to print an error. */
2016 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
2017 } else {
2018 ERR("Relay didn't receive valid end data_pending struct size: %d",
2019 ret);
2020 }
2021 ret = -1;
2022 goto end_no_session;
2023 }
2024
2025 session_id = be64toh(msg.session_id);
2026
2027 /*
2028 * Iterate over all streams to see if the begin data pending
2029 * flag is set.
2030 */
2031 rcu_read_lock();
2032 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2033 node.node) {
2034 if (!stream_get(stream)) {
2035 continue;
2036 }
2037 if (stream->trace->session->id != session_id) {
2038 stream_put(stream);
2039 continue;
2040 }
2041 pthread_mutex_lock(&stream->lock);
2042 if (!stream->data_pending_check_done) {
2043 if (!stream->closed || !(((int64_t) (stream->prev_seq - stream->last_net_seq_num)) >= 0)) {
2044 is_data_inflight = 1;
2045 DBG("Data is still in flight for stream %" PRIu64,
2046 stream->stream_handle);
2047 pthread_mutex_unlock(&stream->lock);
2048 stream_put(stream);
2049 break;
2050 }
2051 }
2052 pthread_mutex_unlock(&stream->lock);
2053 stream_put(stream);
2054 }
2055 rcu_read_unlock();
2056
2057 memset(&reply, 0, sizeof(reply));
2058 /* All good, send back reply. */
2059 reply.ret_code = htobe32(is_data_inflight);
2060
2061 ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2062 if (ret < 0) {
2063 ERR("Relay end data pending send reply failed");
2064 }
2065
2066 end_no_session:
2067 return ret;
2068 }
2069
2070 /*
2071 * Receive an index for a specific stream.
2072 *
2073 * Return 0 on success else a negative value.
2074 */
2075 static int relay_recv_index(struct lttcomm_relayd_hdr *recv_hdr,
2076 struct relay_connection *conn)
2077 {
2078 int ret, send_ret;
2079 struct relay_session *session = conn->session;
2080 struct lttcomm_relayd_index index_info;
2081 struct relay_index *index;
2082 struct lttcomm_relayd_generic_reply reply;
2083 struct relay_stream *stream;
2084 uint64_t net_seq_num;
2085 size_t msg_len;
2086
2087 assert(conn);
2088
2089 DBG("Relay receiving index");
2090
2091 if (!session || conn->version_check_done == 0) {
2092 ERR("Trying to close a stream before version check");
2093 ret = -1;
2094 goto end_no_session;
2095 }
2096
2097 msg_len = lttcomm_relayd_index_len(
2098 lttng_to_index_major(conn->major, conn->minor),
2099 lttng_to_index_minor(conn->major, conn->minor));
2100 ret = conn->sock->ops->recvmsg(conn->sock, &index_info,
2101 msg_len, 0);
2102 if (ret < msg_len) {
2103 if (ret == 0) {
2104 /* Orderly shutdown. Not necessary to print an error. */
2105 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
2106 } else {
2107 ERR("Relay didn't receive valid index struct size : %d", ret);
2108 }
2109 ret = -1;
2110 goto end_no_session;
2111 }
2112
2113 net_seq_num = be64toh(index_info.net_seq_num);
2114
2115 stream = stream_get_by_id(be64toh(index_info.relay_stream_id));
2116 if (!stream) {
2117 ERR("stream_get_by_id not found");
2118 ret = -1;
2119 goto end;
2120 }
2121 pthread_mutex_lock(&stream->lock);
2122
2123 /* Live beacon handling */
2124 if (index_info.packet_size == 0) {
2125 DBG("Received live beacon for stream %" PRIu64,
2126 stream->stream_handle);
2127
2128 /*
2129 * Only flag a stream inactive when it has already
2130 * received data and no indexes are in flight.
2131 */
2132 if (stream->index_received_seqcount > 0
2133 && stream->indexes_in_flight == 0) {
2134 stream->beacon_ts_end =
2135 be64toh(index_info.timestamp_end);
2136 }
2137 ret = 0;
2138 goto end_stream_put;
2139 } else {
2140 stream->beacon_ts_end = -1ULL;
2141 }
2142
2143 if (stream->ctf_stream_id == -1ULL) {
2144 stream->ctf_stream_id = be64toh(index_info.stream_id);
2145 }
2146 index = relay_index_get_by_id_or_create(stream, net_seq_num);
2147 if (!index) {
2148 ret = -1;
2149 ERR("relay_index_get_by_id_or_create index NULL");
2150 goto end_stream_put;
2151 }
2152 if (set_index_control_data(index, &index_info, conn)) {
2153 ERR("set_index_control_data error");
2154 relay_index_put(index);
2155 ret = -1;
2156 goto end_stream_put;
2157 }
2158 ret = relay_index_try_flush(index);
2159 if (ret == 0) {
2160 tracefile_array_commit_seq(stream->tfa);
2161 stream->index_received_seqcount++;
2162 } else if (ret > 0) {
2163 /* no flush. */
2164 ret = 0;
2165 } else {
2166 ERR("relay_index_try_flush error %d", ret);
2167 relay_index_put(index);
2168 ret = -1;
2169 }
2170
2171 end_stream_put:
2172 pthread_mutex_unlock(&stream->lock);
2173 stream_put(stream);
2174
2175 end:
2176
2177 memset(&reply, 0, sizeof(reply));
2178 if (ret < 0) {
2179 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2180 } else {
2181 reply.ret_code = htobe32(LTTNG_OK);
2182 }
2183 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2184 if (send_ret < 0) {
2185 ERR("Relay sending close index id reply");
2186 ret = send_ret;
2187 }
2188
2189 end_no_session:
2190 return ret;
2191 }
2192
2193 /*
2194 * Receive the streams_sent message.
2195 *
2196 * Return 0 on success else a negative value.
2197 */
2198 static int relay_streams_sent(struct lttcomm_relayd_hdr *recv_hdr,
2199 struct relay_connection *conn)
2200 {
2201 int ret, send_ret;
2202 struct lttcomm_relayd_generic_reply reply;
2203
2204 assert(conn);
2205
2206 DBG("Relay receiving streams_sent");
2207
2208 if (!conn->session || conn->version_check_done == 0) {
2209 ERR("Trying to close a stream before version check");
2210 ret = -1;
2211 goto end_no_session;
2212 }
2213
2214 /*
2215 * Publish every pending stream in the connection recv list which are
2216 * now ready to be used by the viewer.
2217 */
2218 publish_connection_local_streams(conn);
2219
2220 memset(&reply, 0, sizeof(reply));
2221 reply.ret_code = htobe32(LTTNG_OK);
2222 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2223 if (send_ret < 0) {
2224 ERR("Relay sending sent_stream reply");
2225 ret = send_ret;
2226 } else {
2227 /* Success. */
2228 ret = 0;
2229 }
2230
2231 end_no_session:
2232 return ret;
2233 }
2234
2235 /*
2236 * relay_rotate_stream: rotate a stream to a new tracefile for the session
2237 * rotation feature (not the tracefile rotation feature).
2238 */
2239 static int relay_rotate_session_stream(struct lttcomm_relayd_hdr *recv_hdr,
2240 struct relay_connection *conn)
2241 {
2242 int ret, send_ret;
2243 struct relay_session *session = conn->session;
2244 struct lttcomm_relayd_rotate_stream stream_info;
2245 struct lttcomm_relayd_generic_reply reply;
2246 struct relay_stream *stream;
2247 size_t len;
2248
2249 DBG("Rotate stream received");
2250
2251 if (!session || conn->version_check_done == 0) {
2252 ERR("Trying to rotate a stream before version check");
2253 ret = -1;
2254 goto end_no_session;
2255 }
2256
2257 if (session->minor < 11) {
2258 ERR("Unsupported feature before 2.11");
2259 ret = -1;
2260 goto end_no_session;
2261 }
2262
2263 ret = conn->sock->ops->recvmsg(conn->sock, &stream_info,
2264 sizeof(stream_info), 0);
2265 if (ret < sizeof(stream_info)) {
2266 if (ret == 0) {
2267 /* Orderly shutdown. Not necessary to print an error. */
2268 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
2269 } else {
2270 ERR("Relay didn't receive valid rotate_stream struct size : %d", ret);
2271 }
2272 ret = -1;
2273 goto end_no_session;
2274 }
2275
2276 stream = stream_get_by_id(be64toh(stream_info.stream_id));
2277 if (!stream) {
2278 ret = -1;
2279 goto end;
2280 }
2281
2282 len = lttng_strnlen(stream_info.new_pathname,
2283 sizeof(stream_info.new_pathname));
2284 /* Ensure that NULL-terminated and fits in local filename length. */
2285 if (len == sizeof(stream_info.new_pathname) || len >= LTTNG_NAME_MAX) {
2286 ret = -ENAMETOOLONG;
2287 ERR("Path name too long");
2288 goto end;
2289 }
2290
2291 pthread_mutex_lock(&stream->lock);
2292
2293 /* Update the trace path (just the folder, the stream name does not change). */
2294 free(stream->path_name);
2295 stream->path_name = create_output_path(stream_info.new_pathname);
2296 if (!stream->path_name) {
2297 ERR("Failed to create a new output path");
2298 goto end_stream_unlock;
2299 }
2300 ret = utils_mkdir_recursive(stream->path_name, S_IRWXU | S_IRWXG,
2301 -1, -1);
2302 if (ret < 0) {
2303 ERR("relay creating output directory");
2304 goto end;
2305 }
2306 stream->chunk_id = be64toh(stream_info.new_chunk_id);
2307
2308 if (stream->is_metadata) {
2309 /*
2310 * The metadata stream is sent only over the control connection
2311 * so we know we have all the data to perform the stream
2312 * rotation.
2313 */
2314 ret = do_rotate_stream(stream);
2315 } else {
2316 stream->rotate_at_seq_num = be64toh(stream_info.rotate_at_seq_num);
2317 ret = check_rotate_stream(stream);
2318 }
2319 if (ret < 0) {
2320 ERR("Check rotate stream");
2321 goto end_stream_unlock;
2322 }
2323
2324 end_stream_unlock:
2325 pthread_mutex_unlock(&stream->lock);
2326 stream_put(stream);
2327 end:
2328 memset(&reply, 0, sizeof(reply));
2329 if (ret < 0) {
2330 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2331 } else {
2332 reply.ret_code = htobe32(LTTNG_OK);
2333 }
2334 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
2335 sizeof(struct lttcomm_relayd_generic_reply), 0);
2336 if (send_ret < 0) {
2337 ERR("Relay sending stream id");
2338 ret = send_ret;
2339 }
2340
2341 end_no_session:
2342 return ret;
2343 }
2344
2345 /*
2346 * relay_rotate_rename: rename the trace folder after the rotation is
2347 * complete. We are not closing any fd here, just moving the folder, so it
2348 * works even if data is still in flight.
2349 */
2350 static int relay_rotate_rename(struct lttcomm_relayd_hdr *recv_hdr,
2351 struct relay_connection *conn)
2352 {
2353 int ret, send_ret;
2354 struct relay_session *session = conn->session;
2355 struct lttcomm_relayd_rotate_rename stream_info;
2356 struct lttcomm_relayd_generic_reply reply;
2357 size_t len;
2358 char *old = NULL, *new = NULL;
2359
2360 DBG("Rotate rename received");
2361
2362 if (!session || conn->version_check_done == 0) {
2363 ERR("Trying to rename before version check");
2364 ret = -1;
2365 goto end_no_session;
2366 }
2367
2368 if (session->minor < 11) {
2369 ERR("Unsupported feature before 2.11");
2370 ret = -1;
2371 goto end_no_session;
2372 }
2373
2374 ret = conn->sock->ops->recvmsg(conn->sock, &stream_info,
2375 sizeof(stream_info), 0);
2376 if (ret < sizeof(stream_info)) {
2377 if (ret == 0) {
2378 /* Orderly shutdown. Not necessary to print an error. */
2379 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
2380 } else {
2381 ERR("Relay didn't receive valid rotate_rename struct size : %d", ret);
2382 }
2383 ret = -1;
2384 goto end_no_session;
2385 }
2386
2387 len = lttng_strnlen(stream_info.current_path,
2388 sizeof(stream_info.current_path));
2389 /* Ensure that NULL-terminated and fits in local filename length. */
2390 if (len == sizeof(stream_info.current_path) || len >= LTTNG_NAME_MAX) {
2391 ret = -ENAMETOOLONG;
2392 ERR("Path name too long");
2393 goto end;
2394 }
2395
2396 len = lttng_strnlen(stream_info.new_path,
2397 sizeof(stream_info.new_path));
2398 /* Ensure that NULL-terminated and fits in local filename length. */
2399 if (len == sizeof(stream_info.new_path) || len >= LTTNG_NAME_MAX) {
2400 ret = -ENAMETOOLONG;
2401 ERR("Path name too long");
2402 goto end;
2403 }
2404
2405 fprintf(stderr, "Renaming %s to %s/\n", stream_info.current_path,
2406 stream_info.new_path);
2407
2408 old = create_output_path(stream_info.current_path);
2409 if (!old) {
2410 ERR("Failed to create current output path");
2411 ret = -1;
2412 goto end;
2413 }
2414
2415 new = create_output_path(stream_info.new_path);
2416 if (!new) {
2417 ERR("Failed to create new output path");
2418 ret = -1;
2419 goto end;
2420 }
2421
2422 ret = utils_mkdir_recursive(new, S_IRWXU | S_IRWXG,
2423 -1, -1);
2424 if (ret < 0) {
2425 ERR("relay creating output directory");
2426 goto end;
2427 }
2428
2429 ret = rename(old, new);
2430 if (ret < 0 && errno != ENOENT) {
2431 PERROR("Rename completed rotation chunk");
2432 goto end;
2433 }
2434
2435 end:
2436 memset(&reply, 0, sizeof(reply));
2437 if (ret < 0) {
2438 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2439 } else {
2440 reply.ret_code = htobe32(LTTNG_OK);
2441 }
2442 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
2443 sizeof(struct lttcomm_relayd_generic_reply), 0);
2444 if (send_ret < 0) {
2445 ERR("Relay sending stream id");
2446 ret = send_ret;
2447 }
2448
2449 end_no_session:
2450 free(old);
2451 free(new);
2452 return ret;
2453 }
2454
2455 static
2456 int relay_rotate_pending(struct lttcomm_relayd_hdr *recv_hdr,
2457 struct relay_connection *conn)
2458 {
2459 struct relay_session *session = conn->session;
2460 struct lttcomm_relayd_rotate_pending msg;
2461 struct lttcomm_relayd_generic_reply reply;
2462 struct lttng_ht_iter iter;
2463 struct relay_stream *stream;
2464 int ret;
2465 uint64_t chunk_id;
2466 uint32_t rotate_pending;
2467
2468 DBG("Rotate pending command received");
2469 fprintf(stderr, "Rotate pending command received\n");
2470
2471 if (!session || conn->version_check_done == 0) {
2472 ERR("Trying to check for data before version check");
2473 ret = -1;
2474 goto end_no_session;
2475 }
2476
2477 if (session->minor < 11) {
2478 ERR("Unsupported feature before 2.11");
2479 ret = -1;
2480 goto end_no_session;
2481 }
2482
2483 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
2484 if (ret < sizeof(msg)) {
2485 if (ret == 0) {
2486 /* Orderly shutdown. Not necessary to print an error. */
2487 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
2488 } else {
2489 ERR("Relay didn't receive valid rotate_pending struct size : %d",
2490 ret);
2491 }
2492 ret = -1;
2493 goto end_no_session;
2494 }
2495
2496 chunk_id = be64toh(msg.chunk_id);
2497
2498 rotate_pending = 0;
2499
2500 rcu_read_lock();
2501 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2502 node.node) {
2503 if (!stream_get(stream)) {
2504 continue;
2505 }
2506 if (stream->trace->session != session) {
2507 stream_put(stream);
2508 continue;
2509 }
2510 pthread_mutex_lock(&stream->lock);
2511 if (stream->rotate_at_seq_num != -1ULL) {
2512 rotate_pending = 1;
2513 DBG("Stream %" PRIu64 " is still rotating",
2514 stream->stream_handle);
2515 } else if (stream->chunk_id < chunk_id) {
2516 rotate_pending = 1;
2517 DBG("Stream %" PRIu64 " did not exist on the consumer "
2518 "when the last rotation started, but is"
2519 "still waiting for data before getting"
2520 "closed",
2521 stream->stream_handle);
2522 }
2523 pthread_mutex_unlock(&stream->lock);
2524 stream_put(stream);
2525 if (rotate_pending) {
2526 goto send_reply;
2527 }
2528 }
2529 rcu_read_unlock();
2530
2531 send_reply:
2532 memset(&reply, 0, sizeof(reply));
2533 reply.ret_code = htobe32(rotate_pending);
2534 ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2535 if (ret < 0) {
2536 ERR("Relay rotate pending ret code failed");
2537 }
2538
2539 end_no_session:
2540 return ret;
2541 }
2542
2543 /*
2544 * Process the commands received on the control socket
2545 */
2546 static int relay_process_control(struct lttcomm_relayd_hdr *recv_hdr,
2547 struct relay_connection *conn)
2548 {
2549 int ret = 0;
2550
2551 switch (be32toh(recv_hdr->cmd)) {
2552 case RELAYD_CREATE_SESSION:
2553 ret = relay_create_session(recv_hdr, conn);
2554 break;
2555 case RELAYD_ADD_STREAM:
2556 ret = relay_add_stream(recv_hdr, conn);
2557 break;
2558 case RELAYD_START_DATA:
2559 ret = relay_start(recv_hdr, conn);
2560 break;
2561 case RELAYD_SEND_METADATA:
2562 ret = relay_recv_metadata(recv_hdr, conn);
2563 break;
2564 case RELAYD_VERSION:
2565 ret = relay_send_version(recv_hdr, conn);
2566 break;
2567 case RELAYD_CLOSE_STREAM:
2568 ret = relay_close_stream(recv_hdr, conn);
2569 break;
2570 case RELAYD_DATA_PENDING:
2571 ret = relay_data_pending(recv_hdr, conn);
2572 break;
2573 case RELAYD_QUIESCENT_CONTROL:
2574 ret = relay_quiescent_control(recv_hdr, conn);
2575 break;
2576 case RELAYD_BEGIN_DATA_PENDING:
2577 ret = relay_begin_data_pending(recv_hdr, conn);
2578 break;
2579 case RELAYD_END_DATA_PENDING:
2580 ret = relay_end_data_pending(recv_hdr, conn);
2581 break;
2582 case RELAYD_SEND_INDEX:
2583 ret = relay_recv_index(recv_hdr, conn);
2584 break;
2585 case RELAYD_STREAMS_SENT:
2586 ret = relay_streams_sent(recv_hdr, conn);
2587 break;
2588 case RELAYD_RESET_METADATA:
2589 ret = relay_reset_metadata(recv_hdr, conn);
2590 break;
2591 case RELAYD_ROTATE_STREAM:
2592 ret = relay_rotate_session_stream(recv_hdr, conn);
2593 break;
2594 case RELAYD_ROTATE_RENAME:
2595 ret = relay_rotate_rename(recv_hdr, conn);
2596 break;
2597 case RELAYD_ROTATE_PENDING:
2598 ret = relay_rotate_pending(recv_hdr, conn);
2599 break;
2600 case RELAYD_UPDATE_SYNC_INFO:
2601 default:
2602 ERR("Received unknown command (%u)", be32toh(recv_hdr->cmd));
2603 relay_unknown_command(conn);
2604 ret = -1;
2605 goto end;
2606 }
2607
2608 end:
2609 return ret;
2610 }
2611
2612 /*
2613 * Handle index for a data stream.
2614 *
2615 * Called with the stream lock held.
2616 *
2617 * Return 0 on success else a negative value.
2618 */
2619 static int handle_index_data(struct relay_stream *stream, uint64_t net_seq_num,
2620 int rotate_index)
2621 {
2622 int ret = 0;
2623 uint64_t data_offset;
2624 struct relay_index *index;
2625
2626 /* Get data offset because we are about to update the index. */
2627 data_offset = htobe64(stream->tracefile_size_current);
2628
2629 DBG("handle_index_data: stream %" PRIu64 " net_seq_num %" PRIu64 " data offset %" PRIu64,
2630 stream->stream_handle, net_seq_num, stream->tracefile_size_current);
2631
2632 /*
2633 * Lookup for an existing index for that stream id/sequence
2634 * number. If it exists, the control thread has already received the
2635 * data for it, thus we need to write it to disk.
2636 */
2637 index = relay_index_get_by_id_or_create(stream, net_seq_num);
2638 if (!index) {
2639 ret = -1;
2640 goto end;
2641 }
2642
2643 if (rotate_index || !stream->index_file) {
2644 ret = rotate_index_file(stream);
2645 if (ret < 0) {
2646 ERR("Failed to rotate index");
2647 /* Put self-ref for this index due to error. */
2648 relay_index_put(index);
2649 index = NULL;
2650 goto end;
2651 }
2652 }
2653
2654 if (relay_index_set_file(index, stream->index_file, data_offset)) {
2655 ret = -1;
2656 /* Put self-ref for this index due to error. */
2657 relay_index_put(index);
2658 index = NULL;
2659 goto end;
2660 }
2661
2662 ret = relay_index_try_flush(index);
2663 if (ret == 0) {
2664 tracefile_array_commit_seq(stream->tfa);
2665 stream->index_received_seqcount++;
2666 } else if (ret > 0) {
2667 /* No flush. */
2668 ret = 0;
2669 } else {
2670 /* Put self-ref for this index due to error. */
2671 relay_index_put(index);
2672 index = NULL;
2673 ret = -1;
2674 }
2675 end:
2676 return ret;
2677 }
2678
2679 /*
2680 * relay_process_data: Process the data received on the data socket
2681 */
2682 static int relay_process_data(struct relay_connection *conn)
2683 {
2684 int ret = 0, rotate_index = 0;
2685 ssize_t size_ret;
2686 struct relay_stream *stream;
2687 struct lttcomm_relayd_data_hdr data_hdr;
2688 uint64_t stream_id;
2689 uint64_t net_seq_num;
2690 uint32_t data_size;
2691 struct relay_session *session;
2692 bool new_stream = false, close_requested = false;
2693 size_t chunk_size = RECV_DATA_BUFFER_SIZE;
2694 size_t recv_off = 0;
2695 char data_buffer[chunk_size];
2696
2697 ret = conn->sock->ops->recvmsg(conn->sock, &data_hdr,
2698 sizeof(struct lttcomm_relayd_data_hdr), 0);
2699 if (ret <= 0) {
2700 if (ret == 0) {
2701 /* Orderly shutdown. Not necessary to print an error. */
2702 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
2703 } else {
2704 ERR("Unable to receive data header on sock %d", conn->sock->fd);
2705 }
2706 ret = -1;
2707 goto end;
2708 }
2709
2710 stream_id = be64toh(data_hdr.stream_id);
2711 stream = stream_get_by_id(stream_id);
2712 if (!stream) {
2713 ERR("relay_process_data: Cannot find stream %" PRIu64, stream_id);
2714 ret = -1;
2715 goto end;
2716 }
2717 session = stream->trace->session;
2718 data_size = be32toh(data_hdr.data_size);
2719
2720 net_seq_num = be64toh(data_hdr.net_seq_num);
2721
2722 DBG3("Receiving data of size %u for stream id %" PRIu64 " seqnum %" PRIu64,
2723 data_size, stream_id, net_seq_num);
2724
2725 pthread_mutex_lock(&stream->lock);
2726
2727 /* Check if a rotation is needed. */
2728 if (stream->tracefile_size > 0 &&
2729 (stream->tracefile_size_current + data_size) >
2730 stream->tracefile_size) {
2731 uint64_t old_id, new_id;
2732
2733 old_id = tracefile_array_get_file_index_head(stream->tfa);
2734 tracefile_array_file_rotate(stream->tfa);
2735
2736 /* new_id is updated by utils_rotate_stream_file. */
2737 new_id = old_id;
2738
2739 ret = utils_rotate_stream_file(stream->path_name,
2740 stream->channel_name, stream->tracefile_size,
2741 stream->tracefile_count, -1,
2742 -1, stream->stream_fd->fd,
2743 &new_id, &stream->stream_fd->fd);
2744 if (ret < 0) {
2745 ERR("Rotating stream output file");
2746 goto end_stream_unlock;
2747 }
2748 /*
2749 * Reset current size because we just performed a stream
2750 * rotation.
2751 */
2752 stream->tracefile_size_current = 0;
2753 rotate_index = 1;
2754 }
2755
2756 /*
2757 * Index are handled in protocol version 2.4 and above. Also,
2758 * snapshot and index are NOT supported.
2759 */
2760 if (session->minor >= 4 && !session->snapshot) {
2761 ret = handle_index_data(stream, net_seq_num, rotate_index);
2762 if (ret < 0) {
2763 ERR("handle_index_data: fail stream %" PRIu64 " net_seq_num %" PRIu64 " ret %d",
2764 stream->stream_handle, net_seq_num, ret);
2765 goto end_stream_unlock;
2766 }
2767 }
2768
2769 for (recv_off = 0; recv_off < data_size; recv_off += chunk_size) {
2770 size_t recv_size = min(data_size - recv_off, chunk_size);
2771
2772 ret = conn->sock->ops->recvmsg(conn->sock, data_buffer, recv_size, 0);
2773 if (ret <= 0) {
2774 if (ret == 0) {
2775 /* Orderly shutdown. Not necessary to print an error. */
2776 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
2777 } else {
2778 ERR("Socket %d error %d", conn->sock->fd, ret);
2779 }
2780 ret = -1;
2781 goto end_stream_unlock;
2782 }
2783
2784 /* Write data to stream output fd. */
2785 size_ret = lttng_write(stream->stream_fd->fd, data_buffer,
2786 recv_size);
2787 if (size_ret < recv_size) {
2788 ERR("Relay error writing data to file");
2789 ret = -1;
2790 goto end_stream_unlock;
2791 }
2792
2793 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64,
2794 size_ret, stream->stream_handle);
2795 }
2796
2797 ret = write_padding_to_file(stream->stream_fd->fd,
2798 be32toh(data_hdr.padding_size));
2799 if (ret < 0) {
2800 ERR("write_padding_to_file: fail stream %" PRIu64 " net_seq_num %" PRIu64 " ret %d",
2801 stream->stream_handle, net_seq_num, ret);
2802 goto end_stream_unlock;
2803 }
2804 stream->tracefile_size_current +=
2805 data_size + be32toh(data_hdr.padding_size);
2806 if (stream->prev_seq == -1ULL) {
2807 new_stream = true;
2808 }
2809
2810 stream->prev_seq = net_seq_num;
2811
2812 ret = check_rotate_stream(stream);
2813 if (ret < 0) {
2814 ERR("Check rotate stream");
2815 goto end_stream_unlock;
2816 }
2817
2818 end_stream_unlock:
2819 close_requested = stream->close_requested;
2820 pthread_mutex_unlock(&stream->lock);
2821 if (close_requested) {
2822 try_stream_close(stream);
2823 }
2824
2825 if (new_stream) {
2826 pthread_mutex_lock(&session->lock);
2827 uatomic_set(&session->new_streams, 1);
2828 pthread_mutex_unlock(&session->lock);
2829 }
2830 stream_put(stream);
2831 end:
2832 return ret;
2833 }
2834
2835 static void cleanup_connection_pollfd(struct lttng_poll_event *events, int pollfd)
2836 {
2837 int ret;
2838
2839 (void) lttng_poll_del(events, pollfd);
2840
2841 ret = close(pollfd);
2842 if (ret < 0) {
2843 ERR("Closing pollfd %d", pollfd);
2844 }
2845 }
2846
2847 static void relay_thread_close_connection(struct lttng_poll_event *events,
2848 int pollfd, struct relay_connection *conn)
2849 {
2850 const char *type_str;
2851
2852 switch (conn->type) {
2853 case RELAY_DATA:
2854 type_str = "Data";
2855 break;
2856 case RELAY_CONTROL:
2857 type_str = "Control";
2858 break;
2859 case RELAY_VIEWER_COMMAND:
2860 type_str = "Viewer Command";
2861 break;
2862 case RELAY_VIEWER_NOTIFICATION:
2863 type_str = "Viewer Notification";
2864 break;
2865 default:
2866 type_str = "Unknown";
2867 }
2868 cleanup_connection_pollfd(events, pollfd);
2869 connection_put(conn);
2870 DBG("%s connection closed with %d", type_str, pollfd);
2871 }
2872
2873 /*
2874 * This thread does the actual work
2875 */
2876 static void *relay_thread_worker(void *data)
2877 {
2878 int ret, err = -1, last_seen_data_fd = -1;
2879 uint32_t nb_fd;
2880 struct lttng_poll_event events;
2881 struct lttng_ht *relay_connections_ht;
2882 struct lttng_ht_iter iter;
2883 struct lttcomm_relayd_hdr recv_hdr;
2884 struct relay_connection *destroy_conn = NULL;
2885
2886 DBG("[thread] Relay worker started");
2887
2888 rcu_register_thread();
2889
2890 health_register(health_relayd, HEALTH_RELAYD_TYPE_WORKER);
2891
2892 if (testpoint(relayd_thread_worker)) {
2893 goto error_testpoint;
2894 }
2895
2896 health_code_update();
2897
2898 /* table of connections indexed on socket */
2899 relay_connections_ht = lttng_ht_new(0, LTTNG_HT_TYPE_ULONG);
2900 if (!relay_connections_ht) {
2901 goto relay_connections_ht_error;
2902 }
2903
2904 ret = create_thread_poll_set(&events, 2);
2905 if (ret < 0) {
2906 goto error_poll_create;
2907 }
2908
2909 ret = lttng_poll_add(&events, relay_conn_pipe[0], LPOLLIN | LPOLLRDHUP);
2910 if (ret < 0) {
2911 goto error;
2912 }
2913
2914 restart:
2915 while (1) {
2916 int idx = -1, i, seen_control = 0, last_notdel_data_fd = -1;
2917
2918 health_code_update();
2919
2920 /* Infinite blocking call, waiting for transmission */
2921 DBG3("Relayd worker thread polling...");
2922 health_poll_entry();
2923 ret = lttng_poll_wait(&events, -1);
2924 health_poll_exit();
2925 if (ret < 0) {
2926 /*
2927 * Restart interrupted system call.
2928 */
2929 if (errno == EINTR) {
2930 goto restart;
2931 }
2932 goto error;
2933 }
2934
2935 nb_fd = ret;
2936
2937 /*
2938 * Process control. The control connection is
2939 * prioritized so we don't starve it with high
2940 * throughput tracing data on the data connection.
2941 */
2942 for (i = 0; i < nb_fd; i++) {
2943 /* Fetch once the poll data */
2944 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
2945 int pollfd = LTTNG_POLL_GETFD(&events, i);
2946
2947 health_code_update();
2948
2949 if (!revents) {
2950 /*
2951 * No activity for this FD (poll
2952 * implementation).
2953 */
2954 continue;
2955 }
2956
2957 /* Thread quit pipe has been closed. Killing thread. */
2958 ret = check_thread_quit_pipe(pollfd, revents);
2959 if (ret) {
2960 err = 0;
2961 goto exit;
2962 }
2963
2964 /* Inspect the relay conn pipe for new connection */
2965 if (pollfd == relay_conn_pipe[0]) {
2966 if (revents & LPOLLIN) {
2967 struct relay_connection *conn;
2968
2969 ret = lttng_read(relay_conn_pipe[0], &conn, sizeof(conn));
2970 if (ret < 0) {
2971 goto error;
2972 }
2973 lttng_poll_add(&events, conn->sock->fd,
2974 LPOLLIN | LPOLLRDHUP);
2975 connection_ht_add(relay_connections_ht, conn);
2976 DBG("Connection socket %d added", conn->sock->fd);
2977 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2978 ERR("Relay connection pipe error");
2979 goto error;
2980 } else {
2981 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
2982 goto error;
2983 }
2984 } else {
2985 struct relay_connection *ctrl_conn;
2986
2987 ctrl_conn = connection_get_by_sock(relay_connections_ht, pollfd);
2988 /* If not found, there is a synchronization issue. */
2989 assert(ctrl_conn);
2990
2991 if (ctrl_conn->type == RELAY_DATA) {
2992 if (revents & LPOLLIN) {
2993 /*
2994 * Flag the last seen data fd not deleted. It will be
2995 * used as the last seen fd if any fd gets deleted in
2996 * this first loop.
2997 */
2998 last_notdel_data_fd = pollfd;
2999 }
3000 goto put_ctrl_connection;
3001 }
3002 assert(ctrl_conn->type == RELAY_CONTROL);
3003
3004 if (revents & LPOLLIN) {
3005 ret = ctrl_conn->sock->ops->recvmsg(ctrl_conn->sock,
3006 &recv_hdr, sizeof(recv_hdr), 0);
3007 if (ret <= 0) {
3008 /* Connection closed */
3009 relay_thread_close_connection(&events, pollfd,
3010 ctrl_conn);
3011 } else {
3012 ret = relay_process_control(&recv_hdr, ctrl_conn);
3013 if (ret < 0) {
3014 /* Clear the session on error. */
3015 relay_thread_close_connection(&events,
3016 pollfd, ctrl_conn);
3017 }
3018 seen_control = 1;
3019 }
3020 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
3021 relay_thread_close_connection(&events,
3022 pollfd, ctrl_conn);
3023 if (last_seen_data_fd == pollfd) {
3024 last_seen_data_fd = last_notdel_data_fd;
3025 }
3026 } else {
3027 ERR("Unexpected poll events %u for control sock %d",
3028 revents, pollfd);
3029 connection_put(ctrl_conn);
3030 goto error;
3031 }
3032 put_ctrl_connection:
3033 connection_put(ctrl_conn);
3034 }
3035 }
3036
3037 /*
3038 * The last loop handled a control request, go back to poll to make
3039 * sure we prioritise the control socket.
3040 */
3041 if (seen_control) {
3042 continue;
3043 }
3044
3045 if (last_seen_data_fd >= 0) {
3046 for (i = 0; i < nb_fd; i++) {
3047 int pollfd = LTTNG_POLL_GETFD(&events, i);
3048
3049 health_code_update();
3050
3051 if (last_seen_data_fd == pollfd) {
3052 idx = i;
3053 break;
3054 }
3055 }
3056 }
3057
3058 /* Process data connection. */
3059 for (i = idx + 1; i < nb_fd; i++) {
3060 /* Fetch the poll data. */
3061 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
3062 int pollfd = LTTNG_POLL_GETFD(&events, i);
3063 struct relay_connection *data_conn;
3064
3065 health_code_update();
3066
3067 if (!revents) {
3068 /* No activity for this FD (poll implementation). */
3069 continue;
3070 }
3071
3072 /* Skip the command pipe. It's handled in the first loop. */
3073 if (pollfd == relay_conn_pipe[0]) {
3074 continue;
3075 }
3076
3077 data_conn = connection_get_by_sock(relay_connections_ht, pollfd);
3078 if (!data_conn) {
3079 /* Skip it. Might be removed before. */
3080 continue;
3081 }
3082 if (data_conn->type == RELAY_CONTROL) {
3083 goto put_data_connection;
3084 }
3085 assert(data_conn->type == RELAY_DATA);
3086
3087 if (revents & LPOLLIN) {
3088 ret = relay_process_data(data_conn);
3089 /* Connection closed */
3090 if (ret < 0) {
3091 relay_thread_close_connection(&events, pollfd,
3092 data_conn);
3093 /*
3094 * Every goto restart call sets the last seen fd where
3095 * here we don't really care since we gracefully
3096 * continue the loop after the connection is deleted.
3097 */
3098 } else {
3099 /* Keep last seen port. */
3100 last_seen_data_fd = pollfd;
3101 connection_put(data_conn);
3102 goto restart;
3103 }
3104 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
3105 relay_thread_close_connection(&events, pollfd,
3106 data_conn);
3107 } else {
3108 ERR("Unknown poll events %u for data sock %d",
3109 revents, pollfd);
3110 }
3111 put_data_connection:
3112 connection_put(data_conn);
3113 }
3114 last_seen_data_fd = -1;
3115 }
3116
3117 /* Normal exit, no error */
3118 ret = 0;
3119
3120 exit:
3121 error:
3122 /* Cleanup reamaining connection object. */
3123 rcu_read_lock();
3124 cds_lfht_for_each_entry(relay_connections_ht->ht, &iter.iter,
3125 destroy_conn,
3126 sock_n.node) {
3127 health_code_update();
3128
3129 if (session_abort(destroy_conn->session)) {
3130 assert(0);
3131 }
3132
3133 /*
3134 * No need to grab another ref, because we own
3135 * destroy_conn.
3136 */
3137 relay_thread_close_connection(&events, destroy_conn->sock->fd,
3138 destroy_conn);
3139 }
3140 rcu_read_unlock();
3141
3142 lttng_poll_clean(&events);
3143 error_poll_create:
3144 lttng_ht_destroy(relay_connections_ht);
3145 relay_connections_ht_error:
3146 /* Close relay conn pipes */
3147 utils_close_pipe(relay_conn_pipe);
3148 if (err) {
3149 DBG("Thread exited with error");
3150 }
3151 DBG("Worker thread cleanup complete");
3152 error_testpoint:
3153 if (err) {
3154 health_error();
3155 ERR("Health error occurred in %s", __func__);
3156 }
3157 health_unregister(health_relayd);
3158 rcu_unregister_thread();
3159 lttng_relay_stop_threads();
3160 return NULL;
3161 }
3162
3163 /*
3164 * Create the relay command pipe to wake thread_manage_apps.
3165 * Closed in cleanup().
3166 */
3167 static int create_relay_conn_pipe(void)
3168 {
3169 int ret;
3170
3171 ret = utils_create_pipe_cloexec(relay_conn_pipe);
3172
3173 return ret;
3174 }
3175
3176 /*
3177 * main
3178 */
3179 int main(int argc, char **argv)
3180 {
3181 int ret = 0, retval = 0;
3182 void *status;
3183
3184 /* Parse arguments */
3185 progname = argv[0];
3186 if (set_options(argc, argv)) {
3187 retval = -1;
3188 goto exit_options;
3189 }
3190
3191 if (set_signal_handler()) {
3192 retval = -1;
3193 goto exit_options;
3194 }
3195
3196 /* Try to create directory if -o, --output is specified. */
3197 if (opt_output_path) {
3198 if (*opt_output_path != '/') {
3199 ERR("Please specify an absolute path for -o, --output PATH");
3200 retval = -1;
3201 goto exit_options;
3202 }
3203
3204 ret = utils_mkdir_recursive(opt_output_path, S_IRWXU | S_IRWXG,
3205 -1, -1);
3206 if (ret < 0) {
3207 ERR("Unable to create %s", opt_output_path);
3208 retval = -1;
3209 goto exit_options;
3210 }
3211 }
3212
3213 /* Daemonize */
3214 if (opt_daemon || opt_background) {
3215 int i;
3216
3217 ret = lttng_daemonize(&child_ppid, &recv_child_signal,
3218 !opt_background);
3219 if (ret < 0) {
3220 retval = -1;
3221 goto exit_options;
3222 }
3223
3224 /*
3225 * We are in the child. Make sure all other file
3226 * descriptors are closed, in case we are called with
3227 * more opened file descriptors than the standard ones.
3228 */
3229 for (i = 3; i < sysconf(_SC_OPEN_MAX); i++) {
3230 (void) close(i);
3231 }
3232 }
3233
3234 /* Initialize thread health monitoring */
3235 health_relayd = health_app_create(NR_HEALTH_RELAYD_TYPES);
3236 if (!health_relayd) {
3237 PERROR("health_app_create error");
3238 retval = -1;
3239 goto exit_health_app_create;
3240 }
3241
3242 /* Create thread quit pipe */
3243 if (init_thread_quit_pipe()) {
3244 retval = -1;
3245 goto exit_init_data;
3246 }
3247
3248 /* Setup the thread apps communication pipe. */
3249 if (create_relay_conn_pipe()) {
3250 retval = -1;
3251 goto exit_init_data;
3252 }
3253
3254 /* Init relay command queue. */
3255 cds_wfcq_init(&relay_conn_queue.head, &relay_conn_queue.tail);
3256
3257 /* Initialize communication library */
3258 lttcomm_init();
3259 lttcomm_inet_init();
3260
3261 /* tables of sessions indexed by session ID */
3262 sessions_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3263 if (!sessions_ht) {
3264 retval = -1;
3265 goto exit_init_data;
3266 }
3267
3268 /* tables of streams indexed by stream ID */
3269 relay_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3270 if (!relay_streams_ht) {
3271 retval = -1;
3272 goto exit_init_data;
3273 }
3274
3275 /* tables of streams indexed by stream ID */
3276 viewer_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3277 if (!viewer_streams_ht) {
3278 retval = -1;
3279 goto exit_init_data;
3280 }
3281
3282 ret = utils_create_pipe(health_quit_pipe);
3283 if (ret) {
3284 retval = -1;
3285 goto exit_health_quit_pipe;
3286 }
3287
3288 /* Create thread to manage the client socket */
3289 ret = pthread_create(&health_thread, default_pthread_attr(),
3290 thread_manage_health, (void *) NULL);
3291 if (ret) {
3292 errno = ret;
3293 PERROR("pthread_create health");
3294 retval = -1;
3295 goto exit_health_thread;
3296 }
3297
3298 /* Setup the dispatcher thread */
3299 ret = pthread_create(&dispatcher_thread, default_pthread_attr(),
3300 relay_thread_dispatcher, (void *) NULL);
3301 if (ret) {
3302 errno = ret;
3303 PERROR("pthread_create dispatcher");
3304 retval = -1;
3305 goto exit_dispatcher_thread;
3306 }
3307
3308 /* Setup the worker thread */
3309 ret = pthread_create(&worker_thread, default_pthread_attr(),
3310 relay_thread_worker, NULL);
3311 if (ret) {
3312 errno = ret;
3313 PERROR("pthread_create worker");
3314 retval = -1;
3315 goto exit_worker_thread;
3316 }
3317
3318 /* Setup the listener thread */
3319 ret = pthread_create(&listener_thread, default_pthread_attr(),
3320 relay_thread_listener, (void *) NULL);
3321 if (ret) {
3322 errno = ret;
3323 PERROR("pthread_create listener");
3324 retval = -1;
3325 goto exit_listener_thread;
3326 }
3327
3328 ret = relayd_live_create(live_uri);
3329 if (ret) {
3330 ERR("Starting live viewer threads");
3331 retval = -1;
3332 goto exit_live;
3333 }
3334
3335 /*
3336 * This is where we start awaiting program completion (e.g. through
3337 * signal that asks threads to teardown).
3338 */
3339
3340 ret = relayd_live_join();
3341 if (ret) {
3342 retval = -1;
3343 }
3344 exit_live:
3345
3346 ret = pthread_join(listener_thread, &status);
3347 if (ret) {
3348 errno = ret;
3349 PERROR("pthread_join listener_thread");
3350 retval = -1;
3351 }
3352
3353 exit_listener_thread:
3354 ret = pthread_join(worker_thread, &status);
3355 if (ret) {
3356 errno = ret;
3357 PERROR("pthread_join worker_thread");
3358 retval = -1;
3359 }
3360
3361 exit_worker_thread:
3362 ret = pthread_join(dispatcher_thread, &status);
3363 if (ret) {
3364 errno = ret;
3365 PERROR("pthread_join dispatcher_thread");
3366 retval = -1;
3367 }
3368 exit_dispatcher_thread:
3369
3370 ret = pthread_join(health_thread, &status);
3371 if (ret) {
3372 errno = ret;
3373 PERROR("pthread_join health_thread");
3374 retval = -1;
3375 }
3376 exit_health_thread:
3377
3378 utils_close_pipe(health_quit_pipe);
3379 exit_health_quit_pipe:
3380
3381 exit_init_data:
3382 health_app_destroy(health_relayd);
3383 exit_health_app_create:
3384 exit_options:
3385 /*
3386 * Wait for all pending call_rcu work to complete before tearing
3387 * down data structures. call_rcu worker may be trying to
3388 * perform lookups in those structures.
3389 */
3390 rcu_barrier();
3391 relayd_cleanup();
3392
3393 /* Ensure all prior call_rcu are done. */
3394 rcu_barrier();
3395
3396 if (!retval) {
3397 exit(EXIT_SUCCESS);
3398 } else {
3399 exit(EXIT_FAILURE);
3400 }
3401 }
This page took 0.093697 seconds and 4 git commands to generate.