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