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