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