Fix: Live tracing does not honor live timer after first tracefile with tracefile...
[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 /* Thread quit pipe has been closed. Killing thread. */
838 ret = check_thread_quit_pipe(pollfd, revents);
839 if (ret) {
840 err = 0;
841 goto exit;
842 }
843
844 if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
845 ERR("socket poll error");
846 goto error;
847 } else if (revents & LPOLLIN) {
848 /*
849 * Get allocated in this thread, enqueued to a global queue,
850 * dequeued and freed in the worker thread.
851 */
852 int val = 1;
853 struct relay_connection *new_conn;
854 struct lttcomm_sock *newsock;
855
856 new_conn = connection_create();
857 if (!new_conn) {
858 goto error;
859 }
860
861 if (pollfd == data_sock->fd) {
862 new_conn->type = RELAY_DATA;
863 newsock = data_sock->ops->accept(data_sock);
864 DBG("Relay data connection accepted, socket %d",
865 newsock->fd);
866 } else {
867 assert(pollfd == control_sock->fd);
868 new_conn->type = RELAY_CONTROL;
869 newsock = control_sock->ops->accept(control_sock);
870 DBG("Relay control connection accepted, socket %d",
871 newsock->fd);
872 }
873 if (!newsock) {
874 PERROR("accepting sock");
875 connection_free(new_conn);
876 goto error;
877 }
878
879 ret = setsockopt(newsock->fd, SOL_SOCKET, SO_REUSEADDR, &val,
880 sizeof(val));
881 if (ret < 0) {
882 PERROR("setsockopt inet");
883 lttcomm_destroy_sock(newsock);
884 connection_free(new_conn);
885 goto error;
886 }
887 new_conn->sock = newsock;
888
889 /* Enqueue request for the dispatcher thread. */
890 cds_wfq_enqueue(&relay_conn_queue.queue, &new_conn->qnode);
891
892 /*
893 * Wake the dispatch queue futex. Implicit memory barrier with
894 * the exchange in cds_wfq_enqueue.
895 */
896 futex_nto1_wake(&relay_conn_queue.futex);
897 }
898 }
899 }
900
901 exit:
902 error:
903 error_poll_add:
904 error_testpoint:
905 lttng_poll_clean(&events);
906 error_create_poll:
907 if (data_sock->fd >= 0) {
908 ret = data_sock->ops->close(data_sock);
909 if (ret) {
910 PERROR("close");
911 }
912 }
913 lttcomm_destroy_sock(data_sock);
914 error_sock_relay:
915 if (control_sock->fd >= 0) {
916 ret = control_sock->ops->close(control_sock);
917 if (ret) {
918 PERROR("close");
919 }
920 }
921 lttcomm_destroy_sock(control_sock);
922 error_sock_control:
923 if (err) {
924 health_error();
925 ERR("Health error occurred in %s", __func__);
926 }
927 health_unregister(health_relayd);
928 DBG("Relay listener thread cleanup complete");
929 stop_threads();
930 return NULL;
931 }
932
933 /*
934 * This thread manages the dispatching of the requests to worker threads
935 */
936 static
937 void *relay_thread_dispatcher(void *data)
938 {
939 int err = -1;
940 ssize_t ret;
941 struct cds_wfq_node *node;
942 struct relay_connection *new_conn = NULL;
943
944 DBG("[thread] Relay dispatcher started");
945
946 health_register(health_relayd, HEALTH_RELAYD_TYPE_DISPATCHER);
947
948 if (testpoint(relayd_thread_dispatcher)) {
949 goto error_testpoint;
950 }
951
952 health_code_update();
953
954 while (!CMM_LOAD_SHARED(dispatch_thread_exit)) {
955 health_code_update();
956
957 /* Atomically prepare the queue futex */
958 futex_nto1_prepare(&relay_conn_queue.futex);
959
960 do {
961 health_code_update();
962
963 /* Dequeue commands */
964 node = cds_wfq_dequeue_blocking(&relay_conn_queue.queue);
965 if (node == NULL) {
966 DBG("Woken up but nothing in the relay command queue");
967 /* Continue thread execution */
968 break;
969 }
970 new_conn = caa_container_of(node, struct relay_connection, qnode);
971
972 DBG("Dispatching request waiting on sock %d", new_conn->sock->fd);
973
974 /*
975 * Inform worker thread of the new request. This call is blocking
976 * so we can be assured that the data will be read at some point in
977 * time or wait to the end of the world :)
978 */
979 ret = lttng_write(relay_conn_pipe[1], &new_conn, sizeof(new_conn));
980 if (ret < 0) {
981 PERROR("write connection pipe");
982 connection_destroy(new_conn);
983 goto error;
984 }
985 } while (node != NULL);
986
987 /* Futex wait on queue. Blocking call on futex() */
988 health_poll_entry();
989 futex_nto1_wait(&relay_conn_queue.futex);
990 health_poll_exit();
991 }
992
993 /* Normal exit, no error */
994 err = 0;
995
996 error:
997 error_testpoint:
998 if (err) {
999 health_error();
1000 ERR("Health error occurred in %s", __func__);
1001 }
1002 health_unregister(health_relayd);
1003 DBG("Dispatch thread dying");
1004 stop_threads();
1005 return NULL;
1006 }
1007
1008 static void try_close_streams(struct relay_session *session)
1009 {
1010 struct ctf_trace *ctf_trace;
1011 struct lttng_ht_iter iter;
1012
1013 assert(session);
1014
1015 pthread_mutex_lock(&session->viewer_ready_lock);
1016 rcu_read_lock();
1017 cds_lfht_for_each_entry(session->ctf_traces_ht->ht, &iter.iter, ctf_trace,
1018 node.node) {
1019 struct relay_stream *stream;
1020
1021 /* Close streams. */
1022 cds_list_for_each_entry(stream, &ctf_trace->stream_list, trace_list) {
1023 stream_close(session, stream);
1024 }
1025
1026 ctf_trace->invalid_flag = 1;
1027 ctf_trace_try_destroy(session, ctf_trace);
1028 }
1029 rcu_read_unlock();
1030 pthread_mutex_unlock(&session->viewer_ready_lock);
1031 }
1032
1033 /*
1034 * Try to destroy a session within a connection.
1035 */
1036 static void destroy_session(struct relay_session *session,
1037 struct lttng_ht *sessions_ht)
1038 {
1039 assert(session);
1040 assert(sessions_ht);
1041
1042 /* Indicate that this session can be destroyed from now on. */
1043 session->close_flag = 1;
1044
1045 try_close_streams(session);
1046
1047 /*
1048 * This will try to delete and destroy the session if no viewer is attached
1049 * to it meaning the refcount is down to zero.
1050 */
1051 session_try_destroy(sessions_ht, session);
1052 }
1053
1054 /*
1055 * Copy index data from the control port to a given index object.
1056 */
1057 static void copy_index_control_data(struct relay_index *index,
1058 struct lttcomm_relayd_index *data)
1059 {
1060 assert(index);
1061 assert(data);
1062
1063 /*
1064 * The index on disk is encoded in big endian, so we don't need to convert
1065 * the data received on the network. The data_offset value is NEVER
1066 * modified here and is updated by the data thread.
1067 */
1068 index->index_data.packet_size = data->packet_size;
1069 index->index_data.content_size = data->content_size;
1070 index->index_data.timestamp_begin = data->timestamp_begin;
1071 index->index_data.timestamp_end = data->timestamp_end;
1072 index->index_data.events_discarded = data->events_discarded;
1073 index->index_data.stream_id = data->stream_id;
1074 }
1075
1076 /*
1077 * Handle the RELAYD_CREATE_SESSION command.
1078 *
1079 * On success, send back the session id or else return a negative value.
1080 */
1081 static
1082 int relay_create_session(struct lttcomm_relayd_hdr *recv_hdr,
1083 struct relay_connection *conn)
1084 {
1085 int ret = 0, send_ret;
1086 struct relay_session *session;
1087 struct lttcomm_relayd_status_session reply;
1088
1089 assert(recv_hdr);
1090 assert(conn);
1091
1092 memset(&reply, 0, sizeof(reply));
1093
1094 session = session_create();
1095 if (!session) {
1096 ret = -1;
1097 goto error;
1098 }
1099 session->minor = conn->minor;
1100 session->major = conn->major;
1101 conn->session_id = session->id;
1102 conn->session = session;
1103
1104 reply.session_id = htobe64(session->id);
1105
1106 switch (conn->minor) {
1107 case 1:
1108 case 2:
1109 case 3:
1110 break;
1111 case 4: /* LTTng sessiond 2.4 */
1112 default:
1113 ret = cmd_create_session_2_4(conn, session);
1114 }
1115
1116 lttng_ht_add_unique_u64(conn->sessions_ht, &session->session_n);
1117 DBG("Created session %" PRIu64, session->id);
1118
1119 error:
1120 if (ret < 0) {
1121 reply.ret_code = htobe32(LTTNG_ERR_FATAL);
1122 } else {
1123 reply.ret_code = htobe32(LTTNG_OK);
1124 }
1125
1126 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1127 if (send_ret < 0) {
1128 ERR("Relayd sending session id");
1129 ret = send_ret;
1130 }
1131
1132 return ret;
1133 }
1134
1135 /*
1136 * When we have received all the streams and the metadata for a channel,
1137 * we make them visible to the viewer threads.
1138 */
1139 static
1140 void set_viewer_ready_flag(struct relay_connection *conn)
1141 {
1142 struct relay_stream *stream, *tmp_stream;
1143
1144 pthread_mutex_lock(&conn->session->viewer_ready_lock);
1145 cds_list_for_each_entry_safe(stream, tmp_stream, &conn->recv_head,
1146 recv_list) {
1147 stream->viewer_ready = 1;
1148 cds_list_del(&stream->recv_list);
1149 }
1150 pthread_mutex_unlock(&conn->session->viewer_ready_lock);
1151 return;
1152 }
1153
1154 /*
1155 * Add a recv handle node to the connection recv list with the given stream
1156 * handle. A new node is allocated thus must be freed when the node is deleted
1157 * from the list.
1158 */
1159 static void queue_stream(struct relay_stream *stream,
1160 struct relay_connection *conn)
1161 {
1162 assert(conn);
1163 assert(stream);
1164
1165 cds_list_add(&stream->recv_list, &conn->recv_head);
1166 }
1167
1168 /*
1169 * relay_add_stream: allocate a new stream for a session
1170 */
1171 static
1172 int relay_add_stream(struct lttcomm_relayd_hdr *recv_hdr,
1173 struct relay_connection *conn)
1174 {
1175 int ret, send_ret;
1176 struct relay_session *session = conn->session;
1177 struct relay_stream *stream = NULL;
1178 struct lttcomm_relayd_status_stream reply;
1179 struct ctf_trace *trace;
1180
1181 if (!session || conn->version_check_done == 0) {
1182 ERR("Trying to add a stream before version check");
1183 ret = -1;
1184 goto end_no_session;
1185 }
1186
1187 stream = zmalloc(sizeof(struct relay_stream));
1188 if (stream == NULL) {
1189 PERROR("relay stream zmalloc");
1190 ret = -1;
1191 goto end_no_session;
1192 }
1193
1194 switch (conn->minor) {
1195 case 1: /* LTTng sessiond 2.1 */
1196 ret = cmd_recv_stream_2_1(conn, stream);
1197 break;
1198 case 2: /* LTTng sessiond 2.2 */
1199 default:
1200 ret = cmd_recv_stream_2_2(conn, stream);
1201 break;
1202 }
1203 if (ret < 0) {
1204 goto err_free_stream;
1205 }
1206
1207 rcu_read_lock();
1208 stream->stream_handle = ++last_relay_stream_id;
1209 stream->prev_seq = -1ULL;
1210 stream->session_id = session->id;
1211 stream->index_fd = -1;
1212 stream->read_index_fd = -1;
1213 stream->ctf_stream_id = -1ULL;
1214 lttng_ht_node_init_u64(&stream->node, stream->stream_handle);
1215 pthread_mutex_init(&stream->lock, NULL);
1216
1217 ret = utils_mkdir_recursive(stream->path_name, S_IRWXU | S_IRWXG);
1218 if (ret < 0) {
1219 ERR("relay creating output directory");
1220 goto end;
1221 }
1222
1223 /*
1224 * No need to use run_as API here because whatever we receives, the relayd
1225 * uses its own credentials for the stream files.
1226 */
1227 ret = utils_create_stream_file(stream->path_name, stream->channel_name,
1228 stream->tracefile_size, 0, relayd_uid, relayd_gid, NULL);
1229 if (ret < 0) {
1230 ERR("Create output file");
1231 goto end;
1232 }
1233 stream->fd = ret;
1234 if (stream->tracefile_size) {
1235 DBG("Tracefile %s/%s_0 created", stream->path_name, stream->channel_name);
1236 } else {
1237 DBG("Tracefile %s/%s created", stream->path_name, stream->channel_name);
1238 }
1239
1240 trace = ctf_trace_find_by_path(session->ctf_traces_ht, stream->path_name);
1241 if (!trace) {
1242 trace = ctf_trace_create(stream->path_name);
1243 if (!trace) {
1244 ret = -1;
1245 goto end;
1246 }
1247 ctf_trace_add(session->ctf_traces_ht, trace);
1248 }
1249 ctf_trace_get_ref(trace);
1250
1251 if (!strncmp(stream->channel_name, DEFAULT_METADATA_NAME, NAME_MAX)) {
1252 stream->metadata_flag = 1;
1253 /* Assign quick reference to the metadata stream in the trace. */
1254 trace->metadata_stream = stream;
1255 }
1256
1257 /*
1258 * Add the stream in the recv list of the connection. Once the end stream
1259 * message is received, this list is emptied and streams are set with the
1260 * viewer ready flag.
1261 */
1262 queue_stream(stream, conn);
1263
1264 /*
1265 * Both in the ctf_trace object and the global stream ht since the data
1266 * side of the relayd does not have the concept of session.
1267 */
1268 lttng_ht_add_unique_u64(relay_streams_ht, &stream->node);
1269 cds_list_add_tail(&stream->trace_list, &trace->stream_list);
1270
1271 session->stream_count++;
1272
1273 DBG("Relay new stream added %s with ID %" PRIu64, stream->channel_name,
1274 stream->stream_handle);
1275
1276 end:
1277 memset(&reply, 0, sizeof(reply));
1278 reply.handle = htobe64(stream->stream_handle);
1279 /* send the session id to the client or a negative return code on error */
1280 if (ret < 0) {
1281 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1282 /* stream was not properly added to the ht, so free it */
1283 free(stream);
1284 } else {
1285 reply.ret_code = htobe32(LTTNG_OK);
1286 }
1287
1288 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1289 sizeof(struct lttcomm_relayd_status_stream), 0);
1290 if (send_ret < 0) {
1291 ERR("Relay sending stream id");
1292 ret = send_ret;
1293 }
1294 rcu_read_unlock();
1295
1296 end_no_session:
1297 return ret;
1298
1299 err_free_stream:
1300 free(stream->path_name);
1301 free(stream->channel_name);
1302 free(stream);
1303 return ret;
1304 }
1305
1306 /*
1307 * relay_close_stream: close a specific stream
1308 */
1309 static
1310 int relay_close_stream(struct lttcomm_relayd_hdr *recv_hdr,
1311 struct relay_connection *conn)
1312 {
1313 int ret, send_ret;
1314 struct relay_session *session = conn->session;
1315 struct lttcomm_relayd_close_stream stream_info;
1316 struct lttcomm_relayd_generic_reply reply;
1317 struct relay_stream *stream;
1318
1319 DBG("Close stream received");
1320
1321 if (!session || conn->version_check_done == 0) {
1322 ERR("Trying to close a stream before version check");
1323 ret = -1;
1324 goto end_no_session;
1325 }
1326
1327 ret = conn->sock->ops->recvmsg(conn->sock, &stream_info,
1328 sizeof(struct lttcomm_relayd_close_stream), 0);
1329 if (ret < sizeof(struct lttcomm_relayd_close_stream)) {
1330 if (ret == 0) {
1331 /* Orderly shutdown. Not necessary to print an error. */
1332 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1333 } else {
1334 ERR("Relay didn't receive valid add_stream struct size : %d", ret);
1335 }
1336 ret = -1;
1337 goto end_no_session;
1338 }
1339
1340 rcu_read_lock();
1341 stream = stream_find_by_id(relay_streams_ht,
1342 be64toh(stream_info.stream_id));
1343 if (!stream) {
1344 ret = -1;
1345 goto end_unlock;
1346 }
1347
1348 stream->last_net_seq_num = be64toh(stream_info.last_net_seq_num);
1349 stream->close_flag = 1;
1350 session->stream_count--;
1351 assert(session->stream_count >= 0);
1352
1353 /* Check if we can close it or else the data will do it. */
1354 try_close_stream(session, stream);
1355
1356 end_unlock:
1357 rcu_read_unlock();
1358
1359 memset(&reply, 0, sizeof(reply));
1360 if (ret < 0) {
1361 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1362 } else {
1363 reply.ret_code = htobe32(LTTNG_OK);
1364 }
1365 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1366 sizeof(struct lttcomm_relayd_generic_reply), 0);
1367 if (send_ret < 0) {
1368 ERR("Relay sending stream id");
1369 ret = send_ret;
1370 }
1371
1372 end_no_session:
1373 return ret;
1374 }
1375
1376 /*
1377 * relay_unknown_command: send -1 if received unknown command
1378 */
1379 static
1380 void relay_unknown_command(struct relay_connection *conn)
1381 {
1382 struct lttcomm_relayd_generic_reply reply;
1383 int ret;
1384
1385 memset(&reply, 0, sizeof(reply));
1386 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1387 ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1388 sizeof(struct lttcomm_relayd_generic_reply), 0);
1389 if (ret < 0) {
1390 ERR("Relay sending unknown command");
1391 }
1392 }
1393
1394 /*
1395 * relay_start: send an acknowledgment to the client to tell if we are
1396 * ready to receive data. We are ready if a session is established.
1397 */
1398 static
1399 int relay_start(struct lttcomm_relayd_hdr *recv_hdr,
1400 struct relay_connection *conn)
1401 {
1402 int ret = htobe32(LTTNG_OK);
1403 struct lttcomm_relayd_generic_reply reply;
1404 struct relay_session *session = conn->session;
1405
1406 if (!session) {
1407 DBG("Trying to start the streaming without a session established");
1408 ret = htobe32(LTTNG_ERR_UNK);
1409 }
1410
1411 memset(&reply, 0, sizeof(reply));
1412 reply.ret_code = ret;
1413 ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1414 sizeof(struct lttcomm_relayd_generic_reply), 0);
1415 if (ret < 0) {
1416 ERR("Relay sending start ack");
1417 }
1418
1419 return ret;
1420 }
1421
1422 /*
1423 * Append padding to the file pointed by the file descriptor fd.
1424 */
1425 static int write_padding_to_file(int fd, uint32_t size)
1426 {
1427 ssize_t ret = 0;
1428 char *zeros;
1429
1430 if (size == 0) {
1431 goto end;
1432 }
1433
1434 zeros = zmalloc(size);
1435 if (zeros == NULL) {
1436 PERROR("zmalloc zeros for padding");
1437 ret = -1;
1438 goto end;
1439 }
1440
1441 ret = lttng_write(fd, zeros, size);
1442 if (ret < size) {
1443 PERROR("write padding to file");
1444 }
1445
1446 free(zeros);
1447
1448 end:
1449 return ret;
1450 }
1451
1452 /*
1453 * relay_recv_metadata: receive the metada for the session.
1454 */
1455 static
1456 int relay_recv_metadata(struct lttcomm_relayd_hdr *recv_hdr,
1457 struct relay_connection *conn)
1458 {
1459 int ret = htobe32(LTTNG_OK);
1460 ssize_t size_ret;
1461 struct relay_session *session = conn->session;
1462 struct lttcomm_relayd_metadata_payload *metadata_struct;
1463 struct relay_stream *metadata_stream;
1464 uint64_t data_size, payload_size;
1465 struct ctf_trace *ctf_trace;
1466
1467 if (!session) {
1468 ERR("Metadata sent before version check");
1469 ret = -1;
1470 goto end;
1471 }
1472
1473 data_size = payload_size = be64toh(recv_hdr->data_size);
1474 if (data_size < sizeof(struct lttcomm_relayd_metadata_payload)) {
1475 ERR("Incorrect data size");
1476 ret = -1;
1477 goto end;
1478 }
1479 payload_size -= sizeof(struct lttcomm_relayd_metadata_payload);
1480
1481 if (data_buffer_size < data_size) {
1482 /* In case the realloc fails, we can free the memory */
1483 char *tmp_data_ptr;
1484
1485 tmp_data_ptr = realloc(data_buffer, data_size);
1486 if (!tmp_data_ptr) {
1487 ERR("Allocating data buffer");
1488 free(data_buffer);
1489 ret = -1;
1490 goto end;
1491 }
1492 data_buffer = tmp_data_ptr;
1493 data_buffer_size = data_size;
1494 }
1495 memset(data_buffer, 0, data_size);
1496 DBG2("Relay receiving metadata, waiting for %" PRIu64 " bytes", data_size);
1497 ret = conn->sock->ops->recvmsg(conn->sock, data_buffer, data_size, 0);
1498 if (ret < 0 || ret != data_size) {
1499 if (ret == 0) {
1500 /* Orderly shutdown. Not necessary to print an error. */
1501 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1502 } else {
1503 ERR("Relay didn't receive the whole metadata");
1504 }
1505 ret = -1;
1506 goto end;
1507 }
1508 metadata_struct = (struct lttcomm_relayd_metadata_payload *) data_buffer;
1509
1510 rcu_read_lock();
1511 metadata_stream = stream_find_by_id(relay_streams_ht,
1512 be64toh(metadata_struct->stream_id));
1513 if (!metadata_stream) {
1514 ret = -1;
1515 goto end_unlock;
1516 }
1517
1518 size_ret = lttng_write(metadata_stream->fd, metadata_struct->payload,
1519 payload_size);
1520 if (size_ret < payload_size) {
1521 ERR("Relay error writing metadata on file");
1522 ret = -1;
1523 goto end_unlock;
1524 }
1525
1526 ret = write_padding_to_file(metadata_stream->fd,
1527 be32toh(metadata_struct->padding_size));
1528 if (ret < 0) {
1529 goto end_unlock;
1530 }
1531
1532 ctf_trace = ctf_trace_find_by_path(session->ctf_traces_ht,
1533 metadata_stream->path_name);
1534 assert(ctf_trace);
1535 ctf_trace->metadata_received +=
1536 payload_size + be32toh(metadata_struct->padding_size);
1537
1538 DBG2("Relay metadata written");
1539
1540 end_unlock:
1541 rcu_read_unlock();
1542 end:
1543 return ret;
1544 }
1545
1546 /*
1547 * relay_send_version: send relayd version number
1548 */
1549 static
1550 int relay_send_version(struct lttcomm_relayd_hdr *recv_hdr,
1551 struct relay_connection *conn)
1552 {
1553 int ret;
1554 struct lttcomm_relayd_version reply, msg;
1555
1556 assert(conn);
1557
1558 conn->version_check_done = 1;
1559
1560 /* Get version from the other side. */
1561 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
1562 if (ret < 0 || ret != sizeof(msg)) {
1563 if (ret == 0) {
1564 /* Orderly shutdown. Not necessary to print an error. */
1565 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1566 } else {
1567 ERR("Relay failed to receive the version values.");
1568 }
1569 ret = -1;
1570 goto end;
1571 }
1572
1573 memset(&reply, 0, sizeof(reply));
1574 reply.major = RELAYD_VERSION_COMM_MAJOR;
1575 reply.minor = RELAYD_VERSION_COMM_MINOR;
1576
1577 /* Major versions must be the same */
1578 if (reply.major != be32toh(msg.major)) {
1579 DBG("Incompatible major versions (%u vs %u), deleting session",
1580 reply.major, be32toh(msg.major));
1581 destroy_session(conn->session, conn->sessions_ht);
1582 ret = 0;
1583 goto end;
1584 }
1585
1586 conn->major = reply.major;
1587 /* We adapt to the lowest compatible version */
1588 if (reply.minor <= be32toh(msg.minor)) {
1589 conn->minor = reply.minor;
1590 } else {
1591 conn->minor = be32toh(msg.minor);
1592 }
1593
1594 reply.major = htobe32(reply.major);
1595 reply.minor = htobe32(reply.minor);
1596 ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1597 sizeof(struct lttcomm_relayd_version), 0);
1598 if (ret < 0) {
1599 ERR("Relay sending version");
1600 }
1601
1602 DBG("Version check done using protocol %u.%u", conn->major,
1603 conn->minor);
1604
1605 end:
1606 return ret;
1607 }
1608
1609 /*
1610 * Check for data pending for a given stream id from the session daemon.
1611 */
1612 static
1613 int relay_data_pending(struct lttcomm_relayd_hdr *recv_hdr,
1614 struct relay_connection *conn)
1615 {
1616 struct relay_session *session = conn->session;
1617 struct lttcomm_relayd_data_pending msg;
1618 struct lttcomm_relayd_generic_reply reply;
1619 struct relay_stream *stream;
1620 int ret;
1621 uint64_t last_net_seq_num, stream_id;
1622
1623 DBG("Data pending command received");
1624
1625 if (!session || conn->version_check_done == 0) {
1626 ERR("Trying to check for data before version check");
1627 ret = -1;
1628 goto end_no_session;
1629 }
1630
1631 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
1632 if (ret < sizeof(msg)) {
1633 if (ret == 0) {
1634 /* Orderly shutdown. Not necessary to print an error. */
1635 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1636 } else {
1637 ERR("Relay didn't receive valid data_pending struct size : %d",
1638 ret);
1639 }
1640 ret = -1;
1641 goto end_no_session;
1642 }
1643
1644 stream_id = be64toh(msg.stream_id);
1645 last_net_seq_num = be64toh(msg.last_net_seq_num);
1646
1647 rcu_read_lock();
1648 stream = stream_find_by_id(relay_streams_ht, stream_id);
1649 if (stream == NULL) {
1650 ret = -1;
1651 goto end_unlock;
1652 }
1653
1654 DBG("Data pending for stream id %" PRIu64 " prev_seq %" PRIu64
1655 " and last_seq %" PRIu64, stream_id, stream->prev_seq,
1656 last_net_seq_num);
1657
1658 /* Avoid wrapping issue */
1659 if (((int64_t) (stream->prev_seq - last_net_seq_num)) >= 0) {
1660 /* Data has in fact been written and is NOT pending */
1661 ret = 0;
1662 } else {
1663 /* Data still being streamed thus pending */
1664 ret = 1;
1665 }
1666
1667 /* Pending check is now done. */
1668 stream->data_pending_check_done = 1;
1669
1670 end_unlock:
1671 rcu_read_unlock();
1672
1673 memset(&reply, 0, sizeof(reply));
1674 reply.ret_code = htobe32(ret);
1675 ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1676 if (ret < 0) {
1677 ERR("Relay data pending ret code failed");
1678 }
1679
1680 end_no_session:
1681 return ret;
1682 }
1683
1684 /*
1685 * Wait for the control socket to reach a quiescent state.
1686 *
1687 * Note that for now, when receiving this command from the session daemon, this
1688 * means that every subsequent commands or data received on the control socket
1689 * has been handled. So, this is why we simply return OK here.
1690 */
1691 static
1692 int relay_quiescent_control(struct lttcomm_relayd_hdr *recv_hdr,
1693 struct relay_connection *conn)
1694 {
1695 int ret;
1696 uint64_t stream_id;
1697 struct relay_stream *stream;
1698 struct lttng_ht_iter iter;
1699 struct lttcomm_relayd_quiescent_control msg;
1700 struct lttcomm_relayd_generic_reply reply;
1701
1702 DBG("Checking quiescent state on control socket");
1703
1704 if (!conn->session || conn->version_check_done == 0) {
1705 ERR("Trying to check for data before version check");
1706 ret = -1;
1707 goto end_no_session;
1708 }
1709
1710 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
1711 if (ret < sizeof(msg)) {
1712 if (ret == 0) {
1713 /* Orderly shutdown. Not necessary to print an error. */
1714 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1715 } else {
1716 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1717 ret);
1718 }
1719 ret = -1;
1720 goto end_no_session;
1721 }
1722
1723 stream_id = be64toh(msg.stream_id);
1724
1725 rcu_read_lock();
1726 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
1727 node.node) {
1728 if (stream->stream_handle == stream_id) {
1729 stream->data_pending_check_done = 1;
1730 DBG("Relay quiescent control pending flag set to %" PRIu64,
1731 stream_id);
1732 break;
1733 }
1734 }
1735 rcu_read_unlock();
1736
1737 memset(&reply, 0, sizeof(reply));
1738 reply.ret_code = htobe32(LTTNG_OK);
1739 ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1740 if (ret < 0) {
1741 ERR("Relay data quiescent control ret code failed");
1742 }
1743
1744 end_no_session:
1745 return ret;
1746 }
1747
1748 /*
1749 * Initialize a data pending command. This means that a client is about to ask
1750 * for data pending for each stream he/she holds. Simply iterate over all
1751 * streams of a session and set the data_pending_check_done flag.
1752 *
1753 * This command returns to the client a LTTNG_OK code.
1754 */
1755 static
1756 int relay_begin_data_pending(struct lttcomm_relayd_hdr *recv_hdr,
1757 struct relay_connection *conn)
1758 {
1759 int ret;
1760 struct lttng_ht_iter iter;
1761 struct lttcomm_relayd_begin_data_pending msg;
1762 struct lttcomm_relayd_generic_reply reply;
1763 struct relay_stream *stream;
1764 uint64_t session_id;
1765
1766 assert(recv_hdr);
1767 assert(conn);
1768
1769 DBG("Init streams for data pending");
1770
1771 if (!conn->session || conn->version_check_done == 0) {
1772 ERR("Trying to check for data before version check");
1773 ret = -1;
1774 goto end_no_session;
1775 }
1776
1777 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
1778 if (ret < sizeof(msg)) {
1779 if (ret == 0) {
1780 /* Orderly shutdown. Not necessary to print an error. */
1781 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1782 } else {
1783 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1784 ret);
1785 }
1786 ret = -1;
1787 goto end_no_session;
1788 }
1789
1790 session_id = be64toh(msg.session_id);
1791
1792 /*
1793 * Iterate over all streams to set the begin data pending flag. For now, the
1794 * streams are indexed by stream handle so we have to iterate over all
1795 * streams to find the one associated with the right session_id.
1796 */
1797 rcu_read_lock();
1798 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
1799 node.node) {
1800 if (stream->session_id == session_id) {
1801 stream->data_pending_check_done = 0;
1802 DBG("Set begin data pending flag to stream %" PRIu64,
1803 stream->stream_handle);
1804 }
1805 }
1806 rcu_read_unlock();
1807
1808 memset(&reply, 0, sizeof(reply));
1809 /* All good, send back reply. */
1810 reply.ret_code = htobe32(LTTNG_OK);
1811
1812 ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1813 if (ret < 0) {
1814 ERR("Relay begin data pending send reply failed");
1815 }
1816
1817 end_no_session:
1818 return ret;
1819 }
1820
1821 /*
1822 * End data pending command. This will check, for a given session id, if each
1823 * stream associated with it has its data_pending_check_done flag set. If not,
1824 * this means that the client lost track of the stream but the data is still
1825 * being streamed on our side. In this case, we inform the client that data is
1826 * inflight.
1827 *
1828 * Return to the client if there is data in flight or not with a ret_code.
1829 */
1830 static
1831 int relay_end_data_pending(struct lttcomm_relayd_hdr *recv_hdr,
1832 struct relay_connection *conn)
1833 {
1834 int ret;
1835 struct lttng_ht_iter iter;
1836 struct lttcomm_relayd_end_data_pending msg;
1837 struct lttcomm_relayd_generic_reply reply;
1838 struct relay_stream *stream;
1839 uint64_t session_id;
1840 uint32_t is_data_inflight = 0;
1841
1842 assert(recv_hdr);
1843 assert(conn);
1844
1845 DBG("End data pending command");
1846
1847 if (!conn->session || conn->version_check_done == 0) {
1848 ERR("Trying to check for data before version check");
1849 ret = -1;
1850 goto end_no_session;
1851 }
1852
1853 ret = conn->sock->ops->recvmsg(conn->sock, &msg, sizeof(msg), 0);
1854 if (ret < sizeof(msg)) {
1855 if (ret == 0) {
1856 /* Orderly shutdown. Not necessary to print an error. */
1857 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1858 } else {
1859 ERR("Relay didn't receive valid end data_pending struct size: %d",
1860 ret);
1861 }
1862 ret = -1;
1863 goto end_no_session;
1864 }
1865
1866 session_id = be64toh(msg.session_id);
1867
1868 /* Iterate over all streams to see if the begin data pending flag is set. */
1869 rcu_read_lock();
1870 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
1871 node.node) {
1872 if (stream->session_id == session_id &&
1873 !stream->data_pending_check_done && !stream->terminated_flag) {
1874 is_data_inflight = 1;
1875 DBG("Data is still in flight for stream %" PRIu64,
1876 stream->stream_handle);
1877 break;
1878 }
1879 }
1880 rcu_read_unlock();
1881
1882 memset(&reply, 0, sizeof(reply));
1883 /* All good, send back reply. */
1884 reply.ret_code = htobe32(is_data_inflight);
1885
1886 ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1887 if (ret < 0) {
1888 ERR("Relay end data pending send reply failed");
1889 }
1890
1891 end_no_session:
1892 return ret;
1893 }
1894
1895 /*
1896 * Receive an index for a specific stream.
1897 *
1898 * Return 0 on success else a negative value.
1899 */
1900 static
1901 int relay_recv_index(struct lttcomm_relayd_hdr *recv_hdr,
1902 struct relay_connection *conn)
1903 {
1904 int ret, send_ret, index_created = 0;
1905 struct relay_session *session = conn->session;
1906 struct lttcomm_relayd_index index_info;
1907 struct relay_index *index, *wr_index = NULL;
1908 struct lttcomm_relayd_generic_reply reply;
1909 struct relay_stream *stream;
1910 uint64_t net_seq_num;
1911
1912 assert(conn);
1913
1914 DBG("Relay receiving index");
1915
1916 if (!session || conn->version_check_done == 0) {
1917 ERR("Trying to close a stream before version check");
1918 ret = -1;
1919 goto end_no_session;
1920 }
1921
1922 ret = conn->sock->ops->recvmsg(conn->sock, &index_info,
1923 sizeof(index_info), 0);
1924 if (ret < sizeof(index_info)) {
1925 if (ret == 0) {
1926 /* Orderly shutdown. Not necessary to print an error. */
1927 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
1928 } else {
1929 ERR("Relay didn't receive valid index struct size : %d", ret);
1930 }
1931 ret = -1;
1932 goto end_no_session;
1933 }
1934
1935 net_seq_num = be64toh(index_info.net_seq_num);
1936
1937 rcu_read_lock();
1938 stream = stream_find_by_id(relay_streams_ht,
1939 be64toh(index_info.relay_stream_id));
1940 if (!stream) {
1941 ret = -1;
1942 goto end_rcu_unlock;
1943 }
1944
1945 /* Live beacon handling */
1946 if (index_info.packet_size == 0) {
1947 DBG("Received live beacon for stream %" PRIu64, stream->stream_handle);
1948
1949 /*
1950 * Only flag a stream inactive when it has already received data
1951 * and no indexes are in flight.
1952 */
1953 if (stream->total_index_received > 0 && stream->indexes_in_flight == 0) {
1954 stream->beacon_ts_end = be64toh(index_info.timestamp_end);
1955 }
1956 ret = 0;
1957 goto end_rcu_unlock;
1958 } else {
1959 stream->beacon_ts_end = -1ULL;
1960 }
1961
1962 index = relay_index_find(stream->stream_handle, net_seq_num);
1963 if (!index) {
1964 /* A successful creation will add the object to the HT. */
1965 index = relay_index_create(stream->stream_handle, net_seq_num);
1966 if (!index) {
1967 goto end_rcu_unlock;
1968 }
1969 index_created = 1;
1970 stream->indexes_in_flight++;
1971 }
1972
1973 copy_index_control_data(index, &index_info);
1974 if (stream->ctf_stream_id == -1ULL) {
1975 stream->ctf_stream_id = be64toh(index_info.stream_id);
1976 }
1977
1978 if (index_created) {
1979 /*
1980 * Try to add the relay index object to the hash table. If an object
1981 * already exist, destroy back the index created, set the data in this
1982 * object and write it on disk.
1983 */
1984 relay_index_add(index, &wr_index);
1985 if (wr_index) {
1986 copy_index_control_data(wr_index, &index_info);
1987 free(index);
1988 }
1989 } else {
1990 /* The index already exists so write it on disk. */
1991 wr_index = index;
1992 }
1993
1994 /* Do we have a writable ready index to write on disk. */
1995 if (wr_index) {
1996 ret = relay_index_write(wr_index->fd, wr_index);
1997 if (ret < 0) {
1998 goto end_rcu_unlock;
1999 }
2000 stream->total_index_received++;
2001 stream->indexes_in_flight--;
2002 assert(stream->indexes_in_flight >= 0);
2003 }
2004
2005 end_rcu_unlock:
2006 rcu_read_unlock();
2007
2008 memset(&reply, 0, sizeof(reply));
2009 if (ret < 0) {
2010 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2011 } else {
2012 reply.ret_code = htobe32(LTTNG_OK);
2013 }
2014 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2015 if (send_ret < 0) {
2016 ERR("Relay sending close index id reply");
2017 ret = send_ret;
2018 }
2019
2020 end_no_session:
2021 return ret;
2022 }
2023
2024 /*
2025 * Receive the streams_sent message.
2026 *
2027 * Return 0 on success else a negative value.
2028 */
2029 static
2030 int relay_streams_sent(struct lttcomm_relayd_hdr *recv_hdr,
2031 struct relay_connection *conn)
2032 {
2033 int ret, send_ret;
2034 struct lttcomm_relayd_generic_reply reply;
2035
2036 assert(conn);
2037
2038 DBG("Relay receiving streams_sent");
2039
2040 if (!conn->session || conn->version_check_done == 0) {
2041 ERR("Trying to close a stream before version check");
2042 ret = -1;
2043 goto end_no_session;
2044 }
2045
2046 /*
2047 * Flag every pending stream in the connection recv list that they are
2048 * ready to be used by the viewer.
2049 */
2050 set_viewer_ready_flag(conn);
2051
2052 /*
2053 * Inform the viewer that there are new streams in the session.
2054 */
2055 if (conn->session->viewer_refcount) {
2056 uatomic_set(&conn->session->new_streams, 1);
2057 }
2058
2059 memset(&reply, 0, sizeof(reply));
2060 reply.ret_code = htobe32(LTTNG_OK);
2061 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2062 if (send_ret < 0) {
2063 ERR("Relay sending sent_stream reply");
2064 ret = send_ret;
2065 } else {
2066 /* Success. */
2067 ret = 0;
2068 }
2069
2070 end_no_session:
2071 return ret;
2072 }
2073
2074 /*
2075 * Process the commands received on the control socket
2076 */
2077 static
2078 int relay_process_control(struct lttcomm_relayd_hdr *recv_hdr,
2079 struct relay_connection *conn)
2080 {
2081 int ret = 0;
2082
2083 switch (be32toh(recv_hdr->cmd)) {
2084 case RELAYD_CREATE_SESSION:
2085 ret = relay_create_session(recv_hdr, conn);
2086 break;
2087 case RELAYD_ADD_STREAM:
2088 ret = relay_add_stream(recv_hdr, conn);
2089 break;
2090 case RELAYD_START_DATA:
2091 ret = relay_start(recv_hdr, conn);
2092 break;
2093 case RELAYD_SEND_METADATA:
2094 ret = relay_recv_metadata(recv_hdr, conn);
2095 break;
2096 case RELAYD_VERSION:
2097 ret = relay_send_version(recv_hdr, conn);
2098 break;
2099 case RELAYD_CLOSE_STREAM:
2100 ret = relay_close_stream(recv_hdr, conn);
2101 break;
2102 case RELAYD_DATA_PENDING:
2103 ret = relay_data_pending(recv_hdr, conn);
2104 break;
2105 case RELAYD_QUIESCENT_CONTROL:
2106 ret = relay_quiescent_control(recv_hdr, conn);
2107 break;
2108 case RELAYD_BEGIN_DATA_PENDING:
2109 ret = relay_begin_data_pending(recv_hdr, conn);
2110 break;
2111 case RELAYD_END_DATA_PENDING:
2112 ret = relay_end_data_pending(recv_hdr, conn);
2113 break;
2114 case RELAYD_SEND_INDEX:
2115 ret = relay_recv_index(recv_hdr, conn);
2116 break;
2117 case RELAYD_STREAMS_SENT:
2118 ret = relay_streams_sent(recv_hdr, conn);
2119 break;
2120 case RELAYD_UPDATE_SYNC_INFO:
2121 default:
2122 ERR("Received unknown command (%u)", be32toh(recv_hdr->cmd));
2123 relay_unknown_command(conn);
2124 ret = -1;
2125 goto end;
2126 }
2127
2128 end:
2129 return ret;
2130 }
2131
2132 /*
2133 * Handle index for a data stream.
2134 *
2135 * RCU read side lock MUST be acquired.
2136 *
2137 * Return 0 on success else a negative value.
2138 */
2139 static int handle_index_data(struct relay_stream *stream, uint64_t net_seq_num,
2140 int rotate_index)
2141 {
2142 int ret = 0, index_created = 0;
2143 uint64_t stream_id, data_offset;
2144 struct relay_index *index, *wr_index = NULL;
2145
2146 assert(stream);
2147
2148 stream_id = stream->stream_handle;
2149 /* Get data offset because we are about to update the index. */
2150 data_offset = htobe64(stream->tracefile_size_current);
2151
2152 /*
2153 * Lookup for an existing index for that stream id/sequence number. If on
2154 * exists, the control thread already received the data for it thus we need
2155 * to write it on disk.
2156 */
2157 index = relay_index_find(stream_id, net_seq_num);
2158 if (!index) {
2159 /* A successful creation will add the object to the HT. */
2160 index = relay_index_create(stream_id, net_seq_num);
2161 if (!index) {
2162 ret = -1;
2163 goto error;
2164 }
2165 index_created = 1;
2166 stream->indexes_in_flight++;
2167 }
2168
2169 if (rotate_index || stream->index_fd < 0) {
2170 index->to_close_fd = stream->index_fd;
2171 ret = index_create_file(stream->path_name, stream->channel_name,
2172 relayd_uid, relayd_gid, stream->tracefile_size,
2173 stream->tracefile_count_current);
2174 if (ret < 0) {
2175 /* This will close the stream's index fd if one. */
2176 relay_index_free_safe(index);
2177 goto error;
2178 }
2179 stream->index_fd = ret;
2180 }
2181 index->fd = stream->index_fd;
2182 index->index_data.offset = data_offset;
2183
2184 if (index_created) {
2185 /*
2186 * Try to add the relay index object to the hash table. If an object
2187 * already exist, destroy back the index created and set the data.
2188 */
2189 relay_index_add(index, &wr_index);
2190 if (wr_index) {
2191 /* Copy back data from the created index. */
2192 wr_index->fd = index->fd;
2193 wr_index->to_close_fd = index->to_close_fd;
2194 wr_index->index_data.offset = data_offset;
2195 free(index);
2196 }
2197 } else {
2198 /* The index already exists so write it on disk. */
2199 wr_index = index;
2200 }
2201
2202 /* Do we have a writable ready index to write on disk. */
2203 if (wr_index) {
2204 ret = relay_index_write(wr_index->fd, wr_index);
2205 if (ret < 0) {
2206 goto error;
2207 }
2208 stream->total_index_received++;
2209 stream->indexes_in_flight--;
2210 assert(stream->indexes_in_flight >= 0);
2211 }
2212
2213 error:
2214 return ret;
2215 }
2216
2217 /*
2218 * relay_process_data: Process the data received on the data socket
2219 */
2220 static
2221 int relay_process_data(struct relay_connection *conn)
2222 {
2223 int ret = 0, rotate_index = 0;
2224 ssize_t size_ret;
2225 struct relay_stream *stream;
2226 struct lttcomm_relayd_data_hdr data_hdr;
2227 uint64_t stream_id;
2228 uint64_t net_seq_num;
2229 uint32_t data_size;
2230 struct relay_session *session;
2231
2232 assert(conn);
2233
2234 ret = conn->sock->ops->recvmsg(conn->sock, &data_hdr,
2235 sizeof(struct lttcomm_relayd_data_hdr), 0);
2236 if (ret <= 0) {
2237 if (ret == 0) {
2238 /* Orderly shutdown. Not necessary to print an error. */
2239 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
2240 } else {
2241 ERR("Unable to receive data header on sock %d", conn->sock->fd);
2242 }
2243 ret = -1;
2244 goto end;
2245 }
2246
2247 stream_id = be64toh(data_hdr.stream_id);
2248
2249 rcu_read_lock();
2250 stream = stream_find_by_id(relay_streams_ht, stream_id);
2251 if (!stream) {
2252 ret = -1;
2253 goto end_rcu_unlock;
2254 }
2255
2256 session = session_find_by_id(conn->sessions_ht, stream->session_id);
2257 assert(session);
2258
2259 data_size = be32toh(data_hdr.data_size);
2260 if (data_buffer_size < data_size) {
2261 char *tmp_data_ptr;
2262
2263 tmp_data_ptr = realloc(data_buffer, data_size);
2264 if (!tmp_data_ptr) {
2265 ERR("Allocating data buffer");
2266 free(data_buffer);
2267 ret = -1;
2268 goto end_rcu_unlock;
2269 }
2270 data_buffer = tmp_data_ptr;
2271 data_buffer_size = data_size;
2272 }
2273 memset(data_buffer, 0, data_size);
2274
2275 net_seq_num = be64toh(data_hdr.net_seq_num);
2276
2277 DBG3("Receiving data of size %u for stream id %" PRIu64 " seqnum %" PRIu64,
2278 data_size, stream_id, net_seq_num);
2279 ret = conn->sock->ops->recvmsg(conn->sock, data_buffer, data_size, 0);
2280 if (ret <= 0) {
2281 if (ret == 0) {
2282 /* Orderly shutdown. Not necessary to print an error. */
2283 DBG("Socket %d did an orderly shutdown", conn->sock->fd);
2284 }
2285 ret = -1;
2286 goto end_rcu_unlock;
2287 }
2288
2289 /* Check if a rotation is needed. */
2290 if (stream->tracefile_size > 0 &&
2291 (stream->tracefile_size_current + data_size) >
2292 stream->tracefile_size) {
2293 struct relay_viewer_stream *vstream;
2294 uint64_t new_id;
2295
2296 new_id = (stream->tracefile_count_current + 1) %
2297 stream->tracefile_count;
2298 /*
2299 * When we wrap-around back to 0, we start overwriting old
2300 * trace data.
2301 */
2302 if (!stream->tracefile_overwrite && new_id == 0) {
2303 stream->tracefile_overwrite = 1;
2304 }
2305 pthread_mutex_lock(&stream->viewer_stream_rotation_lock);
2306 if (stream->tracefile_overwrite) {
2307 stream->oldest_tracefile_id =
2308 (stream->oldest_tracefile_id + 1) %
2309 stream->tracefile_count;
2310 }
2311 vstream = viewer_stream_find_by_id(stream->stream_handle);
2312 if (vstream) {
2313 /*
2314 * The viewer is reading a file about to be
2315 * overwritten. Close the FDs it is
2316 * currently using and let it handle the fault.
2317 */
2318 if (vstream->tracefile_count_current == new_id) {
2319 pthread_mutex_lock(&vstream->overwrite_lock);
2320 vstream->abort_flag = 1;
2321 pthread_mutex_unlock(&vstream->overwrite_lock);
2322 DBG("Streaming side setting abort_flag on stream %s_%lu\n",
2323 stream->channel_name, new_id);
2324 } else if (vstream->tracefile_count_current ==
2325 stream->tracefile_count_current) {
2326 /*
2327 * The reader and writer were in the
2328 * same trace file, inform the viewer
2329 * that no new index will ever be added
2330 * to this file.
2331 */
2332 vstream->close_write_flag = 1;
2333 }
2334 }
2335 ret = utils_rotate_stream_file(stream->path_name, stream->channel_name,
2336 stream->tracefile_size, stream->tracefile_count,
2337 relayd_uid, relayd_gid, stream->fd,
2338 &(stream->tracefile_count_current), &stream->fd);
2339 pthread_mutex_unlock(&stream->viewer_stream_rotation_lock);
2340 if (ret < 0) {
2341 ERR("Rotating stream output file");
2342 goto end_rcu_unlock;
2343 }
2344 /* Reset current size because we just perform a stream rotation. */
2345 stream->tracefile_size_current = 0;
2346 rotate_index = 1;
2347 }
2348
2349 /*
2350 * Index are handled in protocol version 2.4 and above. Also, snapshot and
2351 * index are NOT supported.
2352 */
2353 if (session->minor >= 4 && !session->snapshot) {
2354 ret = handle_index_data(stream, net_seq_num, rotate_index);
2355 if (ret < 0) {
2356 goto end_rcu_unlock;
2357 }
2358 }
2359
2360 /* Write data to stream output fd. */
2361 size_ret = lttng_write(stream->fd, data_buffer, data_size);
2362 if (size_ret < data_size) {
2363 ERR("Relay error writing data to file");
2364 ret = -1;
2365 goto end_rcu_unlock;
2366 }
2367
2368 DBG2("Relay wrote %d bytes to tracefile for stream id %" PRIu64,
2369 ret, stream->stream_handle);
2370
2371 ret = write_padding_to_file(stream->fd, be32toh(data_hdr.padding_size));
2372 if (ret < 0) {
2373 goto end_rcu_unlock;
2374 }
2375 stream->tracefile_size_current += data_size + be32toh(data_hdr.padding_size);
2376
2377 stream->prev_seq = net_seq_num;
2378
2379 try_close_stream(session, stream);
2380
2381 end_rcu_unlock:
2382 rcu_read_unlock();
2383 end:
2384 return ret;
2385 }
2386
2387 static
2388 void cleanup_connection_pollfd(struct lttng_poll_event *events, int pollfd)
2389 {
2390 int ret;
2391
2392 assert(events);
2393
2394 (void) lttng_poll_del(events, pollfd);
2395
2396 ret = close(pollfd);
2397 if (ret < 0) {
2398 ERR("Closing pollfd %d", pollfd);
2399 }
2400 }
2401
2402 static void destroy_connection(struct lttng_ht *relay_connections_ht,
2403 struct relay_connection *conn)
2404 {
2405 assert(relay_connections_ht);
2406 assert(conn);
2407
2408 connection_delete(relay_connections_ht, conn);
2409
2410 /* For the control socket, we try to destroy the session. */
2411 if (conn->type == RELAY_CONTROL && conn->session) {
2412 destroy_session(conn->session, conn->sessions_ht);
2413 }
2414
2415 connection_destroy(conn);
2416 }
2417
2418 /*
2419 * This thread does the actual work
2420 */
2421 static
2422 void *relay_thread_worker(void *data)
2423 {
2424 int ret, err = -1, last_seen_data_fd = -1;
2425 uint32_t nb_fd;
2426 struct relay_connection *conn;
2427 struct lttng_poll_event events;
2428 struct lttng_ht *relay_connections_ht;
2429 struct lttng_ht_iter iter;
2430 struct lttcomm_relayd_hdr recv_hdr;
2431 struct relay_local_data *relay_ctx = (struct relay_local_data *) data;
2432 struct lttng_ht *sessions_ht = relay_ctx->sessions_ht;
2433 struct relay_index *index;
2434
2435 DBG("[thread] Relay worker started");
2436
2437 rcu_register_thread();
2438
2439 health_register(health_relayd, HEALTH_RELAYD_TYPE_WORKER);
2440
2441 if (testpoint(relayd_thread_worker)) {
2442 goto error_testpoint;
2443 }
2444
2445 health_code_update();
2446
2447 /* table of connections indexed on socket */
2448 relay_connections_ht = lttng_ht_new(0, LTTNG_HT_TYPE_ULONG);
2449 if (!relay_connections_ht) {
2450 goto relay_connections_ht_error;
2451 }
2452
2453 /* Tables of received indexes indexed by index handle and net_seq_num. */
2454 indexes_ht = lttng_ht_new(0, LTTNG_HT_TYPE_TWO_U64);
2455 if (!indexes_ht) {
2456 goto indexes_ht_error;
2457 }
2458
2459 ret = create_thread_poll_set(&events, 2);
2460 if (ret < 0) {
2461 goto error_poll_create;
2462 }
2463
2464 ret = lttng_poll_add(&events, relay_conn_pipe[0], LPOLLIN | LPOLLRDHUP);
2465 if (ret < 0) {
2466 goto error;
2467 }
2468
2469 restart:
2470 while (1) {
2471 int idx = -1, i, seen_control = 0, last_notdel_data_fd = -1;
2472
2473 health_code_update();
2474
2475 /* Infinite blocking call, waiting for transmission */
2476 DBG3("Relayd worker thread polling...");
2477 health_poll_entry();
2478 ret = lttng_poll_wait(&events, -1);
2479 health_poll_exit();
2480 if (ret < 0) {
2481 /*
2482 * Restart interrupted system call.
2483 */
2484 if (errno == EINTR) {
2485 goto restart;
2486 }
2487 goto error;
2488 }
2489
2490 nb_fd = ret;
2491
2492 /*
2493 * Process control. The control connection is prioritised so we don't
2494 * starve it with high throughout put tracing data on the data
2495 * connection.
2496 */
2497 for (i = 0; i < nb_fd; i++) {
2498 /* Fetch once the poll data */
2499 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
2500 int pollfd = LTTNG_POLL_GETFD(&events, i);
2501
2502 health_code_update();
2503
2504 /* Thread quit pipe has been closed. Killing thread. */
2505 ret = check_thread_quit_pipe(pollfd, revents);
2506 if (ret) {
2507 err = 0;
2508 goto exit;
2509 }
2510
2511 /* Inspect the relay conn pipe for new connection */
2512 if (pollfd == relay_conn_pipe[0]) {
2513 if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2514 ERR("Relay connection pipe error");
2515 goto error;
2516 } else if (revents & LPOLLIN) {
2517 ret = lttng_read(relay_conn_pipe[0], &conn, sizeof(conn));
2518 if (ret < 0) {
2519 goto error;
2520 }
2521 conn->sessions_ht = sessions_ht;
2522 connection_init(conn);
2523 lttng_poll_add(&events, conn->sock->fd,
2524 LPOLLIN | LPOLLRDHUP);
2525 rcu_read_lock();
2526 lttng_ht_add_unique_ulong(relay_connections_ht,
2527 &conn->sock_n);
2528 rcu_read_unlock();
2529 DBG("Connection socket %d added", conn->sock->fd);
2530 }
2531 } else {
2532 rcu_read_lock();
2533 conn = connection_find_by_sock(relay_connections_ht, pollfd);
2534 /* If not found, there is a synchronization issue. */
2535 assert(conn);
2536
2537 if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2538 cleanup_connection_pollfd(&events, pollfd);
2539 destroy_connection(relay_connections_ht, conn);
2540 if (last_seen_data_fd == pollfd) {
2541 last_seen_data_fd = last_notdel_data_fd;
2542 }
2543 } else if (revents & LPOLLIN) {
2544 if (conn->type == RELAY_CONTROL) {
2545 ret = conn->sock->ops->recvmsg(conn->sock, &recv_hdr,
2546 sizeof(recv_hdr), 0);
2547 if (ret <= 0) {
2548 /* Connection closed */
2549 cleanup_connection_pollfd(&events, pollfd);
2550 destroy_connection(relay_connections_ht, conn);
2551 DBG("Control connection closed with %d", pollfd);
2552 } else {
2553 ret = relay_process_control(&recv_hdr, conn);
2554 if (ret < 0) {
2555 /* Clear the session on error. */
2556 cleanup_connection_pollfd(&events, pollfd);
2557 destroy_connection(relay_connections_ht, conn);
2558 DBG("Connection closed with %d", pollfd);
2559 }
2560 seen_control = 1;
2561 }
2562 } else {
2563 /*
2564 * Flag the last seen data fd not deleted. It will be
2565 * used as the last seen fd if any fd gets deleted in
2566 * this first loop.
2567 */
2568 last_notdel_data_fd = pollfd;
2569 }
2570 } else {
2571 ERR("Unknown poll events %u for sock %d", revents, pollfd);
2572 }
2573 rcu_read_unlock();
2574 }
2575 }
2576
2577 /*
2578 * The last loop handled a control request, go back to poll to make
2579 * sure we prioritise the control socket.
2580 */
2581 if (seen_control) {
2582 continue;
2583 }
2584
2585 if (last_seen_data_fd >= 0) {
2586 for (i = 0; i < nb_fd; i++) {
2587 int pollfd = LTTNG_POLL_GETFD(&events, i);
2588
2589 health_code_update();
2590
2591 if (last_seen_data_fd == pollfd) {
2592 idx = i;
2593 break;
2594 }
2595 }
2596 }
2597
2598 /* Process data connection. */
2599 for (i = idx + 1; i < nb_fd; i++) {
2600 /* Fetch the poll data. */
2601 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
2602 int pollfd = LTTNG_POLL_GETFD(&events, i);
2603
2604 health_code_update();
2605
2606 /* Skip the command pipe. It's handled in the first loop. */
2607 if (pollfd == relay_conn_pipe[0]) {
2608 continue;
2609 }
2610
2611 if (revents) {
2612 rcu_read_lock();
2613 conn = connection_find_by_sock(relay_connections_ht, pollfd);
2614 if (!conn) {
2615 /* Skip it. Might be removed before. */
2616 rcu_read_unlock();
2617 continue;
2618 }
2619
2620 if (revents & LPOLLIN) {
2621 if (conn->type != RELAY_DATA) {
2622 rcu_read_unlock();
2623 continue;
2624 }
2625
2626 ret = relay_process_data(conn);
2627 /* Connection closed */
2628 if (ret < 0) {
2629 cleanup_connection_pollfd(&events, pollfd);
2630 destroy_connection(relay_connections_ht, conn);
2631 DBG("Data connection closed with %d", pollfd);
2632 /*
2633 * Every goto restart call sets the last seen fd where
2634 * here we don't really care since we gracefully
2635 * continue the loop after the connection is deleted.
2636 */
2637 } else {
2638 /* Keep last seen port. */
2639 last_seen_data_fd = pollfd;
2640 rcu_read_unlock();
2641 goto restart;
2642 }
2643 }
2644 rcu_read_unlock();
2645 }
2646 }
2647 last_seen_data_fd = -1;
2648 }
2649
2650 /* Normal exit, no error */
2651 ret = 0;
2652
2653 exit:
2654 error:
2655 lttng_poll_clean(&events);
2656
2657 /* Cleanup reamaining connection object. */
2658 rcu_read_lock();
2659 cds_lfht_for_each_entry(relay_connections_ht->ht, &iter.iter, conn,
2660 sock_n.node) {
2661 health_code_update();
2662 destroy_connection(relay_connections_ht, conn);
2663 }
2664 rcu_read_unlock();
2665 error_poll_create:
2666 rcu_read_lock();
2667 cds_lfht_for_each_entry(indexes_ht->ht, &iter.iter, index,
2668 index_n.node) {
2669 health_code_update();
2670 relay_index_delete(index);
2671 relay_index_free_safe(index);
2672 }
2673 rcu_read_unlock();
2674 lttng_ht_destroy(indexes_ht);
2675 indexes_ht_error:
2676 lttng_ht_destroy(relay_connections_ht);
2677 relay_connections_ht_error:
2678 /* Close relay conn pipes */
2679 utils_close_pipe(relay_conn_pipe);
2680 if (err) {
2681 DBG("Thread exited with error");
2682 }
2683 DBG("Worker thread cleanup complete");
2684 free(data_buffer);
2685 error_testpoint:
2686 if (err) {
2687 health_error();
2688 ERR("Health error occurred in %s", __func__);
2689 }
2690 health_unregister(health_relayd);
2691 rcu_unregister_thread();
2692 stop_threads();
2693 return NULL;
2694 }
2695
2696 /*
2697 * Create the relay command pipe to wake thread_manage_apps.
2698 * Closed in cleanup().
2699 */
2700 static int create_relay_conn_pipe(void)
2701 {
2702 int ret;
2703
2704 ret = utils_create_pipe_cloexec(relay_conn_pipe);
2705
2706 return ret;
2707 }
2708
2709 /*
2710 * main
2711 */
2712 int main(int argc, char **argv)
2713 {
2714 int ret = 0;
2715 void *status;
2716 struct relay_local_data *relay_ctx;
2717
2718 /* Parse arguments */
2719 progname = argv[0];
2720 if ((ret = set_options(argc, argv)) < 0) {
2721 goto exit;
2722 }
2723
2724 if ((ret = set_signal_handler()) < 0) {
2725 goto exit;
2726 }
2727
2728 /* Try to create directory if -o, --output is specified. */
2729 if (opt_output_path) {
2730 if (*opt_output_path != '/') {
2731 ERR("Please specify an absolute path for -o, --output PATH");
2732 goto exit;
2733 }
2734
2735 ret = utils_mkdir_recursive(opt_output_path, S_IRWXU | S_IRWXG);
2736 if (ret < 0) {
2737 ERR("Unable to create %s", opt_output_path);
2738 goto exit;
2739 }
2740 }
2741
2742 /* Daemonize */
2743 if (opt_daemon || opt_background) {
2744 int i;
2745
2746 ret = lttng_daemonize(&child_ppid, &recv_child_signal,
2747 !opt_background);
2748 if (ret < 0) {
2749 goto exit;
2750 }
2751
2752 /*
2753 * We are in the child. Make sure all other file
2754 * descriptors are closed, in case we are called with
2755 * more opened file descriptors than the standard ones.
2756 */
2757 for (i = 3; i < sysconf(_SC_OPEN_MAX); i++) {
2758 (void) close(i);
2759 }
2760 }
2761
2762 /* Create thread quit pipe */
2763 if ((ret = init_thread_quit_pipe()) < 0) {
2764 goto error;
2765 }
2766
2767 /* We need those values for the file/dir creation. */
2768 relayd_uid = getuid();
2769 relayd_gid = getgid();
2770
2771 /* Check if daemon is UID = 0 */
2772 if (relayd_uid == 0) {
2773 if (control_uri->port < 1024 || data_uri->port < 1024 || live_uri->port < 1024) {
2774 ERR("Need to be root to use ports < 1024");
2775 ret = -1;
2776 goto exit;
2777 }
2778 }
2779
2780 /* Setup the thread apps communication pipe. */
2781 if ((ret = create_relay_conn_pipe()) < 0) {
2782 goto exit;
2783 }
2784
2785 /* Init relay command queue. */
2786 cds_wfq_init(&relay_conn_queue.queue);
2787
2788 /* Set up max poll set size */
2789 lttng_poll_set_max_size();
2790
2791 /* Initialize communication library */
2792 lttcomm_init();
2793 lttcomm_inet_init();
2794
2795 relay_ctx = zmalloc(sizeof(struct relay_local_data));
2796 if (!relay_ctx) {
2797 PERROR("relay_ctx");
2798 goto exit;
2799 }
2800
2801 /* tables of sessions indexed by session ID */
2802 relay_ctx->sessions_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
2803 if (!relay_ctx->sessions_ht) {
2804 goto exit_relay_ctx_sessions;
2805 }
2806
2807 /* tables of streams indexed by stream ID */
2808 relay_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
2809 if (!relay_streams_ht) {
2810 goto exit_relay_ctx_streams;
2811 }
2812
2813 /* tables of streams indexed by stream ID */
2814 viewer_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
2815 if (!viewer_streams_ht) {
2816 goto exit_relay_ctx_viewer_streams;
2817 }
2818
2819 /* Initialize thread health monitoring */
2820 health_relayd = health_app_create(NR_HEALTH_RELAYD_TYPES);
2821 if (!health_relayd) {
2822 PERROR("health_app_create error");
2823 goto exit_health_app_create;
2824 }
2825
2826 ret = utils_create_pipe(health_quit_pipe);
2827 if (ret < 0) {
2828 goto error_health_pipe;
2829 }
2830
2831 /* Create thread to manage the client socket */
2832 ret = pthread_create(&health_thread, NULL,
2833 thread_manage_health, (void *) NULL);
2834 if (ret != 0) {
2835 PERROR("pthread_create health");
2836 goto health_error;
2837 }
2838
2839 /* Setup the dispatcher thread */
2840 ret = pthread_create(&dispatcher_thread, NULL,
2841 relay_thread_dispatcher, (void *) NULL);
2842 if (ret != 0) {
2843 PERROR("pthread_create dispatcher");
2844 goto exit_dispatcher;
2845 }
2846
2847 /* Setup the worker thread */
2848 ret = pthread_create(&worker_thread, NULL,
2849 relay_thread_worker, (void *) relay_ctx);
2850 if (ret != 0) {
2851 PERROR("pthread_create worker");
2852 goto exit_worker;
2853 }
2854
2855 /* Setup the listener thread */
2856 ret = pthread_create(&listener_thread, NULL,
2857 relay_thread_listener, (void *) NULL);
2858 if (ret != 0) {
2859 PERROR("pthread_create listener");
2860 goto exit_listener;
2861 }
2862
2863 ret = live_start_threads(live_uri, relay_ctx);
2864 if (ret != 0) {
2865 ERR("Starting live viewer threads");
2866 goto exit_live;
2867 }
2868
2869 exit_live:
2870 ret = pthread_join(listener_thread, &status);
2871 if (ret != 0) {
2872 PERROR("pthread_join");
2873 goto error; /* join error, exit without cleanup */
2874 }
2875
2876 exit_listener:
2877 ret = pthread_join(worker_thread, &status);
2878 if (ret != 0) {
2879 PERROR("pthread_join");
2880 goto error; /* join error, exit without cleanup */
2881 }
2882
2883 exit_worker:
2884 ret = pthread_join(dispatcher_thread, &status);
2885 if (ret != 0) {
2886 PERROR("pthread_join");
2887 goto error; /* join error, exit without cleanup */
2888 }
2889
2890 exit_dispatcher:
2891 ret = pthread_join(health_thread, &status);
2892 if (ret != 0) {
2893 PERROR("pthread_join health thread");
2894 goto error; /* join error, exit without cleanup */
2895 }
2896
2897 /*
2898 * Stop live threads only after joining other threads.
2899 */
2900 live_stop_threads();
2901
2902 health_error:
2903 utils_close_pipe(health_quit_pipe);
2904
2905 error_health_pipe:
2906 health_app_destroy(health_relayd);
2907
2908 exit_health_app_create:
2909 lttng_ht_destroy(viewer_streams_ht);
2910
2911 exit_relay_ctx_viewer_streams:
2912 lttng_ht_destroy(relay_streams_ht);
2913
2914 exit_relay_ctx_streams:
2915 lttng_ht_destroy(relay_ctx->sessions_ht);
2916
2917 exit_relay_ctx_sessions:
2918 free(relay_ctx);
2919
2920 exit:
2921 cleanup();
2922 if (!ret) {
2923 exit(EXIT_SUCCESS);
2924 }
2925
2926 error:
2927 exit(EXIT_FAILURE);
2928 }
This page took 0.156735 seconds and 4 git commands to generate.