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