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