Backport: Introduce LTTNG_RELAYD_WORKING_DIRECTORY environment variable
[lttng-tools.git] / src / bin / lttng-relayd / main.c
CommitLineData
b8aa1682
JD
1/*
2 * Copyright (C) 2012 - Julien Desfossez <jdesfossez@efficios.com>
3 * David Goulet <dgoulet@efficios.com>
cd60b05a 4 * 2013 - Jérémie Galarneau <jeremie.galarneau@efficios.com>
7591bab1 5 * 2015 - Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
b8aa1682
JD
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License, version 2 only,
9 * as published by the Free Software Foundation.
10 *
11 * This program is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
14 * more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
6c1c0768 21#define _LGPL_SOURCE
b8aa1682
JD
22#include <getopt.h>
23#include <grp.h>
24#include <limits.h>
25#include <pthread.h>
26#include <signal.h>
27#include <stdio.h>
28#include <stdlib.h>
29#include <string.h>
30#include <sys/mman.h>
31#include <sys/mount.h>
32#include <sys/resource.h>
33#include <sys/socket.h>
34#include <sys/stat.h>
35#include <sys/types.h>
36#include <sys/wait.h>
173af62f 37#include <inttypes.h>
b8aa1682
JD
38#include <urcu/futex.h>
39#include <urcu/uatomic.h>
40#include <unistd.h>
41#include <fcntl.h>
b8aa1682
JD
42
43#include <lttng/lttng.h>
44#include <common/common.h>
45#include <common/compat/poll.h>
46#include <common/compat/socket.h>
f263b7fd 47#include <common/compat/endian.h>
e8fa9fb0 48#include <common/compat/getenv.h>
b8aa1682 49#include <common/defaults.h>
3fd27398 50#include <common/daemonize.h>
b8aa1682
JD
51#include <common/futex.h>
52#include <common/sessiond-comm/sessiond-comm.h>
53#include <common/sessiond-comm/inet.h>
b8aa1682
JD
54#include <common/sessiond-comm/relayd.h>
55#include <common/uri.h>
a02de639 56#include <common/utils.h>
f40ef1d5 57#include <common/config/session-config.h>
44a2fbf1
JG
58#include <common/dynamic-buffer.h>
59#include <common/buffer-view.h>
7591bab1 60#include <urcu/rculist.h>
b8aa1682 61
0f907de1 62#include "cmd.h"
d3e2ba59 63#include "ctf-trace.h"
1c20f0e2 64#include "index.h"
0f907de1 65#include "utils.h"
b8aa1682 66#include "lttng-relayd.h"
d3e2ba59 67#include "live.h"
55706a7d 68#include "health-relayd.h"
9b5e0863 69#include "testpoint.h"
2f8f53af 70#include "viewer-stream.h"
2a174661
DG
71#include "session.h"
72#include "stream.h"
58eb9381 73#include "connection.h"
a44ca2ca 74#include "tracefile-array.h"
2fc6b1ab 75#include "tcp_keep_alive.h"
b8aa1682 76
44a2fbf1
JG
77enum relay_connection_status {
78 RELAY_CONNECTION_STATUS_OK,
79 /* An error occured while processing an event on the connection. */
80 RELAY_CONNECTION_STATUS_ERROR,
81 /* Connection closed/shutdown cleanly. */
82 RELAY_CONNECTION_STATUS_CLOSED,
83};
84
b8aa1682 85/* command line options */
76375580 86char *opt_output_path, *opt_working_directory;
b5218ffb 87static int opt_daemon, opt_background;
3fd27398
MD
88
89/*
90 * We need to wait for listener and live listener threads, as well as
91 * health check thread, before being ready to signal readiness.
92 */
93#define NR_LTTNG_RELAY_READY 3
94static int lttng_relay_ready = NR_LTTNG_RELAY_READY;
0848dba7
MD
95
96/* Size of receive buffer. */
97#define RECV_DATA_BUFFER_SIZE 65536
98
3fd27398
MD
99static int recv_child_signal; /* Set to 1 when a SIGUSR1 signal is received. */
100static pid_t child_ppid; /* Internal parent PID use with daemonize. */
101
095a4ae5
MD
102static struct lttng_uri *control_uri;
103static struct lttng_uri *data_uri;
d3e2ba59 104static struct lttng_uri *live_uri;
b8aa1682
JD
105
106const char *progname;
b8aa1682 107
65931c8b 108const char *tracing_group_name = DEFAULT_TRACING_GROUP;
cd60b05a
JG
109static int tracing_group_name_override;
110
111const char * const config_section_name = "relayd";
65931c8b 112
b8aa1682
JD
113/*
114 * Quit pipe for all threads. This permits a single cancellation point
115 * for all threads when receiving an event on the pipe.
116 */
0b242f62 117int thread_quit_pipe[2] = { -1, -1 };
b8aa1682
JD
118
119/*
120 * This pipe is used to inform the worker thread that a command is queued and
121 * ready to be processed.
122 */
58eb9381 123static int relay_conn_pipe[2] = { -1, -1 };
b8aa1682 124
26c9d55e 125/* Shared between threads */
b8aa1682
JD
126static int dispatch_thread_exit;
127
128static pthread_t listener_thread;
129static pthread_t dispatcher_thread;
130static pthread_t worker_thread;
65931c8b 131static pthread_t health_thread;
b8aa1682 132
7591bab1
MD
133/*
134 * last_relay_stream_id_lock protects last_relay_stream_id increment
135 * atomicity on 32-bit architectures.
136 */
137static pthread_mutex_t last_relay_stream_id_lock = PTHREAD_MUTEX_INITIALIZER;
095a4ae5 138static uint64_t last_relay_stream_id;
b8aa1682
JD
139
140/*
141 * Relay command queue.
142 *
143 * The relay_thread_listener and relay_thread_dispatcher communicate with this
144 * queue.
145 */
58eb9381 146static struct relay_conn_queue relay_conn_queue;
b8aa1682 147
d3e2ba59
JD
148/* Global relay stream hash table. */
149struct lttng_ht *relay_streams_ht;
150
92c6ca54
DG
151/* Global relay viewer stream hash table. */
152struct lttng_ht *viewer_streams_ht;
153
7591bab1
MD
154/* Global relay sessions hash table. */
155struct lttng_ht *sessions_ht;
0a6518b0 156
55706a7d 157/* Relayd health monitoring */
eea7556c 158struct health_app *health_relayd;
55706a7d 159
cd60b05a
JG
160static struct option long_options[] = {
161 { "control-port", 1, 0, 'C', },
162 { "data-port", 1, 0, 'D', },
8d5c808e 163 { "live-port", 1, 0, 'L', },
cd60b05a 164 { "daemonize", 0, 0, 'd', },
b5218ffb 165 { "background", 0, 0, 'b', },
cd60b05a
JG
166 { "group", 1, 0, 'g', },
167 { "help", 0, 0, 'h', },
168 { "output", 1, 0, 'o', },
169 { "verbose", 0, 0, 'v', },
170 { "config", 1, 0, 'f' },
297af7ff 171 { "version", 0, 0, 'V' },
76375580 172 { "working-directory", 1, 0, 'w', },
cd60b05a
JG
173 { NULL, 0, 0, 0, },
174};
175
297af7ff 176static const char *config_ignore_options[] = { "help", "config", "version" };
cd60b05a 177
cd60b05a
JG
178/*
179 * Take an option from the getopt output and set it in the right variable to be
180 * used later.
181 *
182 * Return 0 on success else a negative value.
183 */
7591bab1 184static int set_option(int opt, const char *arg, const char *optname)
b8aa1682 185{
cd60b05a
JG
186 int ret;
187
188 switch (opt) {
189 case 0:
190 fprintf(stderr, "option %s", optname);
191 if (arg) {
192 fprintf(stderr, " with arg %s\n", arg);
193 }
194 break;
195 case 'C':
e8fa9fb0
MD
196 if (lttng_is_setuid_setgid()) {
197 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
198 "-C, --control-port");
199 } else {
200 ret = uri_parse(arg, &control_uri);
201 if (ret < 0) {
202 ERR("Invalid control URI specified");
203 goto end;
204 }
205 if (control_uri->port == 0) {
206 control_uri->port = DEFAULT_NETWORK_CONTROL_PORT;
207 }
cd60b05a
JG
208 }
209 break;
210 case 'D':
e8fa9fb0
MD
211 if (lttng_is_setuid_setgid()) {
212 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
213 "-D, -data-port");
214 } else {
215 ret = uri_parse(arg, &data_uri);
216 if (ret < 0) {
217 ERR("Invalid data URI specified");
218 goto end;
219 }
220 if (data_uri->port == 0) {
221 data_uri->port = DEFAULT_NETWORK_DATA_PORT;
222 }
cd60b05a
JG
223 }
224 break;
8d5c808e 225 case 'L':
e8fa9fb0
MD
226 if (lttng_is_setuid_setgid()) {
227 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
228 "-L, -live-port");
229 } else {
230 ret = uri_parse(arg, &live_uri);
231 if (ret < 0) {
232 ERR("Invalid live URI specified");
233 goto end;
234 }
235 if (live_uri->port == 0) {
236 live_uri->port = DEFAULT_NETWORK_VIEWER_PORT;
237 }
8d5c808e
AM
238 }
239 break;
cd60b05a
JG
240 case 'd':
241 opt_daemon = 1;
242 break;
b5218ffb
MD
243 case 'b':
244 opt_background = 1;
245 break;
cd60b05a 246 case 'g':
e8fa9fb0
MD
247 if (lttng_is_setuid_setgid()) {
248 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
249 "-g, --group");
250 } else {
251 tracing_group_name = strdup(arg);
252 if (tracing_group_name == NULL) {
253 ret = -errno;
254 PERROR("strdup");
255 goto end;
256 }
257 tracing_group_name_override = 1;
330a40bb 258 }
cd60b05a
JG
259 break;
260 case 'h':
655b5cc1
PP
261 ret = utils_show_man_page(8, "lttng-relayd");
262 if (ret) {
263 ERR("Cannot view man page lttng-relayd(8)");
264 perror("exec");
265 }
cd60b05a 266 exit(EXIT_FAILURE);
297af7ff
AW
267 case 'V':
268 fprintf(stdout, "%s\n", VERSION);
269 exit(EXIT_SUCCESS);
cd60b05a 270 case 'o':
e8fa9fb0
MD
271 if (lttng_is_setuid_setgid()) {
272 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
273 "-o, --output");
274 } else {
275 ret = asprintf(&opt_output_path, "%s", arg);
276 if (ret < 0) {
277 ret = -errno;
278 PERROR("asprintf opt_output_path");
279 goto end;
280 }
cd60b05a
JG
281 }
282 break;
76375580
JR
283 case 'w':
284 if (lttng_is_setuid_setgid()) {
285 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
286 "-w, --working-directory");
287 } else {
288 ret = asprintf(&opt_working_directory, "%s", arg);
289 if (ret < 0) {
290 ret = -errno;
291 PERROR("asprintf working_directory");
292 goto end;
293 }
294 }
295 break;
296
cd60b05a
JG
297 case 'v':
298 /* Verbose level can increase using multiple -v */
299 if (arg) {
300 lttng_opt_verbose = config_parse_value(arg);
301 } else {
849e5b7b
DG
302 /* Only 3 level of verbosity (-vvv). */
303 if (lttng_opt_verbose < 3) {
304 lttng_opt_verbose += 1;
305 }
cd60b05a
JG
306 }
307 break;
308 default:
309 /* Unknown option or other error.
310 * Error is printed by getopt, just return */
311 ret = -1;
312 goto end;
313 }
314
315 /* All good. */
316 ret = 0;
317
318end:
319 return ret;
320}
321
322/*
323 * config_entry_handler_cb used to handle options read from a config file.
f40ef1d5 324 * See config_entry_handler_cb comment in common/config/session-config.h for the
cd60b05a
JG
325 * return value conventions.
326 */
7591bab1 327static int config_entry_handler(const struct config_entry *entry, void *unused)
cd60b05a
JG
328{
329 int ret = 0, i;
330
331 if (!entry || !entry->name || !entry->value) {
332 ret = -EINVAL;
333 goto end;
334 }
335
336 /* Check if the option is to be ignored */
337 for (i = 0; i < sizeof(config_ignore_options) / sizeof(char *); i++) {
338 if (!strcmp(entry->name, config_ignore_options[i])) {
339 goto end;
340 }
341 }
342
343 for (i = 0; i < (sizeof(long_options) / sizeof(struct option)) - 1; i++) {
344 /* Ignore if entry name is not fully matched. */
345 if (strcmp(entry->name, long_options[i].name)) {
346 continue;
347 }
348
349 /*
7591bab1
MD
350 * If the option takes no argument on the command line,
351 * we have to check if the value is "true". We support
352 * non-zero numeric values, true, on and yes.
cd60b05a
JG
353 */
354 if (!long_options[i].has_arg) {
355 ret = config_parse_value(entry->value);
356 if (ret <= 0) {
357 if (ret) {
358 WARN("Invalid configuration value \"%s\" for option %s",
359 entry->value, entry->name);
360 }
361 /* False, skip boolean config option. */
362 goto end;
363 }
364 }
365
366 ret = set_option(long_options[i].val, entry->value, entry->name);
367 goto end;
368 }
369
370 WARN("Unrecognized option \"%s\" in daemon configuration file.",
371 entry->name);
372
373end:
374 return ret;
375}
376
c7cc870e
JR
377static void parse_env_options(void)
378{
379 char *value = NULL;
380
381 value = lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV);
382 if (value) {
383 opt_working_directory = value;
384 }
385}
386
7591bab1 387static int set_options(int argc, char **argv)
cd60b05a 388{
178a0557 389 int c, ret = 0, option_index = 0, retval = 0;
cd60b05a
JG
390 int orig_optopt = optopt, orig_optind = optind;
391 char *default_address, *optstring;
392 const char *config_path = NULL;
393
394 optstring = utils_generate_optstring(long_options,
395 sizeof(long_options) / sizeof(struct option));
396 if (!optstring) {
178a0557 397 retval = -ENOMEM;
cd60b05a
JG
398 goto exit;
399 }
400
401 /* Check for the --config option */
402
403 while ((c = getopt_long(argc, argv, optstring, long_options,
404 &option_index)) != -1) {
405 if (c == '?') {
178a0557 406 retval = -EINVAL;
cd60b05a
JG
407 goto exit;
408 } else if (c != 'f') {
409 continue;
410 }
411
e8fa9fb0
MD
412 if (lttng_is_setuid_setgid()) {
413 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
414 "-f, --config");
415 } else {
416 config_path = utils_expand_path(optarg);
417 if (!config_path) {
418 ERR("Failed to resolve path: %s", optarg);
419 }
cd60b05a
JG
420 }
421 }
422
423 ret = config_get_section_entries(config_path, config_section_name,
424 config_entry_handler, NULL);
425 if (ret) {
426 if (ret > 0) {
427 ERR("Invalid configuration option at line %i", ret);
cd60b05a 428 }
178a0557 429 retval = -1;
cd60b05a
JG
430 goto exit;
431 }
b8aa1682 432
cd60b05a
JG
433 /* Reset getopt's global state */
434 optopt = orig_optopt;
435 optind = orig_optind;
b8aa1682 436 while (1) {
cd60b05a 437 c = getopt_long(argc, argv, optstring, long_options, &option_index);
b8aa1682
JD
438 if (c == -1) {
439 break;
440 }
441
cd60b05a
JG
442 ret = set_option(c, optarg, long_options[option_index].name);
443 if (ret < 0) {
178a0557 444 retval = -1;
b8aa1682
JD
445 goto exit;
446 }
447 }
448
449 /* assign default values */
450 if (control_uri == NULL) {
fa91dc52
MD
451 ret = asprintf(&default_address,
452 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS ":%d",
453 DEFAULT_NETWORK_CONTROL_PORT);
b8aa1682
JD
454 if (ret < 0) {
455 PERROR("asprintf default data address");
178a0557 456 retval = -1;
b8aa1682
JD
457 goto exit;
458 }
459
460 ret = uri_parse(default_address, &control_uri);
461 free(default_address);
462 if (ret < 0) {
463 ERR("Invalid control URI specified");
178a0557 464 retval = -1;
b8aa1682
JD
465 goto exit;
466 }
467 }
468 if (data_uri == NULL) {
fa91dc52
MD
469 ret = asprintf(&default_address,
470 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS ":%d",
471 DEFAULT_NETWORK_DATA_PORT);
b8aa1682
JD
472 if (ret < 0) {
473 PERROR("asprintf default data address");
178a0557 474 retval = -1;
b8aa1682
JD
475 goto exit;
476 }
477
478 ret = uri_parse(default_address, &data_uri);
479 free(default_address);
480 if (ret < 0) {
481 ERR("Invalid data URI specified");
178a0557 482 retval = -1;
b8aa1682
JD
483 goto exit;
484 }
485 }
d3e2ba59 486 if (live_uri == NULL) {
fa91dc52
MD
487 ret = asprintf(&default_address,
488 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS ":%d",
489 DEFAULT_NETWORK_VIEWER_PORT);
d3e2ba59
JD
490 if (ret < 0) {
491 PERROR("asprintf default viewer control address");
178a0557 492 retval = -1;
d3e2ba59
JD
493 goto exit;
494 }
495
496 ret = uri_parse(default_address, &live_uri);
497 free(default_address);
498 if (ret < 0) {
499 ERR("Invalid viewer control URI specified");
178a0557 500 retval = -1;
d3e2ba59
JD
501 goto exit;
502 }
503 }
b8aa1682
JD
504
505exit:
cd60b05a 506 free(optstring);
178a0557 507 return retval;
b8aa1682
JD
508}
509
7591bab1
MD
510static void print_global_objects(void)
511{
512 rcu_register_thread();
513
514 print_viewer_streams();
515 print_relay_streams();
516 print_sessions();
517
518 rcu_unregister_thread();
519}
520
b8aa1682
JD
521/*
522 * Cleanup the daemon
523 */
7591bab1 524static void relayd_cleanup(void)
b8aa1682 525{
7591bab1
MD
526 print_global_objects();
527
b8aa1682
JD
528 DBG("Cleaning up");
529
178a0557
MD
530 if (viewer_streams_ht)
531 lttng_ht_destroy(viewer_streams_ht);
532 if (relay_streams_ht)
533 lttng_ht_destroy(relay_streams_ht);
7591bab1
MD
534 if (sessions_ht)
535 lttng_ht_destroy(sessions_ht);
178a0557 536
095a4ae5
MD
537 /* free the dynamically allocated opt_output_path */
538 free(opt_output_path);
539
a02de639
CB
540 /* Close thread quit pipes */
541 utils_close_pipe(thread_quit_pipe);
542
710c1f73
DG
543 uri_free(control_uri);
544 uri_free(data_uri);
8d5c808e 545 /* Live URI is freed in the live thread. */
cd60b05a
JG
546
547 if (tracing_group_name_override) {
548 free((void *) tracing_group_name);
549 }
b8aa1682
JD
550}
551
552/*
553 * Write to writable pipe used to notify a thread.
554 */
7591bab1 555static int notify_thread_pipe(int wpipe)
b8aa1682 556{
6cd525e8 557 ssize_t ret;
b8aa1682 558
6cd525e8
MD
559 ret = lttng_write(wpipe, "!", 1);
560 if (ret < 1) {
b8aa1682 561 PERROR("write poll pipe");
b4aacfdc 562 goto end;
b8aa1682 563 }
b4aacfdc
MD
564 ret = 0;
565end:
b8aa1682
JD
566 return ret;
567}
568
7591bab1 569static int notify_health_quit_pipe(int *pipe)
65931c8b 570{
6cd525e8 571 ssize_t ret;
65931c8b 572
6cd525e8
MD
573 ret = lttng_write(pipe[1], "4", 1);
574 if (ret < 1) {
65931c8b 575 PERROR("write relay health quit");
b4aacfdc 576 goto end;
65931c8b 577 }
b4aacfdc
MD
578 ret = 0;
579end:
580 return ret;
65931c8b
MD
581}
582
b8aa1682 583/*
b4aacfdc 584 * Stop all relayd and relayd-live threads.
b8aa1682 585 */
b4aacfdc 586int lttng_relay_stop_threads(void)
b8aa1682 587{
b4aacfdc 588 int retval = 0;
b8aa1682
JD
589
590 /* Stopping all threads */
591 DBG("Terminating all threads");
b4aacfdc 592 if (notify_thread_pipe(thread_quit_pipe[1])) {
b8aa1682 593 ERR("write error on thread quit pipe");
b4aacfdc 594 retval = -1;
b8aa1682
JD
595 }
596
b4aacfdc
MD
597 if (notify_health_quit_pipe(health_quit_pipe)) {
598 ERR("write error on health quit pipe");
599 }
65931c8b 600
b8aa1682 601 /* Dispatch thread */
26c9d55e 602 CMM_STORE_SHARED(dispatch_thread_exit, 1);
58eb9381 603 futex_nto1_wake(&relay_conn_queue.futex);
178a0557 604
b4aacfdc 605 if (relayd_live_stop()) {
178a0557 606 ERR("Error stopping live threads");
b4aacfdc 607 retval = -1;
178a0557 608 }
b4aacfdc 609 return retval;
b8aa1682
JD
610}
611
612/*
613 * Signal handler for the daemon
614 *
615 * Simply stop all worker threads, leaving main() return gracefully after
616 * joining all threads and calling cleanup().
617 */
7591bab1 618static void sighandler(int sig)
b8aa1682
JD
619{
620 switch (sig) {
b8aa1682
JD
621 case SIGINT:
622 DBG("SIGINT caught");
b4aacfdc
MD
623 if (lttng_relay_stop_threads()) {
624 ERR("Error stopping threads");
625 }
b8aa1682
JD
626 break;
627 case SIGTERM:
628 DBG("SIGTERM caught");
b4aacfdc
MD
629 if (lttng_relay_stop_threads()) {
630 ERR("Error stopping threads");
631 }
b8aa1682 632 break;
3fd27398
MD
633 case SIGUSR1:
634 CMM_STORE_SHARED(recv_child_signal, 1);
635 break;
b8aa1682
JD
636 default:
637 break;
638 }
639}
640
641/*
642 * Setup signal handler for :
643 * SIGINT, SIGTERM, SIGPIPE
644 */
7591bab1 645static int set_signal_handler(void)
b8aa1682
JD
646{
647 int ret = 0;
648 struct sigaction sa;
649 sigset_t sigset;
650
651 if ((ret = sigemptyset(&sigset)) < 0) {
652 PERROR("sigemptyset");
653 return ret;
654 }
655
b8aa1682
JD
656 sa.sa_mask = sigset;
657 sa.sa_flags = 0;
0072e5e2
MD
658
659 sa.sa_handler = sighandler;
b8aa1682
JD
660 if ((ret = sigaction(SIGTERM, &sa, NULL)) < 0) {
661 PERROR("sigaction");
662 return ret;
663 }
664
665 if ((ret = sigaction(SIGINT, &sa, NULL)) < 0) {
666 PERROR("sigaction");
667 return ret;
668 }
669
0072e5e2 670 if ((ret = sigaction(SIGUSR1, &sa, NULL)) < 0) {
b8aa1682
JD
671 PERROR("sigaction");
672 return ret;
673 }
674
0072e5e2
MD
675 sa.sa_handler = SIG_IGN;
676 if ((ret = sigaction(SIGPIPE, &sa, NULL)) < 0) {
3fd27398
MD
677 PERROR("sigaction");
678 return ret;
679 }
680
681 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
b8aa1682
JD
682
683 return ret;
684}
685
3fd27398
MD
686void lttng_relay_notify_ready(void)
687{
688 /* Notify the parent of the fork() process that we are ready. */
689 if (opt_daemon || opt_background) {
690 if (uatomic_sub_return(&lttng_relay_ready, 1) == 0) {
691 kill(child_ppid, SIGUSR1);
692 }
693 }
694}
695
b8aa1682
JD
696/*
697 * Init thread quit pipe.
698 *
699 * Return -1 on error or 0 if all pipes are created.
700 */
7591bab1 701static int init_thread_quit_pipe(void)
b8aa1682 702{
a02de639 703 int ret;
b8aa1682 704
a02de639 705 ret = utils_create_pipe_cloexec(thread_quit_pipe);
b8aa1682 706
b8aa1682
JD
707 return ret;
708}
709
710/*
711 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
712 */
7591bab1 713static int create_thread_poll_set(struct lttng_poll_event *events, int size)
b8aa1682
JD
714{
715 int ret;
716
717 if (events == NULL || size == 0) {
718 ret = -1;
719 goto error;
720 }
721
722 ret = lttng_poll_create(events, size, LTTNG_CLOEXEC);
723 if (ret < 0) {
724 goto error;
725 }
726
727 /* Add quit pipe */
c7759e6a 728 ret = lttng_poll_add(events, thread_quit_pipe[0], LPOLLIN | LPOLLERR);
b8aa1682
JD
729 if (ret < 0) {
730 goto error;
731 }
732
733 return 0;
734
735error:
736 return ret;
737}
738
739/*
740 * Check if the thread quit pipe was triggered.
741 *
742 * Return 1 if it was triggered else 0;
743 */
7591bab1 744static int check_thread_quit_pipe(int fd, uint32_t events)
b8aa1682
JD
745{
746 if (fd == thread_quit_pipe[0] && (events & LPOLLIN)) {
747 return 1;
748 }
749
750 return 0;
751}
752
753/*
754 * Create and init socket from uri.
755 */
7591bab1 756static struct lttcomm_sock *relay_socket_create(struct lttng_uri *uri)
b8aa1682
JD
757{
758 int ret;
759 struct lttcomm_sock *sock = NULL;
760
761 sock = lttcomm_alloc_sock_from_uri(uri);
762 if (sock == NULL) {
763 ERR("Allocating socket");
764 goto error;
765 }
766
767 ret = lttcomm_create_sock(sock);
768 if (ret < 0) {
769 goto error;
770 }
771 DBG("Listening on sock %d", sock->fd);
772
773 ret = sock->ops->bind(sock);
774 if (ret < 0) {
775 goto error;
776 }
777
778 ret = sock->ops->listen(sock, -1);
779 if (ret < 0) {
780 goto error;
781
782 }
783
784 return sock;
785
786error:
787 if (sock) {
788 lttcomm_destroy_sock(sock);
789 }
790 return NULL;
791}
792
793/*
794 * This thread manages the listening for new connections on the network
795 */
7591bab1 796static void *relay_thread_listener(void *data)
b8aa1682 797{
095a4ae5 798 int i, ret, pollfd, err = -1;
b8aa1682
JD
799 uint32_t revents, nb_fd;
800 struct lttng_poll_event events;
801 struct lttcomm_sock *control_sock, *data_sock;
802
b8aa1682
JD
803 DBG("[thread] Relay listener started");
804
55706a7d
MD
805 health_register(health_relayd, HEALTH_RELAYD_TYPE_LISTENER);
806
f385ae0a
MD
807 health_code_update();
808
7591bab1 809 control_sock = relay_socket_create(control_uri);
b8aa1682 810 if (!control_sock) {
095a4ae5 811 goto error_sock_control;
b8aa1682
JD
812 }
813
7591bab1 814 data_sock = relay_socket_create(data_uri);
b8aa1682 815 if (!data_sock) {
095a4ae5 816 goto error_sock_relay;
b8aa1682
JD
817 }
818
819 /*
7591bab1
MD
820 * Pass 3 as size here for the thread quit pipe, control and
821 * data socket.
b8aa1682
JD
822 */
823 ret = create_thread_poll_set(&events, 3);
824 if (ret < 0) {
825 goto error_create_poll;
826 }
827
828 /* Add the control socket */
829 ret = lttng_poll_add(&events, control_sock->fd, LPOLLIN | LPOLLRDHUP);
830 if (ret < 0) {
831 goto error_poll_add;
832 }
833
834 /* Add the data socket */
835 ret = lttng_poll_add(&events, data_sock->fd, LPOLLIN | LPOLLRDHUP);
836 if (ret < 0) {
837 goto error_poll_add;
838 }
839
3fd27398
MD
840 lttng_relay_notify_ready();
841
9b5e0863
MD
842 if (testpoint(relayd_thread_listener)) {
843 goto error_testpoint;
844 }
845
b8aa1682 846 while (1) {
f385ae0a
MD
847 health_code_update();
848
b8aa1682
JD
849 DBG("Listener accepting connections");
850
b8aa1682 851restart:
f385ae0a 852 health_poll_entry();
b8aa1682 853 ret = lttng_poll_wait(&events, -1);
f385ae0a 854 health_poll_exit();
b8aa1682
JD
855 if (ret < 0) {
856 /*
857 * Restart interrupted system call.
858 */
859 if (errno == EINTR) {
860 goto restart;
861 }
862 goto error;
863 }
864
0d9c5d77
DG
865 nb_fd = ret;
866
b8aa1682
JD
867 DBG("Relay new connection received");
868 for (i = 0; i < nb_fd; i++) {
f385ae0a
MD
869 health_code_update();
870
b8aa1682
JD
871 /* Fetch once the poll data */
872 revents = LTTNG_POLL_GETEV(&events, i);
873 pollfd = LTTNG_POLL_GETFD(&events, i);
874
fd20dac9 875 if (!revents) {
7591bab1
MD
876 /*
877 * No activity for this FD (poll
878 * implementation).
879 */
fd20dac9
MD
880 continue;
881 }
882
b8aa1682
JD
883 /* Thread quit pipe has been closed. Killing thread. */
884 ret = check_thread_quit_pipe(pollfd, revents);
885 if (ret) {
095a4ae5
MD
886 err = 0;
887 goto exit;
b8aa1682
JD
888 }
889
03e43155 890 if (revents & LPOLLIN) {
4b7f17b2 891 /*
7591bab1
MD
892 * A new connection is requested, therefore a
893 * sessiond/consumerd connection is allocated in
894 * this thread, enqueued to a global queue and
895 * dequeued (and freed) in the worker thread.
4b7f17b2 896 */
58eb9381
DG
897 int val = 1;
898 struct relay_connection *new_conn;
4b7f17b2 899 struct lttcomm_sock *newsock;
7591bab1 900 enum connection_type type;
b8aa1682
JD
901
902 if (pollfd == data_sock->fd) {
7591bab1 903 type = RELAY_DATA;
b8aa1682 904 newsock = data_sock->ops->accept(data_sock);
58eb9381
DG
905 DBG("Relay data connection accepted, socket %d",
906 newsock->fd);
4b7f17b2
MD
907 } else {
908 assert(pollfd == control_sock->fd);
7591bab1 909 type = RELAY_CONTROL;
b8aa1682 910 newsock = control_sock->ops->accept(control_sock);
58eb9381
DG
911 DBG("Relay control connection accepted, socket %d",
912 newsock->fd);
b8aa1682 913 }
58eb9381
DG
914 if (!newsock) {
915 PERROR("accepting sock");
58eb9381
DG
916 goto error;
917 }
918
919 ret = setsockopt(newsock->fd, SOL_SOCKET, SO_REUSEADDR, &val,
920 sizeof(val));
b8aa1682
JD
921 if (ret < 0) {
922 PERROR("setsockopt inet");
4b7f17b2 923 lttcomm_destroy_sock(newsock);
b8aa1682
JD
924 goto error;
925 }
2fc6b1ab
JR
926
927 ret = socket_apply_keep_alive_config(newsock->fd);
928 if (ret < 0) {
929 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
930 newsock->fd);
931 lttcomm_destroy_sock(newsock);
932 goto error;
933 }
934
7591bab1
MD
935 new_conn = connection_create(newsock, type);
936 if (!new_conn) {
937 lttcomm_destroy_sock(newsock);
938 goto error;
939 }
58eb9381
DG
940
941 /* Enqueue request for the dispatcher thread. */
8bdee6e2
SM
942 cds_wfcq_enqueue(&relay_conn_queue.head, &relay_conn_queue.tail,
943 &new_conn->qnode);
b8aa1682
JD
944
945 /*
7591bab1
MD
946 * Wake the dispatch queue futex.
947 * Implicit memory barrier with the
948 * exchange in cds_wfcq_enqueue.
b8aa1682 949 */
58eb9381 950 futex_nto1_wake(&relay_conn_queue.futex);
03e43155
MD
951 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
952 ERR("socket poll error");
953 goto error;
954 } else {
955 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
956 goto error;
b8aa1682
JD
957 }
958 }
959 }
960
095a4ae5 961exit:
b8aa1682
JD
962error:
963error_poll_add:
9b5e0863 964error_testpoint:
b8aa1682
JD
965 lttng_poll_clean(&events);
966error_create_poll:
095a4ae5
MD
967 if (data_sock->fd >= 0) {
968 ret = data_sock->ops->close(data_sock);
b8aa1682
JD
969 if (ret) {
970 PERROR("close");
971 }
b8aa1682 972 }
095a4ae5
MD
973 lttcomm_destroy_sock(data_sock);
974error_sock_relay:
975 if (control_sock->fd >= 0) {
976 ret = control_sock->ops->close(control_sock);
b8aa1682
JD
977 if (ret) {
978 PERROR("close");
979 }
b8aa1682 980 }
095a4ae5
MD
981 lttcomm_destroy_sock(control_sock);
982error_sock_control:
983 if (err) {
f385ae0a
MD
984 health_error();
985 ERR("Health error occurred in %s", __func__);
095a4ae5 986 }
55706a7d 987 health_unregister(health_relayd);
b8aa1682 988 DBG("Relay listener thread cleanup complete");
b4aacfdc 989 lttng_relay_stop_threads();
b8aa1682
JD
990 return NULL;
991}
992
993/*
994 * This thread manages the dispatching of the requests to worker threads
995 */
7591bab1 996static void *relay_thread_dispatcher(void *data)
b8aa1682 997{
6cd525e8
MD
998 int err = -1;
999 ssize_t ret;
8bdee6e2 1000 struct cds_wfcq_node *node;
58eb9381 1001 struct relay_connection *new_conn = NULL;
b8aa1682
JD
1002
1003 DBG("[thread] Relay dispatcher started");
1004
55706a7d
MD
1005 health_register(health_relayd, HEALTH_RELAYD_TYPE_DISPATCHER);
1006
9b5e0863
MD
1007 if (testpoint(relayd_thread_dispatcher)) {
1008 goto error_testpoint;
1009 }
1010
f385ae0a
MD
1011 health_code_update();
1012
68924dc1 1013 for (;;) {
f385ae0a
MD
1014 health_code_update();
1015
b8aa1682 1016 /* Atomically prepare the queue futex */
58eb9381 1017 futex_nto1_prepare(&relay_conn_queue.futex);
b8aa1682 1018
68924dc1
MD
1019 if (CMM_LOAD_SHARED(dispatch_thread_exit)) {
1020 break;
1021 }
1022
b8aa1682 1023 do {
f385ae0a
MD
1024 health_code_update();
1025
b8aa1682 1026 /* Dequeue commands */
8bdee6e2
SM
1027 node = cds_wfcq_dequeue_blocking(&relay_conn_queue.head,
1028 &relay_conn_queue.tail);
b8aa1682
JD
1029 if (node == NULL) {
1030 DBG("Woken up but nothing in the relay command queue");
1031 /* Continue thread execution */
1032 break;
1033 }
58eb9381 1034 new_conn = caa_container_of(node, struct relay_connection, qnode);
b8aa1682 1035
58eb9381 1036 DBG("Dispatching request waiting on sock %d", new_conn->sock->fd);
b8aa1682
JD
1037
1038 /*
7591bab1
MD
1039 * Inform worker thread of the new request. This
1040 * call is blocking so we can be assured that
1041 * the data will be read at some point in time
1042 * or wait to the end of the world :)
b8aa1682 1043 */
58eb9381
DG
1044 ret = lttng_write(relay_conn_pipe[1], &new_conn, sizeof(new_conn));
1045 if (ret < 0) {
1046 PERROR("write connection pipe");
7591bab1 1047 connection_put(new_conn);
b8aa1682
JD
1048 goto error;
1049 }
1050 } while (node != NULL);
1051
1052 /* Futex wait on queue. Blocking call on futex() */
f385ae0a 1053 health_poll_entry();
58eb9381 1054 futex_nto1_wait(&relay_conn_queue.futex);
f385ae0a 1055 health_poll_exit();
b8aa1682
JD
1056 }
1057
f385ae0a
MD
1058 /* Normal exit, no error */
1059 err = 0;
1060
b8aa1682 1061error:
9b5e0863 1062error_testpoint:
f385ae0a
MD
1063 if (err) {
1064 health_error();
1065 ERR("Health error occurred in %s", __func__);
1066 }
55706a7d 1067 health_unregister(health_relayd);
b8aa1682 1068 DBG("Dispatch thread dying");
b4aacfdc 1069 lttng_relay_stop_threads();
b8aa1682
JD
1070 return NULL;
1071}
1072
b8aa1682 1073/*
7591bab1 1074 * Set index data from the control port to a given index object.
b8aa1682 1075 */
7591bab1 1076static int set_index_control_data(struct relay_index *index,
234cd636
JD
1077 struct lttcomm_relayd_index *data,
1078 struct relay_connection *conn)
1c20f0e2 1079{
7591bab1 1080 struct ctf_packet_index index_data;
1c20f0e2
JD
1081
1082 /*
44a2fbf1 1083 * The index on disk is encoded in big endian.
1c20f0e2 1084 */
44a2fbf1
JG
1085 index_data.packet_size = htobe64(data->packet_size);
1086 index_data.content_size = htobe64(data->content_size);
1087 index_data.timestamp_begin = htobe64(data->timestamp_begin);
1088 index_data.timestamp_end = htobe64(data->timestamp_end);
1089 index_data.events_discarded = htobe64(data->events_discarded);
1090 index_data.stream_id = htobe64(data->stream_id);
234cd636
JD
1091
1092 if (conn->minor >= 8) {
44a2fbf1
JG
1093 index->index_data.stream_instance_id = htobe64(data->stream_instance_id);
1094 index->index_data.packet_seq_num = htobe64(data->packet_seq_num);
234cd636
JD
1095 }
1096
7591bab1 1097 return relay_index_set_data(index, &index_data);
1c20f0e2
JD
1098}
1099
c5b6f4f0
DG
1100/*
1101 * Handle the RELAYD_CREATE_SESSION command.
1102 *
1103 * On success, send back the session id or else return a negative value.
1104 */
44a2fbf1
JG
1105static int relay_create_session(const struct lttcomm_relayd_hdr *recv_hdr,
1106 struct relay_connection *conn,
1107 const struct lttng_buffer_view *payload)
c5b6f4f0 1108{
44a2fbf1
JG
1109 int ret = 0;
1110 ssize_t send_ret;
c5b6f4f0
DG
1111 struct relay_session *session;
1112 struct lttcomm_relayd_status_session reply;
36d2e35d 1113 char session_name[LTTNG_NAME_MAX];
9cf3eb20 1114 char hostname[LTTNG_HOST_NAME_MAX];
7591bab1
MD
1115 uint32_t live_timer = 0;
1116 bool snapshot = false;
c5b6f4f0 1117
36d2e35d 1118 memset(session_name, 0, LTTNG_NAME_MAX);
9cf3eb20 1119 memset(hostname, 0, LTTNG_HOST_NAME_MAX);
c5b6f4f0
DG
1120
1121 memset(&reply, 0, sizeof(reply));
1122
58eb9381 1123 switch (conn->minor) {
2a174661
DG
1124 case 1:
1125 case 2:
1126 case 3:
1127 break;
1128 case 4: /* LTTng sessiond 2.4 */
1129 default:
44a2fbf1 1130 ret = cmd_create_session_2_4(payload, session_name,
7591bab1
MD
1131 hostname, &live_timer, &snapshot);
1132 }
1133 if (ret < 0) {
1134 goto send_reply;
d3e2ba59
JD
1135 }
1136
7591bab1
MD
1137 session = session_create(session_name, hostname, live_timer,
1138 snapshot, conn->major, conn->minor);
1139 if (!session) {
1140 ret = -1;
1141 goto send_reply;
1142 }
1143 assert(!conn->session);
1144 conn->session = session;
c5b6f4f0
DG
1145 DBG("Created session %" PRIu64, session->id);
1146
7591bab1
MD
1147 reply.session_id = htobe64(session->id);
1148
1149send_reply:
c5b6f4f0
DG
1150 if (ret < 0) {
1151 reply.ret_code = htobe32(LTTNG_ERR_FATAL);
1152 } else {
1153 reply.ret_code = htobe32(LTTNG_OK);
1154 }
1155
58eb9381 1156 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
44a2fbf1
JG
1157 if (send_ret < (ssize_t) sizeof(reply)) {
1158 ERR("Failed to send \"create session\" command reply (ret = %zd)",
1159 send_ret);
1160 ret = -1;
c5b6f4f0
DG
1161 }
1162
1163 return ret;
1164}
1165
a4baae1b
JD
1166/*
1167 * When we have received all the streams and the metadata for a channel,
1168 * we make them visible to the viewer threads.
1169 */
7591bab1 1170static void publish_connection_local_streams(struct relay_connection *conn)
a4baae1b 1171{
7591bab1
MD
1172 struct relay_stream *stream;
1173 struct relay_session *session = conn->session;
a4baae1b 1174
7591bab1
MD
1175 /*
1176 * We publish all streams belonging to a session atomically wrt
1177 * session lock.
1178 */
1179 pthread_mutex_lock(&session->lock);
1180 rcu_read_lock();
1181 cds_list_for_each_entry_rcu(stream, &session->recv_list,
1182 recv_node) {
1183 stream_publish(stream);
a4baae1b 1184 }
7591bab1 1185 rcu_read_unlock();
a4baae1b 1186
7591bab1
MD
1187 /*
1188 * Inform the viewer that there are new streams in the session.
1189 */
1190 if (session->viewer_attached) {
1191 uatomic_set(&session->new_streams, 1);
1192 }
1193 pthread_mutex_unlock(&session->lock);
a4baae1b
JD
1194}
1195
b8aa1682
JD
1196/*
1197 * relay_add_stream: allocate a new stream for a session
1198 */
44a2fbf1
JG
1199static int relay_add_stream(const struct lttcomm_relayd_hdr *recv_hdr,
1200 struct relay_connection *conn,
1201 const struct lttng_buffer_view *payload)
b8aa1682 1202{
7591bab1
MD
1203 int ret;
1204 ssize_t send_ret;
58eb9381 1205 struct relay_session *session = conn->session;
b8aa1682
JD
1206 struct relay_stream *stream = NULL;
1207 struct lttcomm_relayd_status_stream reply;
4030a636 1208 struct ctf_trace *trace = NULL;
7591bab1
MD
1209 uint64_t stream_handle = -1ULL;
1210 char *path_name = NULL, *channel_name = NULL;
1211 uint64_t tracefile_size = 0, tracefile_count = 0;
b8aa1682 1212
44a2fbf1 1213 if (!session || !conn->version_check_done) {
b8aa1682
JD
1214 ERR("Trying to add a stream before version check");
1215 ret = -1;
1216 goto end_no_session;
1217 }
1218
7591bab1
MD
1219 switch (session->minor) {
1220 case 1: /* LTTng sessiond 2.1. Allocates path_name and channel_name. */
44a2fbf1 1221 ret = cmd_recv_stream_2_1(payload, &path_name,
7591bab1 1222 &channel_name);
0f907de1 1223 break;
7591bab1 1224 case 2: /* LTTng sessiond 2.2. Allocates path_name and channel_name. */
0f907de1 1225 default:
44a2fbf1 1226 ret = cmd_recv_stream_2_2(payload, &path_name,
7591bab1 1227 &channel_name, &tracefile_size, &tracefile_count);
0f907de1
JD
1228 break;
1229 }
1230 if (ret < 0) {
7591bab1 1231 goto send_reply;
b8aa1682
JD
1232 }
1233
7591bab1 1234 trace = ctf_trace_get_by_path_or_create(session, path_name);
2a174661 1235 if (!trace) {
7591bab1 1236 goto send_reply;
2a174661 1237 }
7591bab1 1238 /* This stream here has one reference on the trace. */
2a174661 1239
7591bab1
MD
1240 pthread_mutex_lock(&last_relay_stream_id_lock);
1241 stream_handle = ++last_relay_stream_id;
1242 pthread_mutex_unlock(&last_relay_stream_id_lock);
d3e2ba59 1243
7591bab1
MD
1244 /* We pass ownership of path_name and channel_name. */
1245 stream = stream_create(trace, stream_handle, path_name,
1246 channel_name, tracefile_size, tracefile_count);
1247 path_name = NULL;
1248 channel_name = NULL;
a4baae1b 1249
2a174661 1250 /*
7591bab1
MD
1251 * Streams are the owners of their trace. Reference to trace is
1252 * kept within stream_create().
2a174661 1253 */
7591bab1 1254 ctf_trace_put(trace);
d3e2ba59 1255
7591bab1 1256send_reply:
53efb85a 1257 memset(&reply, 0, sizeof(reply));
7591bab1
MD
1258 reply.handle = htobe64(stream_handle);
1259 if (!stream) {
f73fabfd 1260 reply.ret_code = htobe32(LTTNG_ERR_UNK);
b8aa1682 1261 } else {
f73fabfd 1262 reply.ret_code = htobe32(LTTNG_OK);
b8aa1682 1263 }
5af40280 1264
58eb9381 1265 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
b8aa1682 1266 sizeof(struct lttcomm_relayd_status_stream), 0);
44a2fbf1
JG
1267 if (send_ret < (ssize_t) sizeof(reply)) {
1268 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1269 send_ret);
1270 ret = -1;
b8aa1682
JD
1271 }
1272
1273end_no_session:
7591bab1
MD
1274 free(path_name);
1275 free(channel_name);
0f907de1 1276 return ret;
b8aa1682
JD
1277}
1278
173af62f
DG
1279/*
1280 * relay_close_stream: close a specific stream
1281 */
44a2fbf1
JG
1282static int relay_close_stream(const struct lttcomm_relayd_hdr *recv_hdr,
1283 struct relay_connection *conn,
1284 const struct lttng_buffer_view *payload)
173af62f 1285{
44a2fbf1
JG
1286 int ret;
1287 ssize_t send_ret;
58eb9381 1288 struct relay_session *session = conn->session;
173af62f
DG
1289 struct lttcomm_relayd_close_stream stream_info;
1290 struct lttcomm_relayd_generic_reply reply;
1291 struct relay_stream *stream;
173af62f
DG
1292
1293 DBG("Close stream received");
1294
44a2fbf1 1295 if (!session || !conn->version_check_done) {
173af62f
DG
1296 ERR("Trying to close a stream before version check");
1297 ret = -1;
1298 goto end_no_session;
1299 }
1300
44a2fbf1
JG
1301 if (payload->size < sizeof(stream_info)) {
1302 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1303 sizeof(stream_info), payload->size);
173af62f
DG
1304 ret = -1;
1305 goto end_no_session;
1306 }
44a2fbf1
JG
1307 memcpy(&stream_info, payload->data, sizeof(stream_info));
1308 stream_info.stream_id = be64toh(stream_info.stream_id);
1309 stream_info.last_net_seq_num = be64toh(stream_info.last_net_seq_num);
173af62f 1310
44a2fbf1 1311 stream = stream_get_by_id(stream_info.stream_id);
173af62f
DG
1312 if (!stream) {
1313 ret = -1;
7591bab1 1314 goto end;
173af62f 1315 }
77f7bd85
MD
1316
1317 /*
1318 * Set last_net_seq_num before the close flag. Required by data
1319 * pending check.
1320 */
7591bab1 1321 pthread_mutex_lock(&stream->lock);
44a2fbf1 1322 stream->last_net_seq_num = stream_info.last_net_seq_num;
77f7bd85
MD
1323 pthread_mutex_unlock(&stream->lock);
1324
bda7c7b9
JG
1325 /*
1326 * This is one of the conditions which may trigger a stream close
1327 * with the others being:
1328 * 1) A close command is received for a stream
1329 * 2) The control connection owning the stream is closed
1330 * 3) We have received all of the stream's data _after_ a close
1331 * request.
1332 */
1333 try_stream_close(stream);
7591bab1
MD
1334 if (stream->is_metadata) {
1335 struct relay_viewer_stream *vstream;
173af62f 1336
7591bab1
MD
1337 vstream = viewer_stream_get_by_id(stream->stream_handle);
1338 if (vstream) {
1339 if (vstream->metadata_sent == stream->metadata_received) {
1340 /*
1341 * Since all the metadata has been sent to the
1342 * viewer and that we have a request to close
1343 * its stream, we can safely teardown the
1344 * corresponding metadata viewer stream.
1345 */
1346 viewer_stream_put(vstream);
1347 }
1348 /* Put local reference. */
1349 viewer_stream_put(vstream);
1350 }
1351 }
7591bab1 1352 stream_put(stream);
44a2fbf1 1353 ret = 0;
173af62f 1354
7591bab1 1355end:
53efb85a 1356 memset(&reply, 0, sizeof(reply));
173af62f 1357 if (ret < 0) {
f73fabfd 1358 reply.ret_code = htobe32(LTTNG_ERR_UNK);
173af62f 1359 } else {
f73fabfd 1360 reply.ret_code = htobe32(LTTNG_OK);
173af62f 1361 }
58eb9381 1362 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
173af62f 1363 sizeof(struct lttcomm_relayd_generic_reply), 0);
44a2fbf1
JG
1364 if (send_ret < (ssize_t) sizeof(reply)) {
1365 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1366 send_ret);
1367 ret = -1;
173af62f
DG
1368 }
1369
1370end_no_session:
1371 return ret;
1372}
1373
93ec662e
JD
1374/*
1375 * relay_reset_metadata: reset a metadata stream
1376 */
1377static
44a2fbf1
JG
1378int relay_reset_metadata(const struct lttcomm_relayd_hdr *recv_hdr,
1379 struct relay_connection *conn,
1380 const struct lttng_buffer_view *payload)
93ec662e 1381{
44a2fbf1
JG
1382 int ret;
1383 ssize_t send_ret;
93ec662e
JD
1384 struct relay_session *session = conn->session;
1385 struct lttcomm_relayd_reset_metadata stream_info;
1386 struct lttcomm_relayd_generic_reply reply;
1387 struct relay_stream *stream;
1388
1389 DBG("Reset metadata received");
1390
44a2fbf1 1391 if (!session || !conn->version_check_done) {
93ec662e
JD
1392 ERR("Trying to reset a metadata stream before version check");
1393 ret = -1;
1394 goto end_no_session;
1395 }
1396
44a2fbf1
JG
1397 if (payload->size < sizeof(stream_info)) {
1398 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1399 sizeof(stream_info), payload->size);
93ec662e
JD
1400 ret = -1;
1401 goto end_no_session;
1402 }
44a2fbf1
JG
1403 memcpy(&stream_info, payload->data, sizeof(stream_info));
1404 stream_info.stream_id = be64toh(stream_info.stream_id);
1405 stream_info.version = be64toh(stream_info.version);
1406
1407 DBG("Update metadata to version %" PRIu64, stream_info.version);
93ec662e
JD
1408
1409 /* Unsupported for live sessions for now. */
1410 if (session->live_timer != 0) {
1411 ret = -1;
1412 goto end;
1413 }
1414
44a2fbf1 1415 stream = stream_get_by_id(stream_info.stream_id);
93ec662e
JD
1416 if (!stream) {
1417 ret = -1;
1418 goto end;
1419 }
1420 pthread_mutex_lock(&stream->lock);
1421 if (!stream->is_metadata) {
1422 ret = -1;
1423 goto end_unlock;
1424 }
1425
1426 ret = utils_rotate_stream_file(stream->path_name, stream->channel_name,
1427 0, 0, -1, -1, stream->stream_fd->fd, NULL,
1428 &stream->stream_fd->fd);
1429 if (ret < 0) {
1430 ERR("Failed to rotate metadata file %s of channel %s",
1431 stream->path_name, stream->channel_name);
1432 goto end_unlock;
1433 }
1434
1435end_unlock:
1436 pthread_mutex_unlock(&stream->lock);
1437 stream_put(stream);
1438
1439end:
1440 memset(&reply, 0, sizeof(reply));
1441 if (ret < 0) {
1442 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1443 } else {
1444 reply.ret_code = htobe32(LTTNG_OK);
1445 }
1446 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1447 sizeof(struct lttcomm_relayd_generic_reply), 0);
44a2fbf1
JG
1448 if (send_ret < (ssize_t) sizeof(reply)) {
1449 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1450 send_ret);
1451 ret = -1;
93ec662e
JD
1452 }
1453
1454end_no_session:
1455 return ret;
1456}
1457
b8aa1682
JD
1458/*
1459 * relay_unknown_command: send -1 if received unknown command
1460 */
7591bab1 1461static void relay_unknown_command(struct relay_connection *conn)
b8aa1682
JD
1462{
1463 struct lttcomm_relayd_generic_reply reply;
44a2fbf1 1464 ssize_t send_ret;
b8aa1682 1465
53efb85a 1466 memset(&reply, 0, sizeof(reply));
f73fabfd 1467 reply.ret_code = htobe32(LTTNG_ERR_UNK);
44a2fbf1
JG
1468 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1469 if (send_ret < sizeof(reply)) {
1470 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret);
b8aa1682
JD
1471 }
1472}
1473
1474/*
1475 * relay_start: send an acknowledgment to the client to tell if we are
1476 * ready to receive data. We are ready if a session is established.
1477 */
44a2fbf1
JG
1478static int relay_start(const struct lttcomm_relayd_hdr *recv_hdr,
1479 struct relay_connection *conn,
1480 const struct lttng_buffer_view *payload)
b8aa1682 1481{
44a2fbf1
JG
1482 int ret = 0;
1483 ssize_t send_ret;
b8aa1682 1484 struct lttcomm_relayd_generic_reply reply;
58eb9381 1485 struct relay_session *session = conn->session;
b8aa1682
JD
1486
1487 if (!session) {
1488 DBG("Trying to start the streaming without a session established");
f73fabfd 1489 ret = htobe32(LTTNG_ERR_UNK);
b8aa1682
JD
1490 }
1491
53efb85a 1492 memset(&reply, 0, sizeof(reply));
44a2fbf1
JG
1493 reply.ret_code = htobe32(LTTNG_OK);
1494 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1495 sizeof(reply), 0);
1496 if (send_ret < (ssize_t) sizeof(reply)) {
1497 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1498 send_ret);
1499 ret = -1;
b8aa1682
JD
1500 }
1501
1502 return ret;
1503}
1504
1d4dfdef
DG
1505/*
1506 * Append padding to the file pointed by the file descriptor fd.
1507 */
1508static int write_padding_to_file(int fd, uint32_t size)
1509{
6cd525e8 1510 ssize_t ret = 0;
1d4dfdef
DG
1511 char *zeros;
1512
1513 if (size == 0) {
1514 goto end;
1515 }
1516
1517 zeros = zmalloc(size);
1518 if (zeros == NULL) {
1519 PERROR("zmalloc zeros for padding");
1520 ret = -1;
1521 goto end;
1522 }
1523
6cd525e8
MD
1524 ret = lttng_write(fd, zeros, size);
1525 if (ret < size) {
1d4dfdef
DG
1526 PERROR("write padding to file");
1527 }
1528
e986c7a1
DG
1529 free(zeros);
1530
1d4dfdef
DG
1531end:
1532 return ret;
1533}
1534
b8aa1682 1535/*
7591bab1 1536 * relay_recv_metadata: receive the metadata for the session.
b8aa1682 1537 */
44a2fbf1
JG
1538static int relay_recv_metadata(const struct lttcomm_relayd_hdr *recv_hdr,
1539 struct relay_connection *conn,
1540 const struct lttng_buffer_view *payload)
b8aa1682 1541{
32d1569c 1542 int ret = 0;
6cd525e8 1543 ssize_t size_ret;
58eb9381 1544 struct relay_session *session = conn->session;
44a2fbf1 1545 struct lttcomm_relayd_metadata_payload metadata_payload_header;
b8aa1682 1546 struct relay_stream *metadata_stream;
44a2fbf1 1547 uint64_t metadata_payload_size;
b8aa1682
JD
1548
1549 if (!session) {
1550 ERR("Metadata sent before version check");
1551 ret = -1;
1552 goto end;
1553 }
1554
44a2fbf1 1555 if (recv_hdr->data_size < sizeof(struct lttcomm_relayd_metadata_payload)) {
f6416125
MD
1556 ERR("Incorrect data size");
1557 ret = -1;
1558 goto end;
1559 }
44a2fbf1
JG
1560 metadata_payload_size = recv_hdr->data_size -
1561 sizeof(struct lttcomm_relayd_metadata_payload);
f6416125 1562
44a2fbf1
JG
1563 memcpy(&metadata_payload_header, payload->data,
1564 sizeof(metadata_payload_header));
1565 metadata_payload_header.stream_id = be64toh(
1566 metadata_payload_header.stream_id);
1567 metadata_payload_header.padding_size = be32toh(
1568 metadata_payload_header.padding_size);
c617c0c6 1569
44a2fbf1 1570 metadata_stream = stream_get_by_id(metadata_payload_header.stream_id);
b8aa1682
JD
1571 if (!metadata_stream) {
1572 ret = -1;
7591bab1 1573 goto end;
b8aa1682
JD
1574 }
1575
7591bab1
MD
1576 pthread_mutex_lock(&metadata_stream->lock);
1577
44a2fbf1
JG
1578 size_ret = lttng_write(metadata_stream->stream_fd->fd,
1579 payload->data + sizeof(metadata_payload_header),
1580 metadata_payload_size);
1581 if (size_ret < metadata_payload_size) {
b8aa1682
JD
1582 ERR("Relay error writing metadata on file");
1583 ret = -1;
7591bab1 1584 goto end_put;
b8aa1682 1585 }
1d4dfdef 1586
32d1569c 1587 size_ret = write_padding_to_file(metadata_stream->stream_fd->fd,
44a2fbf1
JG
1588 metadata_payload_header.padding_size);
1589 if (size_ret < (int64_t) metadata_payload_header.padding_size) {
1590 ret = -1;
7591bab1 1591 goto end_put;
1d4dfdef 1592 }
2a174661 1593
7591bab1 1594 metadata_stream->metadata_received +=
44a2fbf1 1595 metadata_payload_size + metadata_payload_header.padding_size;
7591bab1
MD
1596 DBG2("Relay metadata written. Updated metadata_received %" PRIu64,
1597 metadata_stream->metadata_received);
1d4dfdef 1598
7591bab1
MD
1599end_put:
1600 pthread_mutex_unlock(&metadata_stream->lock);
1601 stream_put(metadata_stream);
b8aa1682
JD
1602end:
1603 return ret;
1604}
1605
1606/*
1607 * relay_send_version: send relayd version number
1608 */
44a2fbf1
JG
1609static int relay_send_version(const struct lttcomm_relayd_hdr *recv_hdr,
1610 struct relay_connection *conn,
1611 const struct lttng_buffer_view *payload)
b8aa1682 1612{
7f51dcba 1613 int ret;
44a2fbf1 1614 ssize_t send_ret;
092b6259 1615 struct lttcomm_relayd_version reply, msg;
40096142 1616 bool compatible = true;
b8aa1682 1617
44a2fbf1 1618 conn->version_check_done = true;
b8aa1682 1619
092b6259 1620 /* Get version from the other side. */
44a2fbf1
JG
1621 if (payload->size < sizeof(msg)) {
1622 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1623 sizeof(msg), payload->size);
092b6259 1624 ret = -1;
092b6259
DG
1625 goto end;
1626 }
1627
44a2fbf1
JG
1628 memcpy(&msg, payload->data, sizeof(msg));
1629 msg.major = be32toh(msg.major);
1630 msg.minor = be32toh(msg.minor);
1631
53efb85a 1632 memset(&reply, 0, sizeof(reply));
d83a952c
MD
1633 reply.major = RELAYD_VERSION_COMM_MAJOR;
1634 reply.minor = RELAYD_VERSION_COMM_MINOR;
d4519fa3
JD
1635
1636 /* Major versions must be the same */
44a2fbf1 1637 if (reply.major != msg.major) {
6151a90f 1638 DBG("Incompatible major versions (%u vs %u), deleting session",
44a2fbf1 1639 reply.major, msg.major);
40096142 1640 compatible = false;
d4519fa3
JD
1641 }
1642
58eb9381 1643 conn->major = reply.major;
0f907de1 1644 /* We adapt to the lowest compatible version */
44a2fbf1 1645 if (reply.minor <= msg.minor) {
58eb9381 1646 conn->minor = reply.minor;
0f907de1 1647 } else {
44a2fbf1 1648 conn->minor = msg.minor;
0f907de1
JD
1649 }
1650
6151a90f
JD
1651 reply.major = htobe32(reply.major);
1652 reply.minor = htobe32(reply.minor);
44a2fbf1
JG
1653 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1654 sizeof(reply), 0);
1655 if (send_ret < (ssize_t) sizeof(reply)) {
1656 ERR("Failed to send \"send version\" command reply (ret = %zd)",
1657 send_ret);
1658 ret = -1;
1659 goto end;
1660 } else {
1661 ret = 0;
6151a90f
JD
1662 }
1663
40096142
JD
1664 if (!compatible) {
1665 ret = -1;
1666 goto end;
1667 }
1668
58eb9381
DG
1669 DBG("Version check done using protocol %u.%u", conn->major,
1670 conn->minor);
b8aa1682
JD
1671
1672end:
1673 return ret;
1674}
1675
c8f59ee5 1676/*
6d805429 1677 * Check for data pending for a given stream id from the session daemon.
c8f59ee5 1678 */
44a2fbf1
JG
1679static int relay_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
1680 struct relay_connection *conn,
1681 const struct lttng_buffer_view *payload)
c8f59ee5 1682{
58eb9381 1683 struct relay_session *session = conn->session;
6d805429 1684 struct lttcomm_relayd_data_pending msg;
c8f59ee5
DG
1685 struct lttcomm_relayd_generic_reply reply;
1686 struct relay_stream *stream;
44a2fbf1 1687 ssize_t send_ret;
c8f59ee5 1688 int ret;
c8f59ee5 1689
6d805429 1690 DBG("Data pending command received");
c8f59ee5 1691
44a2fbf1 1692 if (!session || !conn->version_check_done) {
c8f59ee5
DG
1693 ERR("Trying to check for data before version check");
1694 ret = -1;
1695 goto end_no_session;
1696 }
1697
44a2fbf1
JG
1698 if (payload->size < sizeof(msg)) {
1699 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
1700 sizeof(msg), payload->size);
c8f59ee5
DG
1701 ret = -1;
1702 goto end_no_session;
1703 }
44a2fbf1
JG
1704 memcpy(&msg, payload->data, sizeof(msg));
1705 msg.stream_id = be64toh(msg.stream_id);
1706 msg.last_net_seq_num = be64toh(msg.last_net_seq_num);
c8f59ee5 1707
44a2fbf1 1708 stream = stream_get_by_id(msg.stream_id);
de91f48a 1709 if (stream == NULL) {
c8f59ee5 1710 ret = -1;
7591bab1 1711 goto end;
c8f59ee5
DG
1712 }
1713
7591bab1
MD
1714 pthread_mutex_lock(&stream->lock);
1715
6d805429 1716 DBG("Data pending for stream id %" PRIu64 " prev_seq %" PRIu64
44a2fbf1
JG
1717 " and last_seq %" PRIu64, msg.stream_id,
1718 stream->prev_seq, msg.last_net_seq_num);
c8f59ee5 1719
33832e64 1720 /* Avoid wrapping issue */
44a2fbf1 1721 if (((int64_t) (stream->prev_seq - msg.last_net_seq_num)) >= 0) {
6d805429 1722 /* Data has in fact been written and is NOT pending */
c8f59ee5 1723 ret = 0;
6d805429
DG
1724 } else {
1725 /* Data still being streamed thus pending */
1726 ret = 1;
c8f59ee5
DG
1727 }
1728
7591bab1
MD
1729 stream->data_pending_check_done = true;
1730 pthread_mutex_unlock(&stream->lock);
f7079f67 1731
7591bab1
MD
1732 stream_put(stream);
1733end:
c8f59ee5 1734
53efb85a 1735 memset(&reply, 0, sizeof(reply));
c8f59ee5 1736 reply.ret_code = htobe32(ret);
44a2fbf1
JG
1737 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1738 if (send_ret < (ssize_t) sizeof(reply)) {
1739 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
1740 send_ret);
1741 ret = -1;
c8f59ee5
DG
1742 }
1743
1744end_no_session:
1745 return ret;
1746}
1747
1748/*
1749 * Wait for the control socket to reach a quiescent state.
1750 *
7591bab1
MD
1751 * Note that for now, when receiving this command from the session
1752 * daemon, this means that every subsequent commands or data received on
1753 * the control socket has been handled. So, this is why we simply return
1754 * OK here.
c8f59ee5 1755 */
44a2fbf1
JG
1756static int relay_quiescent_control(const struct lttcomm_relayd_hdr *recv_hdr,
1757 struct relay_connection *conn,
1758 const struct lttng_buffer_view *payload)
c8f59ee5
DG
1759{
1760 int ret;
44a2fbf1 1761 ssize_t send_ret;
ad7051c0 1762 struct relay_stream *stream;
ad7051c0 1763 struct lttcomm_relayd_quiescent_control msg;
c8f59ee5
DG
1764 struct lttcomm_relayd_generic_reply reply;
1765
1766 DBG("Checking quiescent state on control socket");
1767
44a2fbf1 1768 if (!conn->session || !conn->version_check_done) {
ad7051c0
DG
1769 ERR("Trying to check for data before version check");
1770 ret = -1;
1771 goto end_no_session;
1772 }
1773
44a2fbf1
JG
1774 if (payload->size < sizeof(msg)) {
1775 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
1776 sizeof(msg), payload->size);
ad7051c0
DG
1777 ret = -1;
1778 goto end_no_session;
1779 }
44a2fbf1
JG
1780 memcpy(&msg, payload->data, sizeof(msg));
1781 msg.stream_id = be64toh(msg.stream_id);
ad7051c0 1782
44a2fbf1 1783 stream = stream_get_by_id(msg.stream_id);
7591bab1
MD
1784 if (!stream) {
1785 goto reply;
1786 }
1787 pthread_mutex_lock(&stream->lock);
1788 stream->data_pending_check_done = true;
1789 pthread_mutex_unlock(&stream->lock);
44a2fbf1
JG
1790
1791 DBG("Relay quiescent control pending flag set to %" PRIu64, msg.stream_id);
7591bab1
MD
1792 stream_put(stream);
1793reply:
53efb85a 1794 memset(&reply, 0, sizeof(reply));
c8f59ee5 1795 reply.ret_code = htobe32(LTTNG_OK);
44a2fbf1
JG
1796 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1797 if (send_ret < (ssize_t) sizeof(reply)) {
1798 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
1799 send_ret);
1800 ret = -1;
1801 } else {
1802 ret = 0;
c8f59ee5
DG
1803 }
1804
ad7051c0 1805end_no_session:
c8f59ee5
DG
1806 return ret;
1807}
1808
f7079f67 1809/*
7591bab1
MD
1810 * Initialize a data pending command. This means that a consumer is about
1811 * to ask for data pending for each stream it holds. Simply iterate over
1812 * all streams of a session and set the data_pending_check_done flag.
f7079f67
DG
1813 *
1814 * This command returns to the client a LTTNG_OK code.
1815 */
44a2fbf1
JG
1816static int relay_begin_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
1817 struct relay_connection *conn,
1818 const struct lttng_buffer_view *payload)
f7079f67
DG
1819{
1820 int ret;
44a2fbf1 1821 ssize_t send_ret;
f7079f67
DG
1822 struct lttng_ht_iter iter;
1823 struct lttcomm_relayd_begin_data_pending msg;
1824 struct lttcomm_relayd_generic_reply reply;
1825 struct relay_stream *stream;
f7079f67
DG
1826
1827 assert(recv_hdr);
58eb9381 1828 assert(conn);
f7079f67
DG
1829
1830 DBG("Init streams for data pending");
1831
44a2fbf1 1832 if (!conn->session || !conn->version_check_done) {
f7079f67
DG
1833 ERR("Trying to check for data before version check");
1834 ret = -1;
1835 goto end_no_session;
1836 }
1837
44a2fbf1
JG
1838 if (payload->size < sizeof(msg)) {
1839 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
1840 sizeof(msg), payload->size);
f7079f67
DG
1841 ret = -1;
1842 goto end_no_session;
1843 }
44a2fbf1
JG
1844 memcpy(&msg, payload->data, sizeof(msg));
1845 msg.session_id = be64toh(msg.session_id);
f7079f67
DG
1846
1847 /*
7591bab1
MD
1848 * Iterate over all streams to set the begin data pending flag.
1849 * For now, the streams are indexed by stream handle so we have
1850 * to iterate over all streams to find the one associated with
1851 * the right session_id.
f7079f67
DG
1852 */
1853 rcu_read_lock();
d3e2ba59 1854 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2a174661 1855 node.node) {
7591bab1
MD
1856 if (!stream_get(stream)) {
1857 continue;
1858 }
44a2fbf1 1859 if (stream->trace->session->id == msg.session_id) {
7591bab1
MD
1860 pthread_mutex_lock(&stream->lock);
1861 stream->data_pending_check_done = false;
1862 pthread_mutex_unlock(&stream->lock);
f7079f67
DG
1863 DBG("Set begin data pending flag to stream %" PRIu64,
1864 stream->stream_handle);
1865 }
7591bab1 1866 stream_put(stream);
f7079f67
DG
1867 }
1868 rcu_read_unlock();
1869
53efb85a 1870 memset(&reply, 0, sizeof(reply));
f7079f67
DG
1871 /* All good, send back reply. */
1872 reply.ret_code = htobe32(LTTNG_OK);
1873
44a2fbf1
JG
1874 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1875 if (send_ret < (ssize_t) sizeof(reply)) {
1876 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
1877 send_ret);
1878 ret = -1;
1879 } else {
1880 ret = 0;
f7079f67
DG
1881 }
1882
1883end_no_session:
1884 return ret;
1885}
1886
1887/*
7591bab1
MD
1888 * End data pending command. This will check, for a given session id, if
1889 * each stream associated with it has its data_pending_check_done flag
1890 * set. If not, this means that the client lost track of the stream but
1891 * the data is still being streamed on our side. In this case, we inform
1892 * the client that data is in flight.
f7079f67
DG
1893 *
1894 * Return to the client if there is data in flight or not with a ret_code.
1895 */
44a2fbf1
JG
1896static int relay_end_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
1897 struct relay_connection *conn,
1898 const struct lttng_buffer_view *payload)
f7079f67
DG
1899{
1900 int ret;
44a2fbf1 1901 ssize_t send_ret;
f7079f67
DG
1902 struct lttng_ht_iter iter;
1903 struct lttcomm_relayd_end_data_pending msg;
1904 struct lttcomm_relayd_generic_reply reply;
1905 struct relay_stream *stream;
f7079f67
DG
1906 uint32_t is_data_inflight = 0;
1907
f7079f67
DG
1908 DBG("End data pending command");
1909
44a2fbf1 1910 if (!conn->session || !conn->version_check_done) {
f7079f67
DG
1911 ERR("Trying to check for data before version check");
1912 ret = -1;
1913 goto end_no_session;
1914 }
1915
44a2fbf1
JG
1916 if (payload->size < sizeof(msg)) {
1917 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
1918 sizeof(msg), payload->size);
f7079f67
DG
1919 ret = -1;
1920 goto end_no_session;
1921 }
44a2fbf1
JG
1922 memcpy(&msg, payload->data, sizeof(msg));
1923 msg.session_id = be64toh(msg.session_id);
f7079f67 1924
7591bab1
MD
1925 /*
1926 * Iterate over all streams to see if the begin data pending
1927 * flag is set.
1928 */
f7079f67 1929 rcu_read_lock();
d3e2ba59 1930 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
2a174661 1931 node.node) {
7591bab1
MD
1932 if (!stream_get(stream)) {
1933 continue;
1934 }
44a2fbf1 1935 if (stream->trace->session->id != msg.session_id) {
7591bab1
MD
1936 stream_put(stream);
1937 continue;
1938 }
1939 pthread_mutex_lock(&stream->lock);
1940 if (!stream->data_pending_check_done) {
1941 if (!stream->closed || !(((int64_t) (stream->prev_seq - stream->last_net_seq_num)) >= 0)) {
1942 is_data_inflight = 1;
1943 DBG("Data is still in flight for stream %" PRIu64,
1944 stream->stream_handle);
1945 pthread_mutex_unlock(&stream->lock);
1946 stream_put(stream);
1947 break;
1948 }
f7079f67 1949 }
7591bab1
MD
1950 pthread_mutex_unlock(&stream->lock);
1951 stream_put(stream);
f7079f67
DG
1952 }
1953 rcu_read_unlock();
1954
53efb85a 1955 memset(&reply, 0, sizeof(reply));
f7079f67
DG
1956 /* All good, send back reply. */
1957 reply.ret_code = htobe32(is_data_inflight);
1958
44a2fbf1
JG
1959 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1960 if (send_ret < (ssize_t) sizeof(reply)) {
1961 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
1962 send_ret);
1963 ret = -1;
1964 } else {
1965 ret = 0;
f7079f67
DG
1966 }
1967
1968end_no_session:
1969 return ret;
1970}
1971
1c20f0e2
JD
1972/*
1973 * Receive an index for a specific stream.
1974 *
1975 * Return 0 on success else a negative value.
1976 */
44a2fbf1
JG
1977static int relay_recv_index(const struct lttcomm_relayd_hdr *recv_hdr,
1978 struct relay_connection *conn,
1979 const struct lttng_buffer_view *payload)
1c20f0e2 1980{
44a2fbf1
JG
1981 int ret;
1982 ssize_t send_ret;
58eb9381 1983 struct relay_session *session = conn->session;
1c20f0e2 1984 struct lttcomm_relayd_index index_info;
7591bab1 1985 struct relay_index *index;
1c20f0e2
JD
1986 struct lttcomm_relayd_generic_reply reply;
1987 struct relay_stream *stream;
e0547b83 1988 size_t msg_len;
1c20f0e2 1989
58eb9381 1990 assert(conn);
1c20f0e2
JD
1991
1992 DBG("Relay receiving index");
1993
44a2fbf1 1994 if (!session || !conn->version_check_done) {
1c20f0e2
JD
1995 ERR("Trying to close a stream before version check");
1996 ret = -1;
1997 goto end_no_session;
1998 }
1999
e0547b83
MD
2000 msg_len = lttcomm_relayd_index_len(
2001 lttng_to_index_major(conn->major, conn->minor),
2002 lttng_to_index_minor(conn->major, conn->minor));
44a2fbf1
JG
2003 if (payload->size < msg_len) {
2004 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2005 msg_len, payload->size);
1c20f0e2
JD
2006 ret = -1;
2007 goto end_no_session;
2008 }
44a2fbf1
JG
2009 memcpy(&index_info, payload->data, msg_len);
2010 index_info.relay_stream_id = be64toh(index_info.relay_stream_id);
2011 index_info.net_seq_num = be64toh(index_info.net_seq_num);
2012 index_info.packet_size = be64toh(index_info.packet_size);
2013 index_info.content_size = be64toh(index_info.content_size);
2014 index_info.timestamp_begin = be64toh(index_info.timestamp_begin);
2015 index_info.timestamp_end = be64toh(index_info.timestamp_end);
2016 index_info.events_discarded = be64toh(index_info.events_discarded);
2017 index_info.stream_id = be64toh(index_info.stream_id);
1c20f0e2 2018
44a2fbf1
JG
2019 if (conn->minor >= 8) {
2020 index_info.stream_instance_id =
2021 be64toh(index_info.stream_instance_id);
2022 index_info.packet_seq_num = be64toh(index_info.packet_seq_num);
2023 }
1c20f0e2 2024
44a2fbf1 2025 stream = stream_get_by_id(index_info.relay_stream_id);
1c20f0e2 2026 if (!stream) {
7591bab1 2027 ERR("stream_get_by_id not found");
1c20f0e2 2028 ret = -1;
7591bab1 2029 goto end;
1c20f0e2 2030 }
7591bab1 2031 pthread_mutex_lock(&stream->lock);
1c20f0e2 2032
d3e2ba59
JD
2033 /* Live beacon handling */
2034 if (index_info.packet_size == 0) {
7591bab1
MD
2035 DBG("Received live beacon for stream %" PRIu64,
2036 stream->stream_handle);
d3e2ba59
JD
2037
2038 /*
7591bab1
MD
2039 * Only flag a stream inactive when it has already
2040 * received data and no indexes are in flight.
d3e2ba59 2041 */
a44ca2ca 2042 if (stream->index_received_seqcount > 0
7591bab1 2043 && stream->indexes_in_flight == 0) {
44a2fbf1 2044 stream->beacon_ts_end = index_info.timestamp_end;
d3e2ba59
JD
2045 }
2046 ret = 0;
7591bab1 2047 goto end_stream_put;
d3e2ba59
JD
2048 } else {
2049 stream->beacon_ts_end = -1ULL;
2050 }
2051
528f2ffa 2052 if (stream->ctf_stream_id == -1ULL) {
44a2fbf1 2053 stream->ctf_stream_id = index_info.stream_id;
528f2ffa 2054 }
44a2fbf1 2055 index = relay_index_get_by_id_or_create(stream, index_info.net_seq_num);
7591bab1
MD
2056 if (!index) {
2057 ret = -1;
2058 ERR("relay_index_get_by_id_or_create index NULL");
2059 goto end_stream_put;
1c20f0e2 2060 }
234cd636 2061 if (set_index_control_data(index, &index_info, conn)) {
7591bab1
MD
2062 ERR("set_index_control_data error");
2063 relay_index_put(index);
2064 ret = -1;
2065 goto end_stream_put;
2066 }
2067 ret = relay_index_try_flush(index);
2068 if (ret == 0) {
a44ca2ca
MD
2069 tracefile_array_commit_seq(stream->tfa);
2070 stream->index_received_seqcount++;
7591bab1
MD
2071 } else if (ret > 0) {
2072 /* no flush. */
2073 ret = 0;
2074 } else {
2075 ERR("relay_index_try_flush error %d", ret);
2076 relay_index_put(index);
2077 ret = -1;
1c20f0e2
JD
2078 }
2079
7591bab1
MD
2080end_stream_put:
2081 pthread_mutex_unlock(&stream->lock);
2082 stream_put(stream);
2083
2084end:
1c20f0e2 2085
53efb85a 2086 memset(&reply, 0, sizeof(reply));
1c20f0e2
JD
2087 if (ret < 0) {
2088 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2089 } else {
2090 reply.ret_code = htobe32(LTTNG_OK);
2091 }
58eb9381 2092 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
44a2fbf1
JG
2093 if (send_ret < (ssize_t) sizeof(reply)) {
2094 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret);
2095 ret = -1;
1c20f0e2
JD
2096 }
2097
2098end_no_session:
2099 return ret;
2100}
2101
a4baae1b
JD
2102/*
2103 * Receive the streams_sent message.
2104 *
2105 * Return 0 on success else a negative value.
2106 */
44a2fbf1
JG
2107static int relay_streams_sent(const struct lttcomm_relayd_hdr *recv_hdr,
2108 struct relay_connection *conn,
2109 const struct lttng_buffer_view *payload)
a4baae1b 2110{
44a2fbf1
JG
2111 int ret;
2112 ssize_t send_ret;
a4baae1b
JD
2113 struct lttcomm_relayd_generic_reply reply;
2114
58eb9381 2115 assert(conn);
a4baae1b
JD
2116
2117 DBG("Relay receiving streams_sent");
2118
44a2fbf1 2119 if (!conn->session || !conn->version_check_done) {
a4baae1b
JD
2120 ERR("Trying to close a stream before version check");
2121 ret = -1;
2122 goto end_no_session;
2123 }
2124
2125 /*
7591bab1
MD
2126 * Publish every pending stream in the connection recv list which are
2127 * now ready to be used by the viewer.
4a9daf17 2128 */
7591bab1 2129 publish_connection_local_streams(conn);
4a9daf17 2130
53efb85a 2131 memset(&reply, 0, sizeof(reply));
a4baae1b 2132 reply.ret_code = htobe32(LTTNG_OK);
58eb9381 2133 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
44a2fbf1
JG
2134 if (send_ret < (ssize_t) sizeof(reply)) {
2135 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2136 send_ret);
2137 ret = -1;
a4baae1b
JD
2138 } else {
2139 /* Success. */
2140 ret = 0;
2141 }
2142
2143end_no_session:
2144 return ret;
2145}
2146
44a2fbf1
JG
2147#define DBG_CMD(cmd_name, conn) \
2148 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
2149
2150static int relay_process_control_command(struct relay_connection *conn,
2151 const struct lttcomm_relayd_hdr *header,
2152 const struct lttng_buffer_view *payload)
b8aa1682
JD
2153{
2154 int ret = 0;
2155
44a2fbf1 2156 switch (header->cmd) {
b8aa1682 2157 case RELAYD_CREATE_SESSION:
44a2fbf1
JG
2158 DBG_CMD("RELAYD_CREATE_SESSION", conn);
2159 ret = relay_create_session(header, conn, payload);
b8aa1682 2160 break;
b8aa1682 2161 case RELAYD_ADD_STREAM:
44a2fbf1
JG
2162 DBG_CMD("RELAYD_ADD_STREAM", conn);
2163 ret = relay_add_stream(header, conn, payload);
b8aa1682
JD
2164 break;
2165 case RELAYD_START_DATA:
44a2fbf1
JG
2166 DBG_CMD("RELAYD_START_DATA", conn);
2167 ret = relay_start(header, conn, payload);
b8aa1682
JD
2168 break;
2169 case RELAYD_SEND_METADATA:
44a2fbf1
JG
2170 DBG_CMD("RELAYD_SEND_METADATA", conn);
2171 ret = relay_recv_metadata(header, conn, payload);
b8aa1682
JD
2172 break;
2173 case RELAYD_VERSION:
44a2fbf1
JG
2174 DBG_CMD("RELAYD_VERSION", conn);
2175 ret = relay_send_version(header, conn, payload);
b8aa1682 2176 break;
173af62f 2177 case RELAYD_CLOSE_STREAM:
44a2fbf1
JG
2178 DBG_CMD("RELAYD_CLOSE_STREAM", conn);
2179 ret = relay_close_stream(header, conn, payload);
173af62f 2180 break;
6d805429 2181 case RELAYD_DATA_PENDING:
44a2fbf1
JG
2182 DBG_CMD("RELAYD_DATA_PENDING", conn);
2183 ret = relay_data_pending(header, conn, payload);
c8f59ee5
DG
2184 break;
2185 case RELAYD_QUIESCENT_CONTROL:
44a2fbf1
JG
2186 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn);
2187 ret = relay_quiescent_control(header, conn, payload);
c8f59ee5 2188 break;
f7079f67 2189 case RELAYD_BEGIN_DATA_PENDING:
44a2fbf1
JG
2190 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn);
2191 ret = relay_begin_data_pending(header, conn, payload);
f7079f67
DG
2192 break;
2193 case RELAYD_END_DATA_PENDING:
44a2fbf1
JG
2194 DBG_CMD("RELAYD_END_DATA_PENDING", conn);
2195 ret = relay_end_data_pending(header, conn, payload);
f7079f67 2196 break;
1c20f0e2 2197 case RELAYD_SEND_INDEX:
44a2fbf1
JG
2198 DBG_CMD("RELAYD_SEND_INDEX", conn);
2199 ret = relay_recv_index(header, conn, payload);
1c20f0e2 2200 break;
a4baae1b 2201 case RELAYD_STREAMS_SENT:
44a2fbf1
JG
2202 DBG_CMD("RELAYD_STREAMS_SENT", conn);
2203 ret = relay_streams_sent(header, conn, payload);
a4baae1b 2204 break;
93ec662e 2205 case RELAYD_RESET_METADATA:
44a2fbf1
JG
2206 DBG_CMD("RELAYD_RESET_METADATA", conn);
2207 ret = relay_reset_metadata(header, conn, payload);
93ec662e 2208 break;
b8aa1682
JD
2209 case RELAYD_UPDATE_SYNC_INFO:
2210 default:
44a2fbf1 2211 ERR("Received unknown command (%u)", header->cmd);
58eb9381 2212 relay_unknown_command(conn);
b8aa1682
JD
2213 ret = -1;
2214 goto end;
2215 }
2216
2217end:
2218 return ret;
2219}
2220
44a2fbf1
JG
2221static enum relay_connection_status relay_process_control_receive_payload(
2222 struct relay_connection *conn)
2223{
2224 int ret = 0;
2225 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
2226 struct lttng_dynamic_buffer *reception_buffer =
2227 &conn->protocol.ctrl.reception_buffer;
2228 struct ctrl_connection_state_receive_payload *state =
2229 &conn->protocol.ctrl.state.receive_payload;
2230 struct lttng_buffer_view payload_view;
2231
2232 if (state->left_to_receive == 0) {
2233 /* Short-circuit for payload-less commands. */
2234 goto reception_complete;
2235 }
2236 ret = conn->sock->ops->recvmsg(conn->sock,
2237 reception_buffer->data + state->received,
2238 state->left_to_receive, MSG_DONTWAIT);
2239 if (ret < 0) {
2240 if (errno != EAGAIN && errno != EWOULDBLOCK) {
2241 PERROR("Unable to receive command payload on sock %d",
2242 conn->sock->fd);
2243 status = RELAY_CONNECTION_STATUS_ERROR;
2244 }
2245 goto end;
2246 } else if (ret == 0) {
2247 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
2248 status = RELAY_CONNECTION_STATUS_CLOSED;
2249 goto end;
2250 }
2251
2252 assert(ret > 0);
2253 assert(ret <= state->left_to_receive);
2254
2255 state->left_to_receive -= ret;
2256 state->received += ret;
2257
2258 if (state->left_to_receive > 0) {
2259 /*
2260 * Can't transition to the protocol's next state, wait to
2261 * receive the rest of the header.
2262 */
2263 DBG3("Partial reception of control connection protocol payload (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
2264 state->received, state->left_to_receive,
2265 conn->sock->fd);
2266 goto end;
2267 }
2268
2269reception_complete:
2270 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64 " bytes",
2271 conn->sock->fd, state->received);
2272 /*
2273 * The payload required to process the command has been received.
2274 * A view to the reception buffer is forwarded to the various
2275 * commands and the state of the control is reset on success.
2276 *
2277 * Commands are responsible for sending their reply to the peer.
2278 */
2279 payload_view = lttng_buffer_view_from_dynamic_buffer(reception_buffer,
2280 0, -1);
2281 ret = relay_process_control_command(conn,
2282 &state->header, &payload_view);
2283 if (ret < 0) {
2284 status = RELAY_CONNECTION_STATUS_ERROR;
2285 goto end;
2286 }
2287
2288 ret = connection_reset_protocol_state(conn);
2289 if (ret) {
2290 status = RELAY_CONNECTION_STATUS_ERROR;
2291 }
2292end:
2293 return status;
2294}
2295
2296static enum relay_connection_status relay_process_control_receive_header(
2297 struct relay_connection *conn)
2298{
2299 int ret = 0;
2300 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
2301 struct lttcomm_relayd_hdr header;
2302 struct lttng_dynamic_buffer *reception_buffer =
2303 &conn->protocol.ctrl.reception_buffer;
2304 struct ctrl_connection_state_receive_header *state =
2305 &conn->protocol.ctrl.state.receive_header;
2306
2307 assert(state->left_to_receive != 0);
2308
2309 ret = conn->sock->ops->recvmsg(conn->sock,
2310 reception_buffer->data + state->received,
2311 state->left_to_receive, MSG_DONTWAIT);
2312 if (ret < 0) {
2313 if (errno != EAGAIN && errno != EWOULDBLOCK) {
2314 PERROR("Unable to receive control command header on sock %d",
2315 conn->sock->fd);
2316 status = RELAY_CONNECTION_STATUS_ERROR;
2317 }
2318 goto end;
2319 } else if (ret == 0) {
2320 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
2321 status = RELAY_CONNECTION_STATUS_CLOSED;
2322 goto end;
2323 }
2324
2325 assert(ret > 0);
2326 assert(ret <= state->left_to_receive);
2327
2328 state->left_to_receive -= ret;
2329 state->received += ret;
2330
2331 if (state->left_to_receive > 0) {
2332 /*
2333 * Can't transition to the protocol's next state, wait to
2334 * receive the rest of the header.
2335 */
2336 DBG3("Partial reception of control connection protocol header (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
2337 state->received, state->left_to_receive,
2338 conn->sock->fd);
2339 goto end;
2340 }
2341
2342 /* Transition to next state: receiving the command's payload. */
2343 conn->protocol.ctrl.state_id =
2344 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD;
2345 memcpy(&header, reception_buffer->data, sizeof(header));
2346 header.circuit_id = be64toh(header.circuit_id);
2347 header.data_size = be64toh(header.data_size);
2348 header.cmd = be32toh(header.cmd);
2349 header.cmd_version = be32toh(header.cmd_version);
2350 memcpy(&conn->protocol.ctrl.state.receive_payload.header,
2351 &header, sizeof(header));
2352
2353 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32 ", cmd_version = %" PRIu32 ", payload size = %" PRIu64 " bytes",
2354 conn->sock->fd, header.cmd, header.cmd_version,
2355 header.data_size);
2356
2357 if (header.data_size > DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE) {
2358 ERR("Command header indicates a payload (%" PRIu64 " bytes) that exceeds the maximal payload size allowed on a control connection.",
2359 header.data_size);
2360 status = RELAY_CONNECTION_STATUS_ERROR;
2361 goto end;
2362 }
2363
2364 conn->protocol.ctrl.state.receive_payload.left_to_receive =
2365 header.data_size;
2366 conn->protocol.ctrl.state.receive_payload.received = 0;
2367 ret = lttng_dynamic_buffer_set_size(reception_buffer,
2368 header.data_size);
2369 if (ret) {
2370 status = RELAY_CONNECTION_STATUS_ERROR;
2371 goto end;
2372 }
2373
2374 if (header.data_size == 0) {
2375 /*
2376 * Manually invoke the next state as the poll loop
2377 * will not wake-up to allow us to proceed further.
2378 */
2379 status = relay_process_control_receive_payload(conn);
2380 }
2381end:
2382 return status;
2383}
2384
2385/*
2386 * Process the commands received on the control socket
2387 */
2388static enum relay_connection_status relay_process_control(
2389 struct relay_connection *conn)
2390{
2391 enum relay_connection_status status;
2392
2393 switch (conn->protocol.ctrl.state_id) {
2394 case CTRL_CONNECTION_STATE_RECEIVE_HEADER:
2395 status = relay_process_control_receive_header(conn);
2396 break;
2397 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD:
2398 status = relay_process_control_receive_payload(conn);
2399 break;
2400 default:
2401 ERR("Unknown control connection protocol state encountered.");
2402 abort();
2403 }
2404
2405 return status;
2406}
2407
7d2f7452
DG
2408/*
2409 * Handle index for a data stream.
2410 *
7591bab1 2411 * Called with the stream lock held.
7d2f7452
DG
2412 *
2413 * Return 0 on success else a negative value.
2414 */
2415static int handle_index_data(struct relay_stream *stream, uint64_t net_seq_num,
44a2fbf1 2416 bool rotate_index)
7d2f7452 2417{
7591bab1
MD
2418 int ret = 0;
2419 uint64_t data_offset;
2420 struct relay_index *index;
7d2f7452 2421
7d2f7452
DG
2422 /* Get data offset because we are about to update the index. */
2423 data_offset = htobe64(stream->tracefile_size_current);
2424
65d66b19
MD
2425 DBG("handle_index_data: stream %" PRIu64 " net_seq_num %" PRIu64 " data offset %" PRIu64,
2426 stream->stream_handle, net_seq_num, stream->tracefile_size_current);
7591bab1 2427
7d2f7452 2428 /*
7591bab1
MD
2429 * Lookup for an existing index for that stream id/sequence
2430 * number. If it exists, the control thread has already received the
2431 * data for it, thus we need to write it to disk.
7d2f7452 2432 */
7591bab1 2433 index = relay_index_get_by_id_or_create(stream, net_seq_num);
7d2f7452 2434 if (!index) {
7591bab1
MD
2435 ret = -1;
2436 goto end;
7d2f7452
DG
2437 }
2438
e0547b83
MD
2439 if (rotate_index || !stream->index_file) {
2440 uint32_t major, minor;
7591bab1 2441
e0547b83
MD
2442 /* Put ref on previous index_file. */
2443 if (stream->index_file) {
2444 lttng_index_file_put(stream->index_file);
2445 stream->index_file = NULL;
7d2f7452 2446 }
e0547b83
MD
2447 major = stream->trace->session->major;
2448 minor = stream->trace->session->minor;
2449 stream->index_file = lttng_index_file_create(stream->path_name,
2450 stream->channel_name,
7591bab1 2451 -1, -1, stream->tracefile_size,
e0547b83
MD
2452 tracefile_array_get_file_index_head(stream->tfa),
2453 lttng_to_index_major(major, minor),
2454 lttng_to_index_minor(major, minor));
2455 if (!stream->index_file) {
7591bab1
MD
2456 ret = -1;
2457 /* Put self-ref for this index due to error. */
2458 relay_index_put(index);
e0547b83 2459 index = NULL;
7591bab1 2460 goto end;
7d2f7452 2461 }
7d2f7452
DG
2462 }
2463
e0547b83 2464 if (relay_index_set_file(index, stream->index_file, data_offset)) {
7591bab1
MD
2465 ret = -1;
2466 /* Put self-ref for this index due to error. */
2467 relay_index_put(index);
e0547b83 2468 index = NULL;
7591bab1 2469 goto end;
7d2f7452
DG
2470 }
2471
7591bab1
MD
2472 ret = relay_index_try_flush(index);
2473 if (ret == 0) {
a44ca2ca
MD
2474 tracefile_array_commit_seq(stream->tfa);
2475 stream->index_received_seqcount++;
7591bab1
MD
2476 } else if (ret > 0) {
2477 /* No flush. */
2478 ret = 0;
2479 } else {
2480 /* Put self-ref for this index due to error. */
2481 relay_index_put(index);
e0547b83 2482 index = NULL;
7591bab1
MD
2483 ret = -1;
2484 }
2485end:
7d2f7452
DG
2486 return ret;
2487}
2488
44a2fbf1
JG
2489static enum relay_connection_status relay_process_data_receive_header(
2490 struct relay_connection *conn)
b8aa1682 2491{
44a2fbf1
JG
2492 int ret;
2493 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
2494 struct data_connection_state_receive_header *state =
2495 &conn->protocol.data.state.receive_header;
2496 struct lttcomm_relayd_data_hdr header;
b8aa1682 2497 struct relay_stream *stream;
b8aa1682 2498
44a2fbf1
JG
2499 assert(state->left_to_receive != 0);
2500
2501 ret = conn->sock->ops->recvmsg(conn->sock,
2502 state->header_reception_buffer + state->received,
2503 state->left_to_receive, MSG_DONTWAIT);
2504 if (ret < 0) {
2505 if (errno != EAGAIN && errno != EWOULDBLOCK) {
2506 PERROR("Unable to receive data header on sock %d", conn->sock->fd);
2507 status = RELAY_CONNECTION_STATUS_ERROR;
a6cd2b97 2508 }
44a2fbf1
JG
2509 goto end;
2510 } else if (ret == 0) {
2511 /* Orderly shutdown. Not necessary to print an error. */
2512 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
2513 status = RELAY_CONNECTION_STATUS_CLOSED;
b8aa1682
JD
2514 goto end;
2515 }
2516
44a2fbf1
JG
2517 assert(ret > 0);
2518 assert(ret <= state->left_to_receive);
2519
2520 state->left_to_receive -= ret;
2521 state->received += ret;
2522
2523 if (state->left_to_receive > 0) {
2524 /*
2525 * Can't transition to the protocol's next state, wait to
2526 * receive the rest of the header.
2527 */
2528 DBG3("Partial reception of data connection header (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
2529 state->received, state->left_to_receive,
2530 conn->sock->fd);
2531 ret = 0;
7591bab1 2532 goto end;
b8aa1682 2533 }
b8aa1682 2534
44a2fbf1
JG
2535 /* Transition to next state: receiving the payload. */
2536 conn->protocol.data.state_id = DATA_CONNECTION_STATE_RECEIVE_PAYLOAD;
173af62f 2537
44a2fbf1
JG
2538 memcpy(&header, state->header_reception_buffer, sizeof(header));
2539 header.circuit_id = be64toh(header.circuit_id);
2540 header.stream_id = be64toh(header.stream_id);
2541 header.data_size = be32toh(header.data_size);
2542 header.net_seq_num = be64toh(header.net_seq_num);
2543 header.padding_size = be32toh(header.padding_size);
2544 memcpy(&conn->protocol.data.state.receive_payload.header, &header, sizeof(header));
2545
2546 conn->protocol.data.state.receive_payload.left_to_receive =
2547 header.data_size;
2548 conn->protocol.data.state.receive_payload.received = 0;
2549 conn->protocol.data.state.receive_payload.rotate_index = false;
2550
2551 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64 ", stream_id = %" PRIu64 ", data_size = %" PRIu32 ", net_seq_num = %" PRIu64 ", padding_size = %" PRIu32,
2552 conn->sock->fd, header.circuit_id,
2553 header.stream_id, header.data_size,
2554 header.net_seq_num, header.padding_size);
2555
2556 stream = stream_get_by_id(header.stream_id);
2557 if (!stream) {
2558 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64,
2559 header.stream_id);
2560 /* Protocol error. */
2561 status = RELAY_CONNECTION_STATUS_ERROR;
2562 goto end;
2563 }
b8aa1682 2564
7591bab1
MD
2565 pthread_mutex_lock(&stream->lock);
2566
1c20f0e2 2567 /* Check if a rotation is needed. */
0f907de1 2568 if (stream->tracefile_size > 0 &&
44a2fbf1 2569 (stream->tracefile_size_current + header.data_size) >
0f907de1 2570 stream->tracefile_size) {
a44ca2ca
MD
2571 uint64_t old_id, new_id;
2572
2573 old_id = tracefile_array_get_file_index_head(stream->tfa);
2574 tracefile_array_file_rotate(stream->tfa);
2575
2576 /* new_id is updated by utils_rotate_stream_file. */
2577 new_id = old_id;
6b6b9a5a 2578
7591bab1
MD
2579 ret = utils_rotate_stream_file(stream->path_name,
2580 stream->channel_name, stream->tracefile_size,
2581 stream->tracefile_count, -1,
2582 -1, stream->stream_fd->fd,
a44ca2ca 2583 &new_id, &stream->stream_fd->fd);
0f907de1 2584 if (ret < 0) {
44a2fbf1
JG
2585 ERR("Failed to rotate stream output file");
2586 status = RELAY_CONNECTION_STATUS_ERROR;
7591bab1
MD
2587 goto end_stream_unlock;
2588 }
44a2fbf1 2589
7591bab1
MD
2590 /*
2591 * Reset current size because we just performed a stream
2592 * rotation.
2593 */
a6976990 2594 stream->tracefile_size_current = 0;
44a2fbf1 2595 conn->protocol.data.state.receive_payload.rotate_index = true;
1c20f0e2
JD
2596 }
2597
44a2fbf1
JG
2598 ret = 0;
2599end_stream_unlock:
2600 pthread_mutex_unlock(&stream->lock);
2601 stream_put(stream);
2602end:
2603 return status;
2604}
2605
2606static enum relay_connection_status relay_process_data_receive_payload(
2607 struct relay_connection *conn)
2608{
2609 int ret;
2610 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
2611 struct relay_stream *stream;
2612 struct data_connection_state_receive_payload *state =
2613 &conn->protocol.data.state.receive_payload;
2614 const size_t chunk_size = RECV_DATA_BUFFER_SIZE;
2615 char data_buffer[chunk_size];
2616 bool partial_recv = false;
2617 bool new_stream = false, close_requested = false;
2618 uint64_t left_to_receive = state->left_to_receive;
2619 struct relay_session *session;
2620
2621 DBG3("Receiving data for stream id %" PRIu64 " seqnum %" PRIu64 ", %" PRIu64" bytes received, %" PRIu64 " bytes left to receive",
2622 state->header.stream_id, state->header.net_seq_num,
2623 state->received, left_to_receive);
2624
2625 stream = stream_get_by_id(state->header.stream_id);
2626 if (!stream) {
2627 /* Protocol error. */
2628 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64,
2629 state->header.stream_id);
2630 status = RELAY_CONNECTION_STATUS_ERROR;
2631 goto end;
2632 }
2633
2634 pthread_mutex_lock(&stream->lock);
2635 session = stream->trace->session;
2636 if (!conn->session) {
2637 ret = connection_set_session(conn, session);
2638 if (ret) {
2639 status = RELAY_CONNECTION_STATUS_ERROR;
7591bab1 2640 goto end_stream_unlock;
1c20f0e2 2641 }
1c20f0e2
JD
2642 }
2643
44a2fbf1
JG
2644 /*
2645 * The size of the "chunk" received on any iteration is bounded by:
2646 * - the data left to receive,
2647 * - the data immediately available on the socket,
2648 * - the on-stack data buffer
2649 */
2650 while (left_to_receive > 0 && !partial_recv) {
2651 ssize_t write_ret;
2652 size_t recv_size = min(left_to_receive, chunk_size);
1d4dfdef 2653
44a2fbf1
JG
2654 ret = conn->sock->ops->recvmsg(conn->sock, data_buffer,
2655 recv_size, MSG_DONTWAIT);
2656 if (ret < 0) {
2657 if (errno != EAGAIN && errno != EWOULDBLOCK) {
2658 PERROR("Socket %d error", conn->sock->fd);
2659 status = RELAY_CONNECTION_STATUS_ERROR;
0848dba7 2660 }
0848dba7 2661 goto end_stream_unlock;
44a2fbf1
JG
2662 } else if (ret == 0) {
2663 /* No more data ready to be consumed on socket. */
2664 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64,
2665 state->header.stream_id);
2666 status = RELAY_CONNECTION_STATUS_CLOSED;
2667 break;
2668 } else if (ret < (int) recv_size) {
2669 /*
2670 * All the data available on the socket has been
2671 * consumed.
2672 */
2673 partial_recv = true;
0848dba7
MD
2674 }
2675
44a2fbf1
JG
2676 recv_size = ret;
2677
0848dba7 2678 /* Write data to stream output fd. */
44a2fbf1 2679 write_ret = lttng_write(stream->stream_fd->fd, data_buffer,
0848dba7 2680 recv_size);
44a2fbf1 2681 if (write_ret < (ssize_t) recv_size) {
0848dba7 2682 ERR("Relay error writing data to file");
44a2fbf1 2683 status = RELAY_CONNECTION_STATUS_ERROR;
0848dba7
MD
2684 goto end_stream_unlock;
2685 }
2686
44a2fbf1
JG
2687 left_to_receive -= recv_size;
2688 state->received += recv_size;
2689 state->left_to_receive = left_to_receive;
2690
0848dba7 2691 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64,
44a2fbf1
JG
2692 write_ret, stream->stream_handle);
2693 }
2694
2695 if (state->left_to_receive > 0) {
2696 /*
2697 * Did not receive all the data expected, wait for more data to
2698 * become available on the socket.
2699 */
2700 DBG3("Partial receive on data connection of stream id %" PRIu64 ", %" PRIu64 " bytes received, %" PRIu64 " bytes left to receive",
2701 state->header.stream_id, state->received,
2702 state->left_to_receive);
2703 goto end_stream_unlock;
0848dba7 2704 }
5ab7344e 2705
7591bab1 2706 ret = write_padding_to_file(stream->stream_fd->fd,
44a2fbf1
JG
2707 state->header.padding_size);
2708 if ((int64_t) ret < (int64_t) state->header.padding_size) {
65d66b19 2709 ERR("write_padding_to_file: fail stream %" PRIu64 " net_seq_num %" PRIu64 " ret %d",
44a2fbf1
JG
2710 stream->stream_handle,
2711 state->header.net_seq_num, ret);
2712 status = RELAY_CONNECTION_STATUS_ERROR;
7591bab1 2713 goto end_stream_unlock;
1d4dfdef 2714 }
44a2fbf1
JG
2715
2716
2717 if (session->minor >= 4 && !session->snapshot) {
2718 ret = handle_index_data(stream, state->header.net_seq_num,
2719 state->rotate_index);
2720 if (ret < 0) {
2721 ERR("handle_index_data: fail stream %" PRIu64 " net_seq_num %" PRIu64 " ret %d",
2722 stream->stream_handle,
2723 state->header.net_seq_num, ret);
2724 status = RELAY_CONNECTION_STATUS_ERROR;
2725 goto end_stream_unlock;
2726 }
2727 }
2728
2729 stream->tracefile_size_current += state->header.data_size +
2730 state->header.padding_size;
2731
c0bae11d
MD
2732 if (stream->prev_seq == -1ULL) {
2733 new_stream = true;
2734 }
2735
44a2fbf1
JG
2736 stream->prev_seq = state->header.net_seq_num;
2737
2738 /*
2739 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
2740 * contents of *state which are aliased (union) to the same location as
2741 * the new state. Don't use it beyond this point.
2742 */
2743 connection_reset_protocol_state(conn);
2744 state = NULL;
173af62f 2745
7591bab1 2746end_stream_unlock:
bda7c7b9 2747 close_requested = stream->close_requested;
7591bab1 2748 pthread_mutex_unlock(&stream->lock);
44a2fbf1 2749 if (close_requested && left_to_receive == 0) {
bda7c7b9
JG
2750 try_stream_close(stream);
2751 }
2752
c0bae11d
MD
2753 if (new_stream) {
2754 pthread_mutex_lock(&session->lock);
2755 uatomic_set(&session->new_streams, 1);
2756 pthread_mutex_unlock(&session->lock);
2757 }
44a2fbf1 2758
7591bab1 2759 stream_put(stream);
b8aa1682 2760end:
44a2fbf1
JG
2761 return status;
2762}
2763
2764/*
2765 * relay_process_data: Process the data received on the data socket
2766 */
2767static enum relay_connection_status relay_process_data(
2768 struct relay_connection *conn)
2769{
2770 enum relay_connection_status status;
2771
2772 switch (conn->protocol.data.state_id) {
2773 case DATA_CONNECTION_STATE_RECEIVE_HEADER:
2774 status = relay_process_data_receive_header(conn);
2775 break;
2776 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD:
2777 status = relay_process_data_receive_payload(conn);
2778 break;
2779 default:
2780 ERR("Unexpected data connection communication state.");
2781 abort();
2782 }
2783
2784 return status;
b8aa1682
JD
2785}
2786
7591bab1 2787static void cleanup_connection_pollfd(struct lttng_poll_event *events, int pollfd)
b8aa1682
JD
2788{
2789 int ret;
2790
58eb9381 2791 (void) lttng_poll_del(events, pollfd);
b8aa1682
JD
2792
2793 ret = close(pollfd);
2794 if (ret < 0) {
2795 ERR("Closing pollfd %d", pollfd);
2796 }
2797}
2798
7591bab1
MD
2799static void relay_thread_close_connection(struct lttng_poll_event *events,
2800 int pollfd, struct relay_connection *conn)
9d1bbf21 2801{
7591bab1 2802 const char *type_str;
2a174661 2803
7591bab1
MD
2804 switch (conn->type) {
2805 case RELAY_DATA:
2806 type_str = "Data";
2807 break;
2808 case RELAY_CONTROL:
2809 type_str = "Control";
2810 break;
2811 case RELAY_VIEWER_COMMAND:
2812 type_str = "Viewer Command";
2813 break;
2814 case RELAY_VIEWER_NOTIFICATION:
2815 type_str = "Viewer Notification";
2816 break;
2817 default:
2818 type_str = "Unknown";
9d1bbf21 2819 }
7591bab1
MD
2820 cleanup_connection_pollfd(events, pollfd);
2821 connection_put(conn);
2822 DBG("%s connection closed with %d", type_str, pollfd);
b8aa1682
JD
2823}
2824
2825/*
2826 * This thread does the actual work
2827 */
7591bab1 2828static void *relay_thread_worker(void *data)
b8aa1682 2829{
beaad64c
DG
2830 int ret, err = -1, last_seen_data_fd = -1;
2831 uint32_t nb_fd;
b8aa1682
JD
2832 struct lttng_poll_event events;
2833 struct lttng_ht *relay_connections_ht;
b8aa1682 2834 struct lttng_ht_iter iter;
90e7d72f 2835 struct relay_connection *destroy_conn = NULL;
b8aa1682
JD
2836
2837 DBG("[thread] Relay worker started");
2838
9d1bbf21
MD
2839 rcu_register_thread();
2840
55706a7d
MD
2841 health_register(health_relayd, HEALTH_RELAYD_TYPE_WORKER);
2842
9b5e0863
MD
2843 if (testpoint(relayd_thread_worker)) {
2844 goto error_testpoint;
2845 }
2846
f385ae0a
MD
2847 health_code_update();
2848
b8aa1682
JD
2849 /* table of connections indexed on socket */
2850 relay_connections_ht = lttng_ht_new(0, LTTNG_HT_TYPE_ULONG);
095a4ae5
MD
2851 if (!relay_connections_ht) {
2852 goto relay_connections_ht_error;
2853 }
b8aa1682 2854
b8aa1682
JD
2855 ret = create_thread_poll_set(&events, 2);
2856 if (ret < 0) {
2857 goto error_poll_create;
2858 }
2859
58eb9381 2860 ret = lttng_poll_add(&events, relay_conn_pipe[0], LPOLLIN | LPOLLRDHUP);
b8aa1682
JD
2861 if (ret < 0) {
2862 goto error;
2863 }
2864
beaad64c 2865restart:
b8aa1682 2866 while (1) {
beaad64c
DG
2867 int idx = -1, i, seen_control = 0, last_notdel_data_fd = -1;
2868
f385ae0a
MD
2869 health_code_update();
2870
b8aa1682 2871 /* Infinite blocking call, waiting for transmission */
87c1611d 2872 DBG3("Relayd worker thread polling...");
f385ae0a 2873 health_poll_entry();
b8aa1682 2874 ret = lttng_poll_wait(&events, -1);
f385ae0a 2875 health_poll_exit();
b8aa1682
JD
2876 if (ret < 0) {
2877 /*
2878 * Restart interrupted system call.
2879 */
2880 if (errno == EINTR) {
2881 goto restart;
2882 }
2883 goto error;
2884 }
2885
0d9c5d77
DG
2886 nb_fd = ret;
2887
beaad64c 2888 /*
7591bab1
MD
2889 * Process control. The control connection is
2890 * prioritized so we don't starve it with high
2891 * throughput tracing data on the data connection.
beaad64c 2892 */
b8aa1682
JD
2893 for (i = 0; i < nb_fd; i++) {
2894 /* Fetch once the poll data */
beaad64c
DG
2895 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
2896 int pollfd = LTTNG_POLL_GETFD(&events, i);
b8aa1682 2897
f385ae0a
MD
2898 health_code_update();
2899
fd20dac9 2900 if (!revents) {
7591bab1
MD
2901 /*
2902 * No activity for this FD (poll
2903 * implementation).
2904 */
fd20dac9
MD
2905 continue;
2906 }
2907
b8aa1682
JD
2908 /* Thread quit pipe has been closed. Killing thread. */
2909 ret = check_thread_quit_pipe(pollfd, revents);
2910 if (ret) {
095a4ae5
MD
2911 err = 0;
2912 goto exit;
b8aa1682
JD
2913 }
2914
58eb9381
DG
2915 /* Inspect the relay conn pipe for new connection */
2916 if (pollfd == relay_conn_pipe[0]) {
03e43155 2917 if (revents & LPOLLIN) {
90e7d72f
JG
2918 struct relay_connection *conn;
2919
58eb9381 2920 ret = lttng_read(relay_conn_pipe[0], &conn, sizeof(conn));
b8aa1682
JD
2921 if (ret < 0) {
2922 goto error;
2923 }
58eb9381
DG
2924 lttng_poll_add(&events, conn->sock->fd,
2925 LPOLLIN | LPOLLRDHUP);
7591bab1 2926 connection_ht_add(relay_connections_ht, conn);
58eb9381 2927 DBG("Connection socket %d added", conn->sock->fd);
03e43155
MD
2928 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2929 ERR("Relay connection pipe error");
2930 goto error;
2931 } else {
2932 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
2933 goto error;
b8aa1682 2934 }
58eb9381 2935 } else {
90e7d72f
JG
2936 struct relay_connection *ctrl_conn;
2937
7591bab1 2938 ctrl_conn = connection_get_by_sock(relay_connections_ht, pollfd);
58eb9381 2939 /* If not found, there is a synchronization issue. */
90e7d72f 2940 assert(ctrl_conn);
58eb9381 2941
03e43155
MD
2942 if (ctrl_conn->type == RELAY_DATA) {
2943 if (revents & LPOLLIN) {
beaad64c
DG
2944 /*
2945 * Flag the last seen data fd not deleted. It will be
2946 * used as the last seen fd if any fd gets deleted in
2947 * this first loop.
2948 */
2949 last_notdel_data_fd = pollfd;
2950 }
03e43155
MD
2951 goto put_ctrl_connection;
2952 }
2953 assert(ctrl_conn->type == RELAY_CONTROL);
2954
2955 if (revents & LPOLLIN) {
44a2fbf1
JG
2956 enum relay_connection_status status;
2957
2958 status = relay_process_control(ctrl_conn);
2959 if (status != RELAY_CONNECTION_STATUS_OK) {
2960 /*
2961 * On socket error flag the session as aborted to force
2962 * the cleanup of its stream otherwise it can leak
2963 * during the lifetime of the relayd.
2964 *
2965 * This prevents situations in which streams can be
2966 * left opened because an index was received, the
2967 * control connection is closed, and the data
2968 * connection is closed (uncleanly) before the packet's
2969 * data provided.
2970 *
2971 * Since the control connection encountered an error,
2972 * it is okay to be conservative and close the
2973 * session right now as we can't rely on the protocol
2974 * being respected anymore.
2975 */
2976 if (status == RELAY_CONNECTION_STATUS_ERROR) {
2977 session_abort(ctrl_conn->session);
03e43155 2978 }
44a2fbf1
JG
2979
2980 /* Clear the connection on error or close. */
2981 relay_thread_close_connection(&events,
2982 pollfd,
2983 ctrl_conn);
03e43155 2984 }
44a2fbf1 2985 seen_control = 1;
03e43155
MD
2986 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2987 relay_thread_close_connection(&events,
2988 pollfd, ctrl_conn);
2989 if (last_seen_data_fd == pollfd) {
2990 last_seen_data_fd = last_notdel_data_fd;
2991 }
58eb9381 2992 } else {
03e43155
MD
2993 ERR("Unexpected poll events %u for control sock %d",
2994 revents, pollfd);
2995 connection_put(ctrl_conn);
2996 goto error;
beaad64c 2997 }
03e43155 2998 put_ctrl_connection:
7591bab1 2999 connection_put(ctrl_conn);
beaad64c
DG
3000 }
3001 }
3002
3003 /*
3004 * The last loop handled a control request, go back to poll to make
3005 * sure we prioritise the control socket.
3006 */
3007 if (seen_control) {
3008 continue;
3009 }
3010
3011 if (last_seen_data_fd >= 0) {
3012 for (i = 0; i < nb_fd; i++) {
3013 int pollfd = LTTNG_POLL_GETFD(&events, i);
f385ae0a
MD
3014
3015 health_code_update();
3016
beaad64c
DG
3017 if (last_seen_data_fd == pollfd) {
3018 idx = i;
3019 break;
3020 }
3021 }
3022 }
3023
3024 /* Process data connection. */
3025 for (i = idx + 1; i < nb_fd; i++) {
3026 /* Fetch the poll data. */
3027 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
3028 int pollfd = LTTNG_POLL_GETFD(&events, i);
90e7d72f 3029 struct relay_connection *data_conn;
beaad64c 3030
f385ae0a
MD
3031 health_code_update();
3032
fd20dac9
MD
3033 if (!revents) {
3034 /* No activity for this FD (poll implementation). */
3035 continue;
3036 }
3037
beaad64c 3038 /* Skip the command pipe. It's handled in the first loop. */
58eb9381 3039 if (pollfd == relay_conn_pipe[0]) {
beaad64c
DG
3040 continue;
3041 }
3042
7591bab1 3043 data_conn = connection_get_by_sock(relay_connections_ht, pollfd);
90e7d72f 3044 if (!data_conn) {
fd20dac9 3045 /* Skip it. Might be removed before. */
fd20dac9
MD
3046 continue;
3047 }
03e43155
MD
3048 if (data_conn->type == RELAY_CONTROL) {
3049 goto put_data_connection;
3050 }
3051 assert(data_conn->type == RELAY_DATA);
fd20dac9
MD
3052
3053 if (revents & LPOLLIN) {
44a2fbf1
JG
3054 enum relay_connection_status status;
3055
3056 status = relay_process_data(data_conn);
3057 /* Connection closed or error. */
3058 if (status != RELAY_CONNECTION_STATUS_OK) {
3059 /*
3060 * On socket error flag the session as aborted to force
3061 * the cleanup of its stream otherwise it can leak
3062 * during the lifetime of the relayd.
3063 *
3064 * This prevents situations in which streams can be
3065 * left opened because an index was received, the
3066 * control connection is closed, and the data
3067 * connection is closed (uncleanly) before the packet's
3068 * data provided.
3069 *
3070 * Since the data connection encountered an error,
3071 * it is okay to be conservative and close the
3072 * session right now as we can't rely on the protocol
3073 * being respected anymore.
3074 */
3075 if (status == RELAY_CONNECTION_STATUS_ERROR) {
3076 session_abort(data_conn->session);
3077 }
7591bab1 3078 relay_thread_close_connection(&events, pollfd,
03e43155 3079 data_conn);
fd20dac9
MD
3080 /*
3081 * Every goto restart call sets the last seen fd where
3082 * here we don't really care since we gracefully
3083 * continue the loop after the connection is deleted.
3084 */
3085 } else {
3086 /* Keep last seen port. */
3087 last_seen_data_fd = pollfd;
7591bab1 3088 connection_put(data_conn);
fd20dac9 3089 goto restart;
b8aa1682 3090 }
03e43155
MD
3091 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
3092 relay_thread_close_connection(&events, pollfd,
3093 data_conn);
3094 } else {
3095 ERR("Unknown poll events %u for data sock %d",
3096 revents, pollfd);
b8aa1682 3097 }
03e43155 3098 put_data_connection:
7591bab1 3099 connection_put(data_conn);
b8aa1682 3100 }
beaad64c 3101 last_seen_data_fd = -1;
b8aa1682
JD
3102 }
3103
f385ae0a
MD
3104 /* Normal exit, no error */
3105 ret = 0;
3106
095a4ae5 3107exit:
b8aa1682 3108error:
58eb9381 3109 /* Cleanup reamaining connection object. */
9d1bbf21 3110 rcu_read_lock();
90e7d72f
JG
3111 cds_lfht_for_each_entry(relay_connections_ht->ht, &iter.iter,
3112 destroy_conn,
58eb9381 3113 sock_n.node) {
f385ae0a 3114 health_code_update();
06a68401 3115
44a2fbf1 3116 session_abort(destroy_conn->session);
06a68401 3117
7591bab1
MD
3118 /*
3119 * No need to grab another ref, because we own
3120 * destroy_conn.
3121 */
3122 relay_thread_close_connection(&events, destroy_conn->sock->fd,
3123 destroy_conn);
b8aa1682 3124 }
94d49140 3125 rcu_read_unlock();
7591bab1
MD
3126
3127 lttng_poll_clean(&events);
7d2f7452 3128error_poll_create:
b8aa1682 3129 lttng_ht_destroy(relay_connections_ht);
095a4ae5 3130relay_connections_ht_error:
58eb9381
DG
3131 /* Close relay conn pipes */
3132 utils_close_pipe(relay_conn_pipe);
095a4ae5
MD
3133 if (err) {
3134 DBG("Thread exited with error");
3135 }
b8aa1682 3136 DBG("Worker thread cleanup complete");
9b5e0863 3137error_testpoint:
f385ae0a
MD
3138 if (err) {
3139 health_error();
3140 ERR("Health error occurred in %s", __func__);
3141 }
3142 health_unregister(health_relayd);
9d1bbf21 3143 rcu_unregister_thread();
b4aacfdc 3144 lttng_relay_stop_threads();
b8aa1682
JD
3145 return NULL;
3146}
3147
3148/*
3149 * Create the relay command pipe to wake thread_manage_apps.
3150 * Closed in cleanup().
3151 */
58eb9381 3152static int create_relay_conn_pipe(void)
b8aa1682 3153{
a02de639 3154 int ret;
b8aa1682 3155
58eb9381 3156 ret = utils_create_pipe_cloexec(relay_conn_pipe);
b8aa1682 3157
b8aa1682
JD
3158 return ret;
3159}
3160
3161/*
3162 * main
3163 */
3164int main(int argc, char **argv)
3165{
178a0557 3166 int ret = 0, retval = 0;
b8aa1682
JD
3167 void *status;
3168
c7cc870e
JR
3169 /* Parse environment variables */
3170 parse_env_options();
3171
3172 /*
3173 * Parse arguments.
3174 * Command line arguments overwrite environment.
3175 */
b8aa1682 3176 progname = argv[0];
178a0557
MD
3177 if (set_options(argc, argv)) {
3178 retval = -1;
3179 goto exit_options;
b8aa1682
JD
3180 }
3181
178a0557
MD
3182 if (set_signal_handler()) {
3183 retval = -1;
3184 goto exit_options;
b8aa1682
JD
3185 }
3186
4d513a50
DG
3187 /* Try to create directory if -o, --output is specified. */
3188 if (opt_output_path) {
994fa64f
DG
3189 if (*opt_output_path != '/') {
3190 ERR("Please specify an absolute path for -o, --output PATH");
178a0557
MD
3191 retval = -1;
3192 goto exit_options;
994fa64f
DG
3193 }
3194
d77dded2
JG
3195 ret = utils_mkdir_recursive(opt_output_path, S_IRWXU | S_IRWXG,
3196 -1, -1);
4d513a50
DG
3197 if (ret < 0) {
3198 ERR("Unable to create %s", opt_output_path);
178a0557
MD
3199 retval = -1;
3200 goto exit_options;
4d513a50
DG
3201 }
3202 }
3203
b8aa1682 3204 /* Daemonize */
b5218ffb 3205 if (opt_daemon || opt_background) {
3fd27398
MD
3206 int i;
3207
3208 ret = lttng_daemonize(&child_ppid, &recv_child_signal,
3209 !opt_background);
b8aa1682 3210 if (ret < 0) {
178a0557
MD
3211 retval = -1;
3212 goto exit_options;
b8aa1682 3213 }
3fd27398
MD
3214
3215 /*
3216 * We are in the child. Make sure all other file
3217 * descriptors are closed, in case we are called with
3218 * more opened file descriptors than the standard ones.
3219 */
3220 for (i = 3; i < sysconf(_SC_OPEN_MAX); i++) {
3221 (void) close(i);
3222 }
3223 }
3224
76375580
JR
3225
3226 if (opt_working_directory) {
3227 ret = utils_change_working_dir(opt_working_directory);
3228 if (ret) {
3229 ERR("Changing working directory");
3230 goto exit_options;
3231 }
3232 }
3233
178a0557
MD
3234 /* Initialize thread health monitoring */
3235 health_relayd = health_app_create(NR_HEALTH_RELAYD_TYPES);
3236 if (!health_relayd) {
3237 PERROR("health_app_create error");
3238 retval = -1;
3239 goto exit_health_app_create;
3240 }
3241
3fd27398 3242 /* Create thread quit pipe */
178a0557
MD
3243 if (init_thread_quit_pipe()) {
3244 retval = -1;
3245 goto exit_init_data;
b8aa1682
JD
3246 }
3247
b8aa1682 3248 /* Setup the thread apps communication pipe. */
178a0557
MD
3249 if (create_relay_conn_pipe()) {
3250 retval = -1;
3251 goto exit_init_data;
b8aa1682
JD
3252 }
3253
3254 /* Init relay command queue. */
8bdee6e2 3255 cds_wfcq_init(&relay_conn_queue.head, &relay_conn_queue.tail);
b8aa1682 3256
554831e7
MD
3257 /* Initialize communication library */
3258 lttcomm_init();
87e45c13 3259 lttcomm_inet_init();
554831e7 3260
d3e2ba59 3261 /* tables of sessions indexed by session ID */
7591bab1
MD
3262 sessions_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3263 if (!sessions_ht) {
178a0557
MD
3264 retval = -1;
3265 goto exit_init_data;
d3e2ba59
JD
3266 }
3267
3268 /* tables of streams indexed by stream ID */
2a174661 3269 relay_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
d3e2ba59 3270 if (!relay_streams_ht) {
178a0557
MD
3271 retval = -1;
3272 goto exit_init_data;
d3e2ba59
JD
3273 }
3274
3275 /* tables of streams indexed by stream ID */
92c6ca54
DG
3276 viewer_streams_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3277 if (!viewer_streams_ht) {
178a0557
MD
3278 retval = -1;
3279 goto exit_init_data;
55706a7d
MD
3280 }
3281
65931c8b 3282 ret = utils_create_pipe(health_quit_pipe);
178a0557
MD
3283 if (ret) {
3284 retval = -1;
3285 goto exit_health_quit_pipe;
65931c8b
MD
3286 }
3287
3288 /* Create thread to manage the client socket */
1a1a34b4 3289 ret = pthread_create(&health_thread, default_pthread_attr(),
65931c8b 3290 thread_manage_health, (void *) NULL);
178a0557
MD
3291 if (ret) {
3292 errno = ret;
65931c8b 3293 PERROR("pthread_create health");
178a0557
MD
3294 retval = -1;
3295 goto exit_health_thread;
65931c8b
MD
3296 }
3297
b8aa1682 3298 /* Setup the dispatcher thread */
1a1a34b4 3299 ret = pthread_create(&dispatcher_thread, default_pthread_attr(),
b8aa1682 3300 relay_thread_dispatcher, (void *) NULL);
178a0557
MD
3301 if (ret) {
3302 errno = ret;
b8aa1682 3303 PERROR("pthread_create dispatcher");
178a0557
MD
3304 retval = -1;
3305 goto exit_dispatcher_thread;
b8aa1682
JD
3306 }
3307
3308 /* Setup the worker thread */
1a1a34b4 3309 ret = pthread_create(&worker_thread, default_pthread_attr(),
7591bab1 3310 relay_thread_worker, NULL);
178a0557
MD
3311 if (ret) {
3312 errno = ret;
b8aa1682 3313 PERROR("pthread_create worker");
178a0557
MD
3314 retval = -1;
3315 goto exit_worker_thread;
b8aa1682
JD
3316 }
3317
3318 /* Setup the listener thread */
1a1a34b4 3319 ret = pthread_create(&listener_thread, default_pthread_attr(),
b8aa1682 3320 relay_thread_listener, (void *) NULL);
178a0557
MD
3321 if (ret) {
3322 errno = ret;
b8aa1682 3323 PERROR("pthread_create listener");
178a0557
MD
3324 retval = -1;
3325 goto exit_listener_thread;
b8aa1682
JD
3326 }
3327
7591bab1 3328 ret = relayd_live_create(live_uri);
178a0557 3329 if (ret) {
d3e2ba59 3330 ERR("Starting live viewer threads");
178a0557 3331 retval = -1;
50138f51 3332 goto exit_live;
d3e2ba59
JD
3333 }
3334
178a0557
MD
3335 /*
3336 * This is where we start awaiting program completion (e.g. through
3337 * signal that asks threads to teardown).
3338 */
3339
3340 ret = relayd_live_join();
3341 if (ret) {
3342 retval = -1;
3343 }
50138f51 3344exit_live:
178a0557 3345
b8aa1682 3346 ret = pthread_join(listener_thread, &status);
178a0557
MD
3347 if (ret) {
3348 errno = ret;
3349 PERROR("pthread_join listener_thread");
3350 retval = -1;
b8aa1682
JD
3351 }
3352
178a0557 3353exit_listener_thread:
b8aa1682 3354 ret = pthread_join(worker_thread, &status);
178a0557
MD
3355 if (ret) {
3356 errno = ret;
3357 PERROR("pthread_join worker_thread");
3358 retval = -1;
b8aa1682
JD
3359 }
3360
178a0557 3361exit_worker_thread:
b8aa1682 3362 ret = pthread_join(dispatcher_thread, &status);
178a0557
MD
3363 if (ret) {
3364 errno = ret;
3365 PERROR("pthread_join dispatcher_thread");
3366 retval = -1;
b8aa1682 3367 }
178a0557 3368exit_dispatcher_thread:
42415026 3369
65931c8b 3370 ret = pthread_join(health_thread, &status);
178a0557
MD
3371 if (ret) {
3372 errno = ret;
3373 PERROR("pthread_join health_thread");
3374 retval = -1;
65931c8b 3375 }
178a0557 3376exit_health_thread:
65931c8b 3377
65931c8b 3378 utils_close_pipe(health_quit_pipe);
178a0557 3379exit_health_quit_pipe:
65931c8b 3380
178a0557 3381exit_init_data:
55706a7d 3382 health_app_destroy(health_relayd);
55706a7d 3383exit_health_app_create:
178a0557 3384exit_options:
2668465a
MD
3385 /*
3386 * Wait for all pending call_rcu work to complete before tearing
3387 * down data structures. call_rcu worker may be trying to
3388 * perform lookups in those structures.
3389 */
3390 rcu_barrier();
7591bab1
MD
3391 relayd_cleanup();
3392
3393 /* Ensure all prior call_rcu are done. */
3394 rcu_barrier();
d3e2ba59 3395
178a0557 3396 if (!retval) {
b8aa1682 3397 exit(EXIT_SUCCESS);
178a0557
MD
3398 } else {
3399 exit(EXIT_FAILURE);
b8aa1682 3400 }
b8aa1682 3401}
This page took 0.27689 seconds and 5 git commands to generate.