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