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