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