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