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