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