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