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