Deliverables 3 and 4
[deliverable/lttng-tools.git] / src / bin / lttng-sessiond / main.c
... / ...
CommitLineData
1/*
2 * Copyright (C) 2011 - David Goulet <david.goulet@polymtl.ca>
3 * Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
4 * 2013 - Jérémie Galarneau <jeremie.galarneau@efficios.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License, version 2 only,
8 * as published by the Free Software Foundation.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20#define _LGPL_SOURCE
21#include <getopt.h>
22#include <grp.h>
23#include <limits.h>
24#include <paths.h>
25#include <pthread.h>
26#include <signal.h>
27#include <stdio.h>
28#include <stdlib.h>
29#include <string.h>
30#include <inttypes.h>
31#include <sys/mman.h>
32#include <sys/mount.h>
33#include <sys/resource.h>
34#include <sys/socket.h>
35#include <sys/stat.h>
36#include <sys/types.h>
37#include <sys/wait.h>
38#include <urcu/uatomic.h>
39#include <unistd.h>
40#include <ctype.h>
41
42#include <common/common.h>
43#include <common/compat/socket.h>
44#include <common/compat/getenv.h>
45#include <common/defaults.h>
46#include <common/kernel-consumer/kernel-consumer.h>
47#include <common/futex.h>
48#include <common/relayd/relayd.h>
49#include <common/utils.h>
50#include <common/daemonize.h>
51#include <common/config/session-config.h>
52
53#include "lttng-sessiond.h"
54#include "buffer-registry.h"
55#include "channel.h"
56#include "cmd.h"
57#include "consumer.h"
58#include "context.h"
59#include "event.h"
60#include "kernel.h"
61#include "kernel-consumer.h"
62#include "modprobe.h"
63#include "shm.h"
64#include "ust-ctl.h"
65#include "ust-consumer.h"
66#include "utils.h"
67#include "fd-limit.h"
68#include "health-sessiond.h"
69#include "testpoint.h"
70#include "ust-thread.h"
71#include "agent-thread.h"
72#include "save.h"
73#include "load-session-thread.h"
74#include "notification-thread.h"
75#include "syscall.h"
76#include "agent.h"
77#include "ht-cleanup.h"
78
79#define CONSUMERD_FILE "lttng-consumerd"
80
81const char *progname;
82static const char *tracing_group_name = DEFAULT_TRACING_GROUP;
83static int tracing_group_name_override;
84static char *opt_pidfile;
85static int opt_sig_parent;
86static int opt_verbose_consumer;
87static int opt_daemon, opt_background;
88static int opt_no_kernel;
89static char *opt_load_session_path;
90static pid_t ppid; /* Parent PID for --sig-parent option */
91static pid_t child_ppid; /* Internal parent PID use with daemonize. */
92static char *rundir;
93static int lockfile_fd = -1;
94
95/* Set to 1 when a SIGUSR1 signal is received. */
96static int recv_child_signal;
97
98/*
99 * Consumer daemon specific control data. Every value not initialized here is
100 * set to 0 by the static definition.
101 */
102static struct consumer_data kconsumer_data = {
103 .type = LTTNG_CONSUMER_KERNEL,
104 .err_unix_sock_path = DEFAULT_KCONSUMERD_ERR_SOCK_PATH,
105 .cmd_unix_sock_path = DEFAULT_KCONSUMERD_CMD_SOCK_PATH,
106 .err_sock = -1,
107 .cmd_sock = -1,
108 .channel_monitor_pipe = -1,
109 .pid_mutex = PTHREAD_MUTEX_INITIALIZER,
110 .lock = PTHREAD_MUTEX_INITIALIZER,
111 .cond = PTHREAD_COND_INITIALIZER,
112 .cond_mutex = PTHREAD_MUTEX_INITIALIZER,
113};
114static struct consumer_data ustconsumer64_data = {
115 .type = LTTNG_CONSUMER64_UST,
116 .err_unix_sock_path = DEFAULT_USTCONSUMERD64_ERR_SOCK_PATH,
117 .cmd_unix_sock_path = DEFAULT_USTCONSUMERD64_CMD_SOCK_PATH,
118 .err_sock = -1,
119 .cmd_sock = -1,
120 .channel_monitor_pipe = -1,
121 .pid_mutex = PTHREAD_MUTEX_INITIALIZER,
122 .lock = PTHREAD_MUTEX_INITIALIZER,
123 .cond = PTHREAD_COND_INITIALIZER,
124 .cond_mutex = PTHREAD_MUTEX_INITIALIZER,
125};
126static struct consumer_data ustconsumer32_data = {
127 .type = LTTNG_CONSUMER32_UST,
128 .err_unix_sock_path = DEFAULT_USTCONSUMERD32_ERR_SOCK_PATH,
129 .cmd_unix_sock_path = DEFAULT_USTCONSUMERD32_CMD_SOCK_PATH,
130 .err_sock = -1,
131 .cmd_sock = -1,
132 .channel_monitor_pipe = -1,
133 .pid_mutex = PTHREAD_MUTEX_INITIALIZER,
134 .lock = PTHREAD_MUTEX_INITIALIZER,
135 .cond = PTHREAD_COND_INITIALIZER,
136 .cond_mutex = PTHREAD_MUTEX_INITIALIZER,
137};
138
139/* Command line options */
140static const struct option long_options[] = {
141 { "client-sock", required_argument, 0, 'c' },
142 { "apps-sock", required_argument, 0, 'a' },
143 { "kconsumerd-cmd-sock", required_argument, 0, '\0' },
144 { "kconsumerd-err-sock", required_argument, 0, '\0' },
145 { "ustconsumerd32-cmd-sock", required_argument, 0, '\0' },
146 { "ustconsumerd32-err-sock", required_argument, 0, '\0' },
147 { "ustconsumerd64-cmd-sock", required_argument, 0, '\0' },
148 { "ustconsumerd64-err-sock", required_argument, 0, '\0' },
149 { "consumerd32-path", required_argument, 0, '\0' },
150 { "consumerd32-libdir", required_argument, 0, '\0' },
151 { "consumerd64-path", required_argument, 0, '\0' },
152 { "consumerd64-libdir", required_argument, 0, '\0' },
153 { "daemonize", no_argument, 0, 'd' },
154 { "background", no_argument, 0, 'b' },
155 { "sig-parent", no_argument, 0, 'S' },
156 { "help", no_argument, 0, 'h' },
157 { "group", required_argument, 0, 'g' },
158 { "version", no_argument, 0, 'V' },
159 { "quiet", no_argument, 0, 'q' },
160 { "verbose", no_argument, 0, 'v' },
161 { "verbose-consumer", no_argument, 0, '\0' },
162 { "no-kernel", no_argument, 0, '\0' },
163 { "pidfile", required_argument, 0, 'p' },
164 { "agent-tcp-port", required_argument, 0, '\0' },
165 { "config", required_argument, 0, 'f' },
166 { "load", required_argument, 0, 'l' },
167 { "kmod-probes", required_argument, 0, '\0' },
168 { "extra-kmod-probes", required_argument, 0, '\0' },
169 { NULL, 0, 0, 0 }
170};
171
172/* Command line options to ignore from configuration file */
173static const char *config_ignore_options[] = { "help", "version", "config" };
174
175/* Shared between threads */
176static int dispatch_thread_exit;
177
178/* Global application Unix socket path */
179static char apps_unix_sock_path[PATH_MAX];
180/* Global client Unix socket path */
181static char client_unix_sock_path[PATH_MAX];
182/* global wait shm path for UST */
183static char wait_shm_path[PATH_MAX];
184/* Global health check unix path */
185static char health_unix_sock_path[PATH_MAX];
186
187/* Sockets and FDs */
188static int client_sock = -1;
189static int apps_sock = -1;
190int kernel_tracer_fd = -1;
191static int kernel_poll_pipe[2] = { -1, -1 };
192
193/*
194 * Quit pipe for all threads. This permits a single cancellation point
195 * for all threads when receiving an event on the pipe.
196 */
197static int thread_quit_pipe[2] = { -1, -1 };
198
199/*
200 * This pipe is used to inform the thread managing application communication
201 * that a command is queued and ready to be processed.
202 */
203static int apps_cmd_pipe[2] = { -1, -1 };
204
205int apps_cmd_notify_pipe[2] = { -1, -1 };
206
207/* Pthread, Mutexes and Semaphores */
208static pthread_t apps_thread;
209static pthread_t apps_notify_thread;
210static pthread_t reg_apps_thread;
211static pthread_t client_thread;
212static pthread_t kernel_thread;
213static pthread_t dispatch_thread;
214static pthread_t health_thread;
215static pthread_t ht_cleanup_thread;
216static pthread_t agent_reg_thread;
217static pthread_t load_session_thread;
218static pthread_t notification_thread;
219
220/*
221 * UST registration command queue. This queue is tied with a futex and uses a N
222 * wakers / 1 waiter implemented and detailed in futex.c/.h
223 *
224 * The thread_registration_apps and thread_dispatch_ust_registration uses this
225 * queue along with the wait/wake scheme. The thread_manage_apps receives down
226 * the line new application socket and monitors it for any I/O error or clean
227 * close that triggers an unregistration of the application.
228 */
229static struct ust_cmd_queue ust_cmd_queue;
230
231/*
232 * Pointer initialized before thread creation.
233 *
234 * This points to the tracing session list containing the session count and a
235 * mutex lock. The lock MUST be taken if you iterate over the list. The lock
236 * MUST NOT be taken if you call a public function in session.c.
237 *
238 * The lock is nested inside the structure: session_list_ptr->lock. Please use
239 * session_lock_list and session_unlock_list for lock acquisition.
240 */
241static struct ltt_session_list *session_list_ptr;
242
243int ust_consumerd64_fd = -1;
244int ust_consumerd32_fd = -1;
245
246static const char *consumerd32_bin = CONFIG_CONSUMERD32_BIN;
247static const char *consumerd64_bin = CONFIG_CONSUMERD64_BIN;
248static const char *consumerd32_libdir = CONFIG_CONSUMERD32_LIBDIR;
249static const char *consumerd64_libdir = CONFIG_CONSUMERD64_LIBDIR;
250static int consumerd32_bin_override;
251static int consumerd64_bin_override;
252static int consumerd32_libdir_override;
253static int consumerd64_libdir_override;
254
255static const char *module_proc_lttng = "/proc/lttng";
256
257/*
258 * Consumer daemon state which is changed when spawning it, killing it or in
259 * case of a fatal error.
260 */
261enum consumerd_state {
262 CONSUMER_STARTED = 1,
263 CONSUMER_STOPPED = 2,
264 CONSUMER_ERROR = 3,
265};
266
267/*
268 * This consumer daemon state is used to validate if a client command will be
269 * able to reach the consumer. If not, the client is informed. For instance,
270 * doing a "lttng start" when the consumer state is set to ERROR will return an
271 * error to the client.
272 *
273 * The following example shows a possible race condition of this scheme:
274 *
275 * consumer thread error happens
276 * client cmd arrives
277 * client cmd checks state -> still OK
278 * consumer thread exit, sets error
279 * client cmd try to talk to consumer
280 * ...
281 *
282 * However, since the consumer is a different daemon, we have no way of making
283 * sure the command will reach it safely even with this state flag. This is why
284 * we consider that up to the state validation during command processing, the
285 * command is safe. After that, we can not guarantee the correctness of the
286 * client request vis-a-vis the consumer.
287 */
288static enum consumerd_state ust_consumerd_state;
289static enum consumerd_state kernel_consumerd_state;
290
291/*
292 * Socket timeout for receiving and sending in seconds.
293 */
294static int app_socket_timeout;
295
296/* Set in main() with the current page size. */
297long page_size;
298
299/* Application health monitoring */
300struct health_app *health_sessiond;
301
302/* Agent TCP port for registration. Used by the agent thread. */
303unsigned int agent_tcp_port = DEFAULT_AGENT_TCP_PORT;
304
305/* Am I root or not. */
306int is_root; /* Set to 1 if the daemon is running as root */
307
308const char * const config_section_name = "sessiond";
309
310/* Load session thread information to operate. */
311struct load_session_thread_data *load_info;
312
313/* Notification thread handle. */
314struct notification_thread_handle *notification_thread_handle;
315
316/* Global hash tables */
317struct lttng_ht *agent_apps_ht_by_sock = NULL;
318
319/*
320 * Whether sessiond is ready for commands/notification channel/health check
321 * requests.
322 * NR_LTTNG_SESSIOND_READY must match the number of calls to
323 * sessiond_notify_ready().
324 */
325#define NR_LTTNG_SESSIOND_READY 4
326int lttng_sessiond_ready = NR_LTTNG_SESSIOND_READY;
327
328int sessiond_check_thread_quit_pipe(int fd, uint32_t events)
329{
330 return (fd == thread_quit_pipe[0] && (events & LPOLLIN)) ? 1 : 0;
331}
332
333/* Notify parents that we are ready for cmd and health check */
334LTTNG_HIDDEN
335void sessiond_notify_ready(void)
336{
337 if (uatomic_sub_return(&lttng_sessiond_ready, 1) == 0) {
338 /*
339 * Notify parent pid that we are ready to accept command
340 * for client side. This ppid is the one from the
341 * external process that spawned us.
342 */
343 if (opt_sig_parent) {
344 kill(ppid, SIGUSR1);
345 }
346
347 /*
348 * Notify the parent of the fork() process that we are
349 * ready.
350 */
351 if (opt_daemon || opt_background) {
352 kill(child_ppid, SIGUSR1);
353 }
354 }
355}
356
357static
358void setup_consumerd_path(void)
359{
360 const char *bin, *libdir;
361
362 /*
363 * Allow INSTALL_BIN_PATH to be used as a target path for the
364 * native architecture size consumer if CONFIG_CONSUMER*_PATH
365 * has not been defined.
366 */
367#if (CAA_BITS_PER_LONG == 32)
368 if (!consumerd32_bin[0]) {
369 consumerd32_bin = INSTALL_BIN_PATH "/" CONSUMERD_FILE;
370 }
371 if (!consumerd32_libdir[0]) {
372 consumerd32_libdir = INSTALL_LIB_PATH;
373 }
374#elif (CAA_BITS_PER_LONG == 64)
375 if (!consumerd64_bin[0]) {
376 consumerd64_bin = INSTALL_BIN_PATH "/" CONSUMERD_FILE;
377 }
378 if (!consumerd64_libdir[0]) {
379 consumerd64_libdir = INSTALL_LIB_PATH;
380 }
381#else
382#error "Unknown bitness"
383#endif
384
385 /*
386 * runtime env. var. overrides the build default.
387 */
388 bin = lttng_secure_getenv("LTTNG_CONSUMERD32_BIN");
389 if (bin) {
390 consumerd32_bin = bin;
391 }
392 bin = lttng_secure_getenv("LTTNG_CONSUMERD64_BIN");
393 if (bin) {
394 consumerd64_bin = bin;
395 }
396 libdir = lttng_secure_getenv("LTTNG_CONSUMERD32_LIBDIR");
397 if (libdir) {
398 consumerd32_libdir = libdir;
399 }
400 libdir = lttng_secure_getenv("LTTNG_CONSUMERD64_LIBDIR");
401 if (libdir) {
402 consumerd64_libdir = libdir;
403 }
404}
405
406static
407int __sessiond_set_thread_pollset(struct lttng_poll_event *events, size_t size,
408 int *a_pipe)
409{
410 int ret;
411
412 assert(events);
413
414 ret = lttng_poll_create(events, size, LTTNG_CLOEXEC);
415 if (ret < 0) {
416 goto error;
417 }
418
419 /* Add quit pipe */
420 ret = lttng_poll_add(events, a_pipe[0], LPOLLIN | LPOLLERR);
421 if (ret < 0) {
422 goto error;
423 }
424
425 return 0;
426
427error:
428 return ret;
429}
430
431/*
432 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
433 */
434int sessiond_set_thread_pollset(struct lttng_poll_event *events, size_t size)
435{
436 return __sessiond_set_thread_pollset(events, size, thread_quit_pipe);
437}
438
439/*
440 * Init thread quit pipe.
441 *
442 * Return -1 on error or 0 if all pipes are created.
443 */
444static int __init_thread_quit_pipe(int *a_pipe)
445{
446 int ret, i;
447
448 ret = pipe(a_pipe);
449 if (ret < 0) {
450 PERROR("thread quit pipe");
451 goto error;
452 }
453
454 for (i = 0; i < 2; i++) {
455 ret = fcntl(a_pipe[i], F_SETFD, FD_CLOEXEC);
456 if (ret < 0) {
457 PERROR("fcntl");
458 goto error;
459 }
460 }
461
462error:
463 return ret;
464}
465
466static int init_thread_quit_pipe(void)
467{
468 return __init_thread_quit_pipe(thread_quit_pipe);
469}
470
471/*
472 * Stop all threads by closing the thread quit pipe.
473 */
474static void stop_threads(void)
475{
476 int ret;
477
478 /* Stopping all threads */
479 DBG("Terminating all threads");
480 ret = notify_thread_pipe(thread_quit_pipe[1]);
481 if (ret < 0) {
482 ERR("write error on thread quit pipe");
483 }
484
485 /* Dispatch thread */
486 CMM_STORE_SHARED(dispatch_thread_exit, 1);
487 futex_nto1_wake(&ust_cmd_queue.futex);
488}
489
490/*
491 * Close every consumer sockets.
492 */
493static void close_consumer_sockets(void)
494{
495 int ret;
496
497 if (kconsumer_data.err_sock >= 0) {
498 ret = close(kconsumer_data.err_sock);
499 if (ret < 0) {
500 PERROR("kernel consumer err_sock close");
501 }
502 }
503 if (ustconsumer32_data.err_sock >= 0) {
504 ret = close(ustconsumer32_data.err_sock);
505 if (ret < 0) {
506 PERROR("UST consumerd32 err_sock close");
507 }
508 }
509 if (ustconsumer64_data.err_sock >= 0) {
510 ret = close(ustconsumer64_data.err_sock);
511 if (ret < 0) {
512 PERROR("UST consumerd64 err_sock close");
513 }
514 }
515 if (kconsumer_data.cmd_sock >= 0) {
516 ret = close(kconsumer_data.cmd_sock);
517 if (ret < 0) {
518 PERROR("kernel consumer cmd_sock close");
519 }
520 }
521 if (ustconsumer32_data.cmd_sock >= 0) {
522 ret = close(ustconsumer32_data.cmd_sock);
523 if (ret < 0) {
524 PERROR("UST consumerd32 cmd_sock close");
525 }
526 }
527 if (ustconsumer64_data.cmd_sock >= 0) {
528 ret = close(ustconsumer64_data.cmd_sock);
529 if (ret < 0) {
530 PERROR("UST consumerd64 cmd_sock close");
531 }
532 }
533 if (kconsumer_data.channel_monitor_pipe >= 0) {
534 ret = close(kconsumer_data.channel_monitor_pipe);
535 if (ret < 0) {
536 PERROR("kernel consumer channel monitor pipe close");
537 }
538 }
539 if (ustconsumer32_data.channel_monitor_pipe >= 0) {
540 ret = close(ustconsumer32_data.channel_monitor_pipe);
541 if (ret < 0) {
542 PERROR("UST consumerd32 channel monitor pipe close");
543 }
544 }
545 if (ustconsumer64_data.channel_monitor_pipe >= 0) {
546 ret = close(ustconsumer64_data.channel_monitor_pipe);
547 if (ret < 0) {
548 PERROR("UST consumerd64 channel monitor pipe close");
549 }
550 }
551}
552
553/*
554 * Generate the full lock file path using the rundir.
555 *
556 * Return the snprintf() return value thus a negative value is an error.
557 */
558static int generate_lock_file_path(char *path, size_t len)
559{
560 int ret;
561
562 assert(path);
563 assert(rundir);
564
565 /* Build lockfile path from rundir. */
566 ret = snprintf(path, len, "%s/" DEFAULT_LTTNG_SESSIOND_LOCKFILE, rundir);
567 if (ret < 0) {
568 PERROR("snprintf lockfile path");
569 }
570
571 return ret;
572}
573
574/*
575 * Wait on consumer process termination.
576 *
577 * Need to be called with the consumer data lock held or from a context
578 * ensuring no concurrent access to data (e.g: cleanup).
579 */
580static void wait_consumer(struct consumer_data *consumer_data)
581{
582 pid_t ret;
583 int status;
584
585 if (consumer_data->pid <= 0) {
586 return;
587 }
588
589 DBG("Waiting for complete teardown of consumerd (PID: %d)",
590 consumer_data->pid);
591 ret = waitpid(consumer_data->pid, &status, 0);
592 if (ret == -1) {
593 PERROR("consumerd waitpid pid: %d", consumer_data->pid)
594 }
595 if (!WIFEXITED(status)) {
596 ERR("consumerd termination with error: %d",
597 WEXITSTATUS(ret));
598 }
599 consumer_data->pid = 0;
600}
601
602/*
603 * Cleanup the session daemon's data structures.
604 */
605static void sessiond_cleanup(void)
606{
607 int ret;
608 struct ltt_session *sess, *stmp;
609 char path[PATH_MAX];
610
611 DBG("Cleanup sessiond");
612
613 /*
614 * Close the thread quit pipe. It has already done its job,
615 * since we are now called.
616 */
617 utils_close_pipe(thread_quit_pipe);
618
619 /*
620 * If opt_pidfile is undefined, the default file will be wiped when
621 * removing the rundir.
622 */
623 if (opt_pidfile) {
624 ret = remove(opt_pidfile);
625 if (ret < 0) {
626 PERROR("remove pidfile %s", opt_pidfile);
627 }
628 }
629
630 DBG("Removing sessiond and consumerd content of directory %s", rundir);
631
632 /* sessiond */
633 snprintf(path, PATH_MAX,
634 "%s/%s",
635 rundir, DEFAULT_LTTNG_SESSIOND_PIDFILE);
636 DBG("Removing %s", path);
637 (void) unlink(path);
638
639 snprintf(path, PATH_MAX, "%s/%s", rundir,
640 DEFAULT_LTTNG_SESSIOND_AGENTPORT_FILE);
641 DBG("Removing %s", path);
642 (void) unlink(path);
643
644 /* kconsumerd */
645 snprintf(path, PATH_MAX,
646 DEFAULT_KCONSUMERD_ERR_SOCK_PATH,
647 rundir);
648 DBG("Removing %s", path);
649 (void) unlink(path);
650
651 snprintf(path, PATH_MAX,
652 DEFAULT_KCONSUMERD_PATH,
653 rundir);
654 DBG("Removing directory %s", path);
655 (void) rmdir(path);
656
657 /* ust consumerd 32 */
658 snprintf(path, PATH_MAX,
659 DEFAULT_USTCONSUMERD32_ERR_SOCK_PATH,
660 rundir);
661 DBG("Removing %s", path);
662 (void) unlink(path);
663
664 snprintf(path, PATH_MAX,
665 DEFAULT_USTCONSUMERD32_PATH,
666 rundir);
667 DBG("Removing directory %s", path);
668 (void) rmdir(path);
669
670 /* ust consumerd 64 */
671 snprintf(path, PATH_MAX,
672 DEFAULT_USTCONSUMERD64_ERR_SOCK_PATH,
673 rundir);
674 DBG("Removing %s", path);
675 (void) unlink(path);
676
677 snprintf(path, PATH_MAX,
678 DEFAULT_USTCONSUMERD64_PATH,
679 rundir);
680 DBG("Removing directory %s", path);
681 (void) rmdir(path);
682
683 DBG("Cleaning up all sessions");
684
685 /* Destroy session list mutex */
686 if (session_list_ptr != NULL) {
687 pthread_mutex_destroy(&session_list_ptr->lock);
688
689 /* Cleanup ALL session */
690 cds_list_for_each_entry_safe(sess, stmp,
691 &session_list_ptr->head, list) {
692 cmd_destroy_session(sess, kernel_poll_pipe[1]);
693 }
694 }
695
696 wait_consumer(&kconsumer_data);
697 wait_consumer(&ustconsumer64_data);
698 wait_consumer(&ustconsumer32_data);
699
700 DBG("Cleaning up all agent apps");
701 agent_app_ht_clean();
702
703 DBG("Closing all UST sockets");
704 ust_app_clean_list();
705 buffer_reg_destroy_registries();
706
707 if (is_root && !opt_no_kernel) {
708 DBG2("Closing kernel fd");
709 if (kernel_tracer_fd >= 0) {
710 ret = close(kernel_tracer_fd);
711 if (ret) {
712 PERROR("close");
713 }
714 }
715 DBG("Unloading kernel modules");
716 modprobe_remove_lttng_all();
717 free(syscall_table);
718 }
719
720 close_consumer_sockets();
721
722 if (load_info) {
723 load_session_destroy_data(load_info);
724 free(load_info);
725 }
726
727 if (notification_thread_handle) {
728 notification_thread_handle_destroy(notification_thread_handle);
729 }
730
731 /*
732 * Cleanup lock file by deleting it and finaly closing it which will
733 * release the file system lock.
734 */
735 if (lockfile_fd >= 0) {
736 char lockfile_path[PATH_MAX];
737
738 ret = generate_lock_file_path(lockfile_path,
739 sizeof(lockfile_path));
740 if (ret > 0) {
741 ret = remove(lockfile_path);
742 if (ret < 0) {
743 PERROR("remove lock file");
744 }
745 ret = close(lockfile_fd);
746 if (ret < 0) {
747 PERROR("close lock file");
748 }
749 }
750 }
751
752 /*
753 * We do NOT rmdir rundir because there are other processes
754 * using it, for instance lttng-relayd, which can start in
755 * parallel with this teardown.
756 */
757
758 free(rundir);
759}
760
761/*
762 * Cleanup the daemon's option data structures.
763 */
764static void sessiond_cleanup_options(void)
765{
766 DBG("Cleaning up options");
767
768 /*
769 * If the override option is set, the pointer points to a *non* const
770 * thus freeing it even though the variable type is set to const.
771 */
772 if (tracing_group_name_override) {
773 free((void *) tracing_group_name);
774 }
775 if (consumerd32_bin_override) {
776 free((void *) consumerd32_bin);
777 }
778 if (consumerd64_bin_override) {
779 free((void *) consumerd64_bin);
780 }
781 if (consumerd32_libdir_override) {
782 free((void *) consumerd32_libdir);
783 }
784 if (consumerd64_libdir_override) {
785 free((void *) consumerd64_libdir);
786 }
787
788 free(opt_pidfile);
789 free(opt_load_session_path);
790 free(kmod_probes_list);
791 free(kmod_extra_probes_list);
792
793 run_as_destroy_worker();
794}
795
796/*
797 * Send data on a unix socket using the liblttsessiondcomm API.
798 *
799 * Return lttcomm error code.
800 */
801static int send_unix_sock(int sock, void *buf, size_t len)
802{
803 /* Check valid length */
804 if (len == 0) {
805 return -1;
806 }
807
808 return lttcomm_send_unix_sock(sock, buf, len);
809}
810
811/*
812 * Free memory of a command context structure.
813 */
814static void clean_command_ctx(struct command_ctx **cmd_ctx)
815{
816 DBG("Clean command context structure");
817 if (*cmd_ctx) {
818 if ((*cmd_ctx)->llm) {
819 free((*cmd_ctx)->llm);
820 }
821 if ((*cmd_ctx)->lsm) {
822 free((*cmd_ctx)->lsm);
823 }
824 free(*cmd_ctx);
825 *cmd_ctx = NULL;
826 }
827}
828
829/*
830 * Notify UST applications using the shm mmap futex.
831 */
832static int notify_ust_apps(int active)
833{
834 char *wait_shm_mmap;
835
836 DBG("Notifying applications of session daemon state: %d", active);
837
838 /* See shm.c for this call implying mmap, shm and futex calls */
839 wait_shm_mmap = shm_ust_get_mmap(wait_shm_path, is_root);
840 if (wait_shm_mmap == NULL) {
841 goto error;
842 }
843
844 /* Wake waiting process */
845 futex_wait_update((int32_t *) wait_shm_mmap, active);
846
847 /* Apps notified successfully */
848 return 0;
849
850error:
851 return -1;
852}
853
854/*
855 * Setup the outgoing data buffer for the response (llm) by allocating the
856 * right amount of memory and copying the original information from the lsm
857 * structure.
858 *
859 * Return 0 on success, negative value on error.
860 */
861static int setup_lttng_msg(struct command_ctx *cmd_ctx,
862 const void *payload_buf, size_t payload_len,
863 const void *cmd_header_buf, size_t cmd_header_len)
864{
865 int ret = 0;
866 const size_t header_len = sizeof(struct lttcomm_lttng_msg);
867 const size_t cmd_header_offset = header_len;
868 const size_t payload_offset = cmd_header_offset + cmd_header_len;
869 const size_t total_msg_size = header_len + cmd_header_len + payload_len;
870
871 cmd_ctx->llm = zmalloc(total_msg_size);
872
873 if (cmd_ctx->llm == NULL) {
874 PERROR("zmalloc");
875 ret = -ENOMEM;
876 goto end;
877 }
878
879 /* Copy common data */
880 cmd_ctx->llm->cmd_type = cmd_ctx->lsm->cmd_type;
881 cmd_ctx->llm->pid = cmd_ctx->lsm->domain.attr.pid;
882 cmd_ctx->llm->cmd_header_size = cmd_header_len;
883 cmd_ctx->llm->data_size = payload_len;
884 cmd_ctx->lttng_msg_size = total_msg_size;
885
886 /* Copy command header */
887 if (cmd_header_len) {
888 memcpy(((uint8_t *) cmd_ctx->llm) + cmd_header_offset, cmd_header_buf,
889 cmd_header_len);
890 }
891
892 /* Copy payload */
893 if (payload_len) {
894 memcpy(((uint8_t *) cmd_ctx->llm) + payload_offset, payload_buf,
895 payload_len);
896 }
897
898end:
899 return ret;
900}
901
902/*
903 * Version of setup_lttng_msg() without command header.
904 */
905static int setup_lttng_msg_no_cmd_header(struct command_ctx *cmd_ctx,
906 void *payload_buf, size_t payload_len)
907{
908 return setup_lttng_msg(cmd_ctx, payload_buf, payload_len, NULL, 0);
909}
910/*
911 * Update the kernel poll set of all channel fd available over all tracing
912 * session. Add the wakeup pipe at the end of the set.
913 */
914static int update_kernel_poll(struct lttng_poll_event *events)
915{
916 int ret;
917 struct ltt_session *session;
918 struct ltt_kernel_channel *channel;
919
920 DBG("Updating kernel poll set");
921
922 session_lock_list();
923 cds_list_for_each_entry(session, &session_list_ptr->head, list) {
924 session_lock(session);
925 if (session->kernel_session == NULL) {
926 session_unlock(session);
927 continue;
928 }
929
930 cds_list_for_each_entry(channel,
931 &session->kernel_session->channel_list.head, list) {
932 /* Add channel fd to the kernel poll set */
933 ret = lttng_poll_add(events, channel->fd, LPOLLIN | LPOLLRDNORM);
934 if (ret < 0) {
935 session_unlock(session);
936 goto error;
937 }
938 DBG("Channel fd %d added to kernel set", channel->fd);
939 }
940 session_unlock(session);
941 }
942 session_unlock_list();
943
944 return 0;
945
946error:
947 session_unlock_list();
948 return -1;
949}
950
951/*
952 * Find the channel fd from 'fd' over all tracing session. When found, check
953 * for new channel stream and send those stream fds to the kernel consumer.
954 *
955 * Useful for CPU hotplug feature.
956 */
957static int update_kernel_stream(struct consumer_data *consumer_data, int fd)
958{
959 int ret = 0;
960 struct ltt_session *session;
961 struct ltt_kernel_session *ksess;
962 struct ltt_kernel_channel *channel;
963
964 DBG("Updating kernel streams for channel fd %d", fd);
965
966 session_lock_list();
967 cds_list_for_each_entry(session, &session_list_ptr->head, list) {
968 session_lock(session);
969 if (session->kernel_session == NULL) {
970 session_unlock(session);
971 continue;
972 }
973 ksess = session->kernel_session;
974
975 cds_list_for_each_entry(channel,
976 &ksess->channel_list.head, list) {
977 struct lttng_ht_iter iter;
978 struct consumer_socket *socket;
979
980 if (channel->fd != fd) {
981 continue;
982 }
983 DBG("Channel found, updating kernel streams");
984 ret = kernel_open_channel_stream(channel);
985 if (ret < 0) {
986 goto error;
987 }
988 /* Update the stream global counter */
989 ksess->stream_count_global += ret;
990
991 /*
992 * Have we already sent fds to the consumer? If yes, it
993 * means that tracing is started so it is safe to send
994 * our updated stream fds.
995 */
996 if (ksess->consumer_fds_sent != 1
997 || ksess->consumer == NULL) {
998 ret = -1;
999 goto error;
1000 }
1001
1002 rcu_read_lock();
1003 cds_lfht_for_each_entry(ksess->consumer->socks->ht,
1004 &iter.iter, socket, node.node) {
1005 pthread_mutex_lock(socket->lock);
1006 ret = kernel_consumer_send_channel_stream(socket,
1007 channel, ksess,
1008 session->output_traces ? 1 : 0);
1009 pthread_mutex_unlock(socket->lock);
1010 if (ret < 0) {
1011 rcu_read_unlock();
1012 goto error;
1013 }
1014 }
1015 rcu_read_unlock();
1016 }
1017 session_unlock(session);
1018 }
1019 session_unlock_list();
1020 return ret;
1021
1022error:
1023 session_unlock(session);
1024 session_unlock_list();
1025 return ret;
1026}
1027
1028/*
1029 * For each tracing session, update newly registered apps. The session list
1030 * lock MUST be acquired before calling this.
1031 */
1032static void update_ust_app(int app_sock)
1033{
1034 struct ltt_session *sess, *stmp;
1035
1036 /* Consumer is in an ERROR state. Stop any application update. */
1037 if (uatomic_read(&ust_consumerd_state) == CONSUMER_ERROR) {
1038 /* Stop the update process since the consumer is dead. */
1039 return;
1040 }
1041
1042 /* For all tracing session(s) */
1043 cds_list_for_each_entry_safe(sess, stmp, &session_list_ptr->head, list) {
1044 struct ust_app *app;
1045
1046 session_lock(sess);
1047 if (!sess->ust_session) {
1048 goto unlock_session;
1049 }
1050
1051 rcu_read_lock();
1052 assert(app_sock >= 0);
1053 app = ust_app_find_by_sock(app_sock);
1054 if (app == NULL) {
1055 /*
1056 * Application can be unregistered before so
1057 * this is possible hence simply stopping the
1058 * update.
1059 */
1060 DBG3("UST app update failed to find app sock %d",
1061 app_sock);
1062 goto unlock_rcu;
1063 }
1064 ust_app_global_update(sess->ust_session, app);
1065 unlock_rcu:
1066 rcu_read_unlock();
1067 unlock_session:
1068 session_unlock(sess);
1069 }
1070}
1071
1072/*
1073 * This thread manage event coming from the kernel.
1074 *
1075 * Features supported in this thread:
1076 * -) CPU Hotplug
1077 */
1078static void *thread_manage_kernel(void *data)
1079{
1080 int ret, i, pollfd, update_poll_flag = 1, err = -1;
1081 uint32_t revents, nb_fd;
1082 char tmp;
1083 struct lttng_poll_event events;
1084
1085 DBG("[thread] Thread manage kernel started");
1086
1087 health_register(health_sessiond, HEALTH_SESSIOND_TYPE_KERNEL);
1088
1089 /*
1090 * This first step of the while is to clean this structure which could free
1091 * non NULL pointers so initialize it before the loop.
1092 */
1093 lttng_poll_init(&events);
1094
1095 if (testpoint(sessiond_thread_manage_kernel)) {
1096 goto error_testpoint;
1097 }
1098
1099 health_code_update();
1100
1101 if (testpoint(sessiond_thread_manage_kernel_before_loop)) {
1102 goto error_testpoint;
1103 }
1104
1105 while (1) {
1106 health_code_update();
1107
1108 if (update_poll_flag == 1) {
1109 /* Clean events object. We are about to populate it again. */
1110 lttng_poll_clean(&events);
1111
1112 ret = sessiond_set_thread_pollset(&events, 2);
1113 if (ret < 0) {
1114 goto error_poll_create;
1115 }
1116
1117 ret = lttng_poll_add(&events, kernel_poll_pipe[0], LPOLLIN);
1118 if (ret < 0) {
1119 goto error;
1120 }
1121
1122 /* This will add the available kernel channel if any. */
1123 ret = update_kernel_poll(&events);
1124 if (ret < 0) {
1125 goto error;
1126 }
1127 update_poll_flag = 0;
1128 }
1129
1130 DBG("Thread kernel polling");
1131
1132 /* Poll infinite value of time */
1133 restart:
1134 health_poll_entry();
1135 ret = lttng_poll_wait(&events, -1);
1136 DBG("Thread kernel return from poll on %d fds",
1137 LTTNG_POLL_GETNB(&events));
1138 health_poll_exit();
1139 if (ret < 0) {
1140 /*
1141 * Restart interrupted system call.
1142 */
1143 if (errno == EINTR) {
1144 goto restart;
1145 }
1146 goto error;
1147 } else if (ret == 0) {
1148 /* Should not happen since timeout is infinite */
1149 ERR("Return value of poll is 0 with an infinite timeout.\n"
1150 "This should not have happened! Continuing...");
1151 continue;
1152 }
1153
1154 nb_fd = ret;
1155
1156 for (i = 0; i < nb_fd; i++) {
1157 /* Fetch once the poll data */
1158 revents = LTTNG_POLL_GETEV(&events, i);
1159 pollfd = LTTNG_POLL_GETFD(&events, i);
1160
1161 health_code_update();
1162
1163 if (!revents) {
1164 /* No activity for this FD (poll implementation). */
1165 continue;
1166 }
1167
1168 /* Thread quit pipe has been closed. Killing thread. */
1169 ret = sessiond_check_thread_quit_pipe(pollfd, revents);
1170 if (ret) {
1171 err = 0;
1172 goto exit;
1173 }
1174
1175 /* Check for data on kernel pipe */
1176 if (revents & LPOLLIN) {
1177 if (pollfd == kernel_poll_pipe[0]) {
1178 (void) lttng_read(kernel_poll_pipe[0],
1179 &tmp, 1);
1180 /*
1181 * Ret value is useless here, if this pipe gets any actions an
1182 * update is required anyway.
1183 */
1184 update_poll_flag = 1;
1185 continue;
1186 } else {
1187 /*
1188 * New CPU detected by the kernel. Adding kernel stream to
1189 * kernel session and updating the kernel consumer
1190 */
1191 ret = update_kernel_stream(&kconsumer_data, pollfd);
1192 if (ret < 0) {
1193 continue;
1194 }
1195 break;
1196 }
1197 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
1198 update_poll_flag = 1;
1199 continue;
1200 } else {
1201 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
1202 goto error;
1203 }
1204 }
1205 }
1206
1207exit:
1208error:
1209 lttng_poll_clean(&events);
1210error_poll_create:
1211error_testpoint:
1212 utils_close_pipe(kernel_poll_pipe);
1213 kernel_poll_pipe[0] = kernel_poll_pipe[1] = -1;
1214 if (err) {
1215 health_error();
1216 ERR("Health error occurred in %s", __func__);
1217 WARN("Kernel thread died unexpectedly. "
1218 "Kernel tracing can continue but CPU hotplug is disabled.");
1219 }
1220 health_unregister(health_sessiond);
1221 DBG("Kernel thread dying");
1222 return NULL;
1223}
1224
1225/*
1226 * Signal pthread condition of the consumer data that the thread.
1227 */
1228static void signal_consumer_condition(struct consumer_data *data, int state)
1229{
1230 pthread_mutex_lock(&data->cond_mutex);
1231
1232 /*
1233 * The state is set before signaling. It can be any value, it's the waiter
1234 * job to correctly interpret this condition variable associated to the
1235 * consumer pthread_cond.
1236 *
1237 * A value of 0 means that the corresponding thread of the consumer data
1238 * was not started. 1 indicates that the thread has started and is ready
1239 * for action. A negative value means that there was an error during the
1240 * thread bootstrap.
1241 */
1242 data->consumer_thread_is_ready = state;
1243 (void) pthread_cond_signal(&data->cond);
1244
1245 pthread_mutex_unlock(&data->cond_mutex);
1246}
1247
1248/*
1249 * This thread manage the consumer error sent back to the session daemon.
1250 */
1251static void *thread_manage_consumer(void *data)
1252{
1253 int sock = -1, i, ret, pollfd, err = -1, should_quit = 0;
1254 uint32_t revents, nb_fd;
1255 enum lttcomm_return_code code;
1256 struct lttng_poll_event events;
1257 struct consumer_data *consumer_data = data;
1258 struct consumer_socket *cmd_socket_wrapper = NULL;
1259
1260 DBG("[thread] Manage consumer started");
1261
1262 rcu_register_thread();
1263 rcu_thread_online();
1264
1265 health_register(health_sessiond, HEALTH_SESSIOND_TYPE_CONSUMER);
1266
1267 health_code_update();
1268
1269 /*
1270 * Pass 3 as size here for the thread quit pipe, consumerd_err_sock and the
1271 * metadata_sock. Nothing more will be added to this poll set.
1272 */
1273 ret = sessiond_set_thread_pollset(&events, 3);
1274 if (ret < 0) {
1275 goto error_poll;
1276 }
1277
1278 /*
1279 * The error socket here is already in a listening state which was done
1280 * just before spawning this thread to avoid a race between the consumer
1281 * daemon exec trying to connect and the listen() call.
1282 */
1283 ret = lttng_poll_add(&events, consumer_data->err_sock, LPOLLIN | LPOLLRDHUP);
1284 if (ret < 0) {
1285 goto error;
1286 }
1287
1288 health_code_update();
1289
1290 /* Infinite blocking call, waiting for transmission */
1291restart:
1292 health_poll_entry();
1293
1294 if (testpoint(sessiond_thread_manage_consumer)) {
1295 goto error;
1296 }
1297
1298 ret = lttng_poll_wait(&events, -1);
1299 health_poll_exit();
1300 if (ret < 0) {
1301 /*
1302 * Restart interrupted system call.
1303 */
1304 if (errno == EINTR) {
1305 goto restart;
1306 }
1307 goto error;
1308 }
1309
1310 nb_fd = ret;
1311
1312 for (i = 0; i < nb_fd; i++) {
1313 /* Fetch once the poll data */
1314 revents = LTTNG_POLL_GETEV(&events, i);
1315 pollfd = LTTNG_POLL_GETFD(&events, i);
1316
1317 health_code_update();
1318
1319 if (!revents) {
1320 /* No activity for this FD (poll implementation). */
1321 continue;
1322 }
1323
1324 /* Thread quit pipe has been closed. Killing thread. */
1325 ret = sessiond_check_thread_quit_pipe(pollfd, revents);
1326 if (ret) {
1327 err = 0;
1328 goto exit;
1329 }
1330
1331 /* Event on the registration socket */
1332 if (pollfd == consumer_data->err_sock) {
1333 if (revents & LPOLLIN) {
1334 continue;
1335 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
1336 ERR("consumer err socket poll error");
1337 goto error;
1338 } else {
1339 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
1340 goto error;
1341 }
1342 }
1343 }
1344
1345 sock = lttcomm_accept_unix_sock(consumer_data->err_sock);
1346 if (sock < 0) {
1347 goto error;
1348 }
1349
1350 /*
1351 * Set the CLOEXEC flag. Return code is useless because either way, the
1352 * show must go on.
1353 */
1354 (void) utils_set_fd_cloexec(sock);
1355
1356 health_code_update();
1357
1358 DBG2("Receiving code from consumer err_sock");
1359
1360 /* Getting status code from kconsumerd */
1361 ret = lttcomm_recv_unix_sock(sock, &code,
1362 sizeof(enum lttcomm_return_code));
1363 if (ret <= 0) {
1364 goto error;
1365 }
1366
1367 health_code_update();
1368 if (code != LTTCOMM_CONSUMERD_COMMAND_SOCK_READY) {
1369 ERR("consumer error when waiting for SOCK_READY : %s",
1370 lttcomm_get_readable_code(-code));
1371 goto error;
1372 }
1373
1374 /* Connect both command and metadata sockets. */
1375 consumer_data->cmd_sock =
1376 lttcomm_connect_unix_sock(
1377 consumer_data->cmd_unix_sock_path);
1378 consumer_data->metadata_fd =
1379 lttcomm_connect_unix_sock(
1380 consumer_data->cmd_unix_sock_path);
1381 if (consumer_data->cmd_sock < 0 || consumer_data->metadata_fd < 0) {
1382 PERROR("consumer connect cmd socket");
1383 /* On error, signal condition and quit. */
1384 signal_consumer_condition(consumer_data, -1);
1385 goto error;
1386 }
1387
1388 consumer_data->metadata_sock.fd_ptr = &consumer_data->metadata_fd;
1389
1390 /* Create metadata socket lock. */
1391 consumer_data->metadata_sock.lock = zmalloc(sizeof(pthread_mutex_t));
1392 if (consumer_data->metadata_sock.lock == NULL) {
1393 PERROR("zmalloc pthread mutex");
1394 goto error;
1395 }
1396 pthread_mutex_init(consumer_data->metadata_sock.lock, NULL);
1397
1398 DBG("Consumer command socket ready (fd: %d", consumer_data->cmd_sock);
1399 DBG("Consumer metadata socket ready (fd: %d)",
1400 consumer_data->metadata_fd);
1401
1402 /*
1403 * Remove the consumerd error sock since we've established a connection.
1404 */
1405 ret = lttng_poll_del(&events, consumer_data->err_sock);
1406 if (ret < 0) {
1407 goto error;
1408 }
1409
1410 /* Add new accepted error socket. */
1411 ret = lttng_poll_add(&events, sock, LPOLLIN | LPOLLRDHUP);
1412 if (ret < 0) {
1413 goto error;
1414 }
1415
1416 /* Add metadata socket that is successfully connected. */
1417 ret = lttng_poll_add(&events, consumer_data->metadata_fd,
1418 LPOLLIN | LPOLLRDHUP);
1419 if (ret < 0) {
1420 goto error;
1421 }
1422
1423 health_code_update();
1424
1425 /*
1426 * Transfer the write-end of the channel monitoring pipe to the
1427 * by issuing a SET_CHANNEL_MONITOR_PIPE command.
1428 */
1429 cmd_socket_wrapper = consumer_allocate_socket(&consumer_data->cmd_sock);
1430 if (!cmd_socket_wrapper) {
1431 goto error;
1432 }
1433
1434 ret = consumer_send_channel_monitor_pipe(cmd_socket_wrapper,
1435 consumer_data->channel_monitor_pipe);
1436 if (ret) {
1437 goto error;
1438 }
1439 /* Discard the socket wrapper as it is no longer needed. */
1440 consumer_destroy_socket(cmd_socket_wrapper);
1441 cmd_socket_wrapper = NULL;
1442
1443 /* The thread is completely initialized, signal that it is ready. */
1444 signal_consumer_condition(consumer_data, 1);
1445
1446 /* Infinite blocking call, waiting for transmission */
1447restart_poll:
1448 while (1) {
1449 health_code_update();
1450
1451 /* Exit the thread because the thread quit pipe has been triggered. */
1452 if (should_quit) {
1453 /* Not a health error. */
1454 err = 0;
1455 goto exit;
1456 }
1457
1458 health_poll_entry();
1459 ret = lttng_poll_wait(&events, -1);
1460 health_poll_exit();
1461 if (ret < 0) {
1462 /*
1463 * Restart interrupted system call.
1464 */
1465 if (errno == EINTR) {
1466 goto restart_poll;
1467 }
1468 goto error;
1469 }
1470
1471 nb_fd = ret;
1472
1473 for (i = 0; i < nb_fd; i++) {
1474 /* Fetch once the poll data */
1475 revents = LTTNG_POLL_GETEV(&events, i);
1476 pollfd = LTTNG_POLL_GETFD(&events, i);
1477
1478 health_code_update();
1479
1480 if (!revents) {
1481 /* No activity for this FD (poll implementation). */
1482 continue;
1483 }
1484
1485 /*
1486 * Thread quit pipe has been triggered, flag that we should stop
1487 * but continue the current loop to handle potential data from
1488 * consumer.
1489 */
1490 should_quit = sessiond_check_thread_quit_pipe(pollfd, revents);
1491
1492 if (pollfd == sock) {
1493 /* Event on the consumerd socket */
1494 if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)
1495 && !(revents & LPOLLIN)) {
1496 ERR("consumer err socket second poll error");
1497 goto error;
1498 }
1499 health_code_update();
1500 /* Wait for any kconsumerd error */
1501 ret = lttcomm_recv_unix_sock(sock, &code,
1502 sizeof(enum lttcomm_return_code));
1503 if (ret <= 0) {
1504 ERR("consumer closed the command socket");
1505 goto error;
1506 }
1507
1508 ERR("consumer return code : %s",
1509 lttcomm_get_readable_code(-code));
1510
1511 goto exit;
1512 } else if (pollfd == consumer_data->metadata_fd) {
1513 if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)
1514 && !(revents & LPOLLIN)) {
1515 ERR("consumer err metadata socket second poll error");
1516 goto error;
1517 }
1518 /* UST metadata requests */
1519 ret = ust_consumer_metadata_request(
1520 &consumer_data->metadata_sock);
1521 if (ret < 0) {
1522 ERR("Handling metadata request");
1523 goto error;
1524 }
1525 }
1526 /* No need for an else branch all FDs are tested prior. */
1527 }
1528 health_code_update();
1529 }
1530
1531exit:
1532error:
1533 /*
1534 * We lock here because we are about to close the sockets and some other
1535 * thread might be using them so get exclusive access which will abort all
1536 * other consumer command by other threads.
1537 */
1538 pthread_mutex_lock(&consumer_data->lock);
1539
1540 /* Immediately set the consumerd state to stopped */
1541 if (consumer_data->type == LTTNG_CONSUMER_KERNEL) {
1542 uatomic_set(&kernel_consumerd_state, CONSUMER_ERROR);
1543 } else if (consumer_data->type == LTTNG_CONSUMER64_UST ||
1544 consumer_data->type == LTTNG_CONSUMER32_UST) {
1545 uatomic_set(&ust_consumerd_state, CONSUMER_ERROR);
1546 } else {
1547 /* Code flow error... */
1548 assert(0);
1549 }
1550
1551 if (consumer_data->err_sock >= 0) {
1552 ret = close(consumer_data->err_sock);
1553 if (ret) {
1554 PERROR("close");
1555 }
1556 consumer_data->err_sock = -1;
1557 }
1558 if (consumer_data->cmd_sock >= 0) {
1559 ret = close(consumer_data->cmd_sock);
1560 if (ret) {
1561 PERROR("close");
1562 }
1563 consumer_data->cmd_sock = -1;
1564 }
1565 if (consumer_data->metadata_sock.fd_ptr &&
1566 *consumer_data->metadata_sock.fd_ptr >= 0) {
1567 ret = close(*consumer_data->metadata_sock.fd_ptr);
1568 if (ret) {
1569 PERROR("close");
1570 }
1571 }
1572 if (sock >= 0) {
1573 ret = close(sock);
1574 if (ret) {
1575 PERROR("close");
1576 }
1577 }
1578
1579 unlink(consumer_data->err_unix_sock_path);
1580 unlink(consumer_data->cmd_unix_sock_path);
1581 pthread_mutex_unlock(&consumer_data->lock);
1582
1583 /* Cleanup metadata socket mutex. */
1584 if (consumer_data->metadata_sock.lock) {
1585 pthread_mutex_destroy(consumer_data->metadata_sock.lock);
1586 free(consumer_data->metadata_sock.lock);
1587 }
1588 lttng_poll_clean(&events);
1589
1590 if (cmd_socket_wrapper) {
1591 consumer_destroy_socket(cmd_socket_wrapper);
1592 }
1593error_poll:
1594 if (err) {
1595 health_error();
1596 ERR("Health error occurred in %s", __func__);
1597 }
1598 health_unregister(health_sessiond);
1599 DBG("consumer thread cleanup completed");
1600
1601 rcu_thread_offline();
1602 rcu_unregister_thread();
1603
1604 return NULL;
1605}
1606
1607/*
1608 * This thread manage application communication.
1609 */
1610static void *thread_manage_apps(void *data)
1611{
1612 int i, ret, pollfd, err = -1;
1613 ssize_t size_ret;
1614 uint32_t revents, nb_fd;
1615 struct lttng_poll_event events;
1616
1617 DBG("[thread] Manage application started");
1618
1619 rcu_register_thread();
1620 rcu_thread_online();
1621
1622 health_register(health_sessiond, HEALTH_SESSIOND_TYPE_APP_MANAGE);
1623
1624 if (testpoint(sessiond_thread_manage_apps)) {
1625 goto error_testpoint;
1626 }
1627
1628 health_code_update();
1629
1630 ret = sessiond_set_thread_pollset(&events, 2);
1631 if (ret < 0) {
1632 goto error_poll_create;
1633 }
1634
1635 ret = lttng_poll_add(&events, apps_cmd_pipe[0], LPOLLIN | LPOLLRDHUP);
1636 if (ret < 0) {
1637 goto error;
1638 }
1639
1640 if (testpoint(sessiond_thread_manage_apps_before_loop)) {
1641 goto error;
1642 }
1643
1644 health_code_update();
1645
1646 while (1) {
1647 DBG("Apps thread polling");
1648
1649 /* Inifinite blocking call, waiting for transmission */
1650 restart:
1651 health_poll_entry();
1652 ret = lttng_poll_wait(&events, -1);
1653 DBG("Apps thread return from poll on %d fds",
1654 LTTNG_POLL_GETNB(&events));
1655 health_poll_exit();
1656 if (ret < 0) {
1657 /*
1658 * Restart interrupted system call.
1659 */
1660 if (errno == EINTR) {
1661 goto restart;
1662 }
1663 goto error;
1664 }
1665
1666 nb_fd = ret;
1667
1668 for (i = 0; i < nb_fd; i++) {
1669 /* Fetch once the poll data */
1670 revents = LTTNG_POLL_GETEV(&events, i);
1671 pollfd = LTTNG_POLL_GETFD(&events, i);
1672
1673 health_code_update();
1674
1675 if (!revents) {
1676 /* No activity for this FD (poll implementation). */
1677 continue;
1678 }
1679
1680 /* Thread quit pipe has been closed. Killing thread. */
1681 ret = sessiond_check_thread_quit_pipe(pollfd, revents);
1682 if (ret) {
1683 err = 0;
1684 goto exit;
1685 }
1686
1687 /* Inspect the apps cmd pipe */
1688 if (pollfd == apps_cmd_pipe[0]) {
1689 if (revents & LPOLLIN) {
1690 int sock;
1691
1692 /* Empty pipe */
1693 size_ret = lttng_read(apps_cmd_pipe[0], &sock, sizeof(sock));
1694 if (size_ret < sizeof(sock)) {
1695 PERROR("read apps cmd pipe");
1696 goto error;
1697 }
1698
1699 health_code_update();
1700
1701 /*
1702 * Since this is a command socket (write then read),
1703 * we only monitor the error events of the socket.
1704 */
1705 ret = lttng_poll_add(&events, sock,
1706 LPOLLERR | LPOLLHUP | LPOLLRDHUP);
1707 if (ret < 0) {
1708 goto error;
1709 }
1710
1711 DBG("Apps with sock %d added to poll set", sock);
1712 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
1713 ERR("Apps command pipe error");
1714 goto error;
1715 } else {
1716 ERR("Unknown poll events %u for sock %d", revents, pollfd);
1717 goto error;
1718 }
1719 } else {
1720 /*
1721 * At this point, we know that a registered application made
1722 * the event at poll_wait.
1723 */
1724 if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
1725 /* Removing from the poll set */
1726 ret = lttng_poll_del(&events, pollfd);
1727 if (ret < 0) {
1728 goto error;
1729 }
1730
1731 /* Socket closed on remote end. */
1732 ust_app_unregister(pollfd);
1733 } else {
1734 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
1735 goto error;
1736 }
1737 }
1738
1739 health_code_update();
1740 }
1741 }
1742
1743exit:
1744error:
1745 lttng_poll_clean(&events);
1746error_poll_create:
1747error_testpoint:
1748 utils_close_pipe(apps_cmd_pipe);
1749 apps_cmd_pipe[0] = apps_cmd_pipe[1] = -1;
1750
1751 /*
1752 * We don't clean the UST app hash table here since already registered
1753 * applications can still be controlled so let them be until the session
1754 * daemon dies or the applications stop.
1755 */
1756
1757 if (err) {
1758 health_error();
1759 ERR("Health error occurred in %s", __func__);
1760 }
1761 health_unregister(health_sessiond);
1762 DBG("Application communication apps thread cleanup complete");
1763 rcu_thread_offline();
1764 rcu_unregister_thread();
1765 return NULL;
1766}
1767
1768/*
1769 * Send a socket to a thread This is called from the dispatch UST registration
1770 * thread once all sockets are set for the application.
1771 *
1772 * The sock value can be invalid, we don't really care, the thread will handle
1773 * it and make the necessary cleanup if so.
1774 *
1775 * On success, return 0 else a negative value being the errno message of the
1776 * write().
1777 */
1778static int send_socket_to_thread(int fd, int sock)
1779{
1780 ssize_t ret;
1781
1782 /*
1783 * It's possible that the FD is set as invalid with -1 concurrently just
1784 * before calling this function being a shutdown state of the thread.
1785 */
1786 if (fd < 0) {
1787 ret = -EBADF;
1788 goto error;
1789 }
1790
1791 ret = lttng_write(fd, &sock, sizeof(sock));
1792 if (ret < sizeof(sock)) {
1793 PERROR("write apps pipe %d", fd);
1794 if (ret < 0) {
1795 ret = -errno;
1796 }
1797 goto error;
1798 }
1799
1800 /* All good. Don't send back the write positive ret value. */
1801 ret = 0;
1802error:
1803 return (int) ret;
1804}
1805
1806/*
1807 * Sanitize the wait queue of the dispatch registration thread meaning removing
1808 * invalid nodes from it. This is to avoid memory leaks for the case the UST
1809 * notify socket is never received.
1810 */
1811static void sanitize_wait_queue(struct ust_reg_wait_queue *wait_queue)
1812{
1813 int ret, nb_fd = 0, i;
1814 unsigned int fd_added = 0;
1815 struct lttng_poll_event events;
1816 struct ust_reg_wait_node *wait_node = NULL, *tmp_wait_node;
1817
1818 assert(wait_queue);
1819
1820 lttng_poll_init(&events);
1821
1822 /* Just skip everything for an empty queue. */
1823 if (!wait_queue->count) {
1824 goto end;
1825 }
1826
1827 ret = lttng_poll_create(&events, wait_queue->count, LTTNG_CLOEXEC);
1828 if (ret < 0) {
1829 goto error_create;
1830 }
1831
1832 cds_list_for_each_entry_safe(wait_node, tmp_wait_node,
1833 &wait_queue->head, head) {
1834 assert(wait_node->app);
1835 ret = lttng_poll_add(&events, wait_node->app->sock,
1836 LPOLLHUP | LPOLLERR);
1837 if (ret < 0) {
1838 goto error;
1839 }
1840
1841 fd_added = 1;
1842 }
1843
1844 if (!fd_added) {
1845 goto end;
1846 }
1847
1848 /*
1849 * Poll but don't block so we can quickly identify the faulty events and
1850 * clean them afterwards from the wait queue.
1851 */
1852 ret = lttng_poll_wait(&events, 0);
1853 if (ret < 0) {
1854 goto error;
1855 }
1856 nb_fd = ret;
1857
1858 for (i = 0; i < nb_fd; i++) {
1859 /* Get faulty FD. */
1860 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
1861 int pollfd = LTTNG_POLL_GETFD(&events, i);
1862
1863 if (!revents) {
1864 /* No activity for this FD (poll implementation). */
1865 continue;
1866 }
1867
1868 cds_list_for_each_entry_safe(wait_node, tmp_wait_node,
1869 &wait_queue->head, head) {
1870 if (pollfd == wait_node->app->sock &&
1871 (revents & (LPOLLHUP | LPOLLERR))) {
1872 cds_list_del(&wait_node->head);
1873 wait_queue->count--;
1874 ust_app_destroy(wait_node->app);
1875 free(wait_node);
1876 /*
1877 * Silence warning of use-after-free in
1878 * cds_list_for_each_entry_safe which uses
1879 * __typeof__(*wait_node).
1880 */
1881 wait_node = NULL;
1882 break;
1883 } else {
1884 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
1885 goto error;
1886 }
1887 }
1888 }
1889
1890 if (nb_fd > 0) {
1891 DBG("Wait queue sanitized, %d node were cleaned up", nb_fd);
1892 }
1893
1894end:
1895 lttng_poll_clean(&events);
1896 return;
1897
1898error:
1899 lttng_poll_clean(&events);
1900error_create:
1901 ERR("Unable to sanitize wait queue");
1902 return;
1903}
1904
1905/*
1906 * Dispatch request from the registration threads to the application
1907 * communication thread.
1908 */
1909static void *thread_dispatch_ust_registration(void *data)
1910{
1911 int ret, err = -1;
1912 struct cds_wfcq_node *node;
1913 struct ust_command *ust_cmd = NULL;
1914 struct ust_reg_wait_node *wait_node = NULL, *tmp_wait_node;
1915 struct ust_reg_wait_queue wait_queue = {
1916 .count = 0,
1917 };
1918
1919 rcu_register_thread();
1920
1921 health_register(health_sessiond, HEALTH_SESSIOND_TYPE_APP_REG_DISPATCH);
1922
1923 if (testpoint(sessiond_thread_app_reg_dispatch)) {
1924 goto error_testpoint;
1925 }
1926
1927 health_code_update();
1928
1929 CDS_INIT_LIST_HEAD(&wait_queue.head);
1930
1931 DBG("[thread] Dispatch UST command started");
1932
1933 while (!CMM_LOAD_SHARED(dispatch_thread_exit)) {
1934 health_code_update();
1935
1936 /* Atomically prepare the queue futex */
1937 futex_nto1_prepare(&ust_cmd_queue.futex);
1938
1939 do {
1940 struct ust_app *app = NULL;
1941 ust_cmd = NULL;
1942
1943 /*
1944 * Make sure we don't have node(s) that have hung up before receiving
1945 * the notify socket. This is to clean the list in order to avoid
1946 * memory leaks from notify socket that are never seen.
1947 */
1948 sanitize_wait_queue(&wait_queue);
1949
1950 health_code_update();
1951 /* Dequeue command for registration */
1952 node = cds_wfcq_dequeue_blocking(&ust_cmd_queue.head, &ust_cmd_queue.tail);
1953 if (node == NULL) {
1954 DBG("Woken up but nothing in the UST command queue");
1955 /* Continue thread execution */
1956 break;
1957 }
1958
1959 ust_cmd = caa_container_of(node, struct ust_command, node);
1960
1961 DBG("Dispatching UST registration pid:%d ppid:%d uid:%d"
1962 " gid:%d sock:%d name:%s (version %d.%d)",
1963 ust_cmd->reg_msg.pid, ust_cmd->reg_msg.ppid,
1964 ust_cmd->reg_msg.uid, ust_cmd->reg_msg.gid,
1965 ust_cmd->sock, ust_cmd->reg_msg.name,
1966 ust_cmd->reg_msg.major, ust_cmd->reg_msg.minor);
1967
1968 if (ust_cmd->reg_msg.type == USTCTL_SOCKET_CMD) {
1969 wait_node = zmalloc(sizeof(*wait_node));
1970 if (!wait_node) {
1971 PERROR("zmalloc wait_node dispatch");
1972 ret = close(ust_cmd->sock);
1973 if (ret < 0) {
1974 PERROR("close ust sock dispatch %d", ust_cmd->sock);
1975 }
1976 lttng_fd_put(LTTNG_FD_APPS, 1);
1977 free(ust_cmd);
1978 goto error;
1979 }
1980 CDS_INIT_LIST_HEAD(&wait_node->head);
1981
1982 /* Create application object if socket is CMD. */
1983 wait_node->app = ust_app_create(&ust_cmd->reg_msg,
1984 ust_cmd->sock);
1985 if (!wait_node->app) {
1986 ret = close(ust_cmd->sock);
1987 if (ret < 0) {
1988 PERROR("close ust sock dispatch %d", ust_cmd->sock);
1989 }
1990 lttng_fd_put(LTTNG_FD_APPS, 1);
1991 free(wait_node);
1992 free(ust_cmd);
1993 continue;
1994 }
1995 /*
1996 * Add application to the wait queue so we can set the notify
1997 * socket before putting this object in the global ht.
1998 */
1999 cds_list_add(&wait_node->head, &wait_queue.head);
2000 wait_queue.count++;
2001
2002 free(ust_cmd);
2003 /*
2004 * We have to continue here since we don't have the notify
2005 * socket and the application MUST be added to the hash table
2006 * only at that moment.
2007 */
2008 continue;
2009 } else {
2010 /*
2011 * Look for the application in the local wait queue and set the
2012 * notify socket if found.
2013 */
2014 cds_list_for_each_entry_safe(wait_node, tmp_wait_node,
2015 &wait_queue.head, head) {
2016 health_code_update();
2017 if (wait_node->app->pid == ust_cmd->reg_msg.pid) {
2018 wait_node->app->notify_sock = ust_cmd->sock;
2019 cds_list_del(&wait_node->head);
2020 wait_queue.count--;
2021 app = wait_node->app;
2022 free(wait_node);
2023 DBG3("UST app notify socket %d is set", ust_cmd->sock);
2024 break;
2025 }
2026 }
2027
2028 /*
2029 * With no application at this stage the received socket is
2030 * basically useless so close it before we free the cmd data
2031 * structure for good.
2032 */
2033 if (!app) {
2034 ret = close(ust_cmd->sock);
2035 if (ret < 0) {
2036 PERROR("close ust sock dispatch %d", ust_cmd->sock);
2037 }
2038 lttng_fd_put(LTTNG_FD_APPS, 1);
2039 }
2040 free(ust_cmd);
2041 }
2042
2043 if (app) {
2044 /*
2045 * @session_lock_list
2046 *
2047 * Lock the global session list so from the register up to the
2048 * registration done message, no thread can see the application
2049 * and change its state.
2050 */
2051 session_lock_list();
2052 rcu_read_lock();
2053
2054 /*
2055 * Add application to the global hash table. This needs to be
2056 * done before the update to the UST registry can locate the
2057 * application.
2058 */
2059 ust_app_add(app);
2060
2061 /* Set app version. This call will print an error if needed. */
2062 (void) ust_app_version(app);
2063
2064 /* Send notify socket through the notify pipe. */
2065 ret = send_socket_to_thread(apps_cmd_notify_pipe[1],
2066 app->notify_sock);
2067 if (ret < 0) {
2068 rcu_read_unlock();
2069 session_unlock_list();
2070 /*
2071 * No notify thread, stop the UST tracing. However, this is
2072 * not an internal error of the this thread thus setting
2073 * the health error code to a normal exit.
2074 */
2075 err = 0;
2076 goto error;
2077 }
2078
2079 /*
2080 * Update newly registered application with the tracing
2081 * registry info already enabled information.
2082 */
2083 update_ust_app(app->sock);
2084
2085 /*
2086 * Don't care about return value. Let the manage apps threads
2087 * handle app unregistration upon socket close.
2088 */
2089 (void) ust_app_register_done(app);
2090
2091 /*
2092 * Even if the application socket has been closed, send the app
2093 * to the thread and unregistration will take place at that
2094 * place.
2095 */
2096 ret = send_socket_to_thread(apps_cmd_pipe[1], app->sock);
2097 if (ret < 0) {
2098 rcu_read_unlock();
2099 session_unlock_list();
2100 /*
2101 * No apps. thread, stop the UST tracing. However, this is
2102 * not an internal error of the this thread thus setting
2103 * the health error code to a normal exit.
2104 */
2105 err = 0;
2106 goto error;
2107 }
2108
2109 rcu_read_unlock();
2110 session_unlock_list();
2111 }
2112 } while (node != NULL);
2113
2114 health_poll_entry();
2115 /* Futex wait on queue. Blocking call on futex() */
2116 futex_nto1_wait(&ust_cmd_queue.futex);
2117 health_poll_exit();
2118 }
2119 /* Normal exit, no error */
2120 err = 0;
2121
2122error:
2123 /* Clean up wait queue. */
2124 cds_list_for_each_entry_safe(wait_node, tmp_wait_node,
2125 &wait_queue.head, head) {
2126 cds_list_del(&wait_node->head);
2127 wait_queue.count--;
2128 free(wait_node);
2129 }
2130
2131 /* Empty command queue. */
2132 for (;;) {
2133 /* Dequeue command for registration */
2134 node = cds_wfcq_dequeue_blocking(&ust_cmd_queue.head, &ust_cmd_queue.tail);
2135 if (node == NULL) {
2136 break;
2137 }
2138 ust_cmd = caa_container_of(node, struct ust_command, node);
2139 ret = close(ust_cmd->sock);
2140 if (ret < 0) {
2141 PERROR("close ust sock exit dispatch %d", ust_cmd->sock);
2142 }
2143 lttng_fd_put(LTTNG_FD_APPS, 1);
2144 free(ust_cmd);
2145 }
2146
2147error_testpoint:
2148 DBG("Dispatch thread dying");
2149 if (err) {
2150 health_error();
2151 ERR("Health error occurred in %s", __func__);
2152 }
2153 health_unregister(health_sessiond);
2154 rcu_unregister_thread();
2155 return NULL;
2156}
2157
2158/*
2159 * This thread manage application registration.
2160 */
2161static void *thread_registration_apps(void *data)
2162{
2163 int sock = -1, i, ret, pollfd, err = -1;
2164 uint32_t revents, nb_fd;
2165 struct lttng_poll_event events;
2166 /*
2167 * Get allocated in this thread, enqueued to a global queue, dequeued and
2168 * freed in the manage apps thread.
2169 */
2170 struct ust_command *ust_cmd = NULL;
2171
2172 DBG("[thread] Manage application registration started");
2173
2174 health_register(health_sessiond, HEALTH_SESSIOND_TYPE_APP_REG);
2175
2176 if (testpoint(sessiond_thread_registration_apps)) {
2177 goto error_testpoint;
2178 }
2179
2180 ret = lttcomm_listen_unix_sock(apps_sock);
2181 if (ret < 0) {
2182 goto error_listen;
2183 }
2184
2185 /*
2186 * Pass 2 as size here for the thread quit pipe and apps socket. Nothing
2187 * more will be added to this poll set.
2188 */
2189 ret = sessiond_set_thread_pollset(&events, 2);
2190 if (ret < 0) {
2191 goto error_create_poll;
2192 }
2193
2194 /* Add the application registration socket */
2195 ret = lttng_poll_add(&events, apps_sock, LPOLLIN | LPOLLRDHUP);
2196 if (ret < 0) {
2197 goto error_poll_add;
2198 }
2199
2200 /* Notify all applications to register */
2201 ret = notify_ust_apps(1);
2202 if (ret < 0) {
2203 ERR("Failed to notify applications or create the wait shared memory.\n"
2204 "Execution continues but there might be problem for already\n"
2205 "running applications that wishes to register.");
2206 }
2207
2208 while (1) {
2209 DBG("Accepting application registration");
2210
2211 /* Inifinite blocking call, waiting for transmission */
2212 restart:
2213 health_poll_entry();
2214 ret = lttng_poll_wait(&events, -1);
2215 health_poll_exit();
2216 if (ret < 0) {
2217 /*
2218 * Restart interrupted system call.
2219 */
2220 if (errno == EINTR) {
2221 goto restart;
2222 }
2223 goto error;
2224 }
2225
2226 nb_fd = ret;
2227
2228 for (i = 0; i < nb_fd; i++) {
2229 health_code_update();
2230
2231 /* Fetch once the poll data */
2232 revents = LTTNG_POLL_GETEV(&events, i);
2233 pollfd = LTTNG_POLL_GETFD(&events, i);
2234
2235 if (!revents) {
2236 /* No activity for this FD (poll implementation). */
2237 continue;
2238 }
2239
2240 /* Thread quit pipe has been closed. Killing thread. */
2241 ret = sessiond_check_thread_quit_pipe(pollfd, revents);
2242 if (ret) {
2243 err = 0;
2244 goto exit;
2245 }
2246
2247 /* Event on the registration socket */
2248 if (pollfd == apps_sock) {
2249 if (revents & LPOLLIN) {
2250 sock = lttcomm_accept_unix_sock(apps_sock);
2251 if (sock < 0) {
2252 goto error;
2253 }
2254
2255 /*
2256 * Set socket timeout for both receiving and ending.
2257 * app_socket_timeout is in seconds, whereas
2258 * lttcomm_setsockopt_rcv_timeout and
2259 * lttcomm_setsockopt_snd_timeout expect msec as
2260 * parameter.
2261 */
2262 if (app_socket_timeout >= 0) {
2263 (void) lttcomm_setsockopt_rcv_timeout(sock,
2264 app_socket_timeout * 1000);
2265 (void) lttcomm_setsockopt_snd_timeout(sock,
2266 app_socket_timeout * 1000);
2267 }
2268
2269 /*
2270 * Set the CLOEXEC flag. Return code is useless because
2271 * either way, the show must go on.
2272 */
2273 (void) utils_set_fd_cloexec(sock);
2274
2275 /* Create UST registration command for enqueuing */
2276 ust_cmd = zmalloc(sizeof(struct ust_command));
2277 if (ust_cmd == NULL) {
2278 PERROR("ust command zmalloc");
2279 ret = close(sock);
2280 if (ret) {
2281 PERROR("close");
2282 }
2283 goto error;
2284 }
2285
2286 /*
2287 * Using message-based transmissions to ensure we don't
2288 * have to deal with partially received messages.
2289 */
2290 ret = lttng_fd_get(LTTNG_FD_APPS, 1);
2291 if (ret < 0) {
2292 ERR("Exhausted file descriptors allowed for applications.");
2293 free(ust_cmd);
2294 ret = close(sock);
2295 if (ret) {
2296 PERROR("close");
2297 }
2298 sock = -1;
2299 continue;
2300 }
2301
2302 health_code_update();
2303 ret = ust_app_recv_registration(sock, &ust_cmd->reg_msg);
2304 if (ret < 0) {
2305 free(ust_cmd);
2306 /* Close socket of the application. */
2307 ret = close(sock);
2308 if (ret) {
2309 PERROR("close");
2310 }
2311 lttng_fd_put(LTTNG_FD_APPS, 1);
2312 sock = -1;
2313 continue;
2314 }
2315 health_code_update();
2316
2317 ust_cmd->sock = sock;
2318 sock = -1;
2319
2320 DBG("UST registration received with pid:%d ppid:%d uid:%d"
2321 " gid:%d sock:%d name:%s (version %d.%d)",
2322 ust_cmd->reg_msg.pid, ust_cmd->reg_msg.ppid,
2323 ust_cmd->reg_msg.uid, ust_cmd->reg_msg.gid,
2324 ust_cmd->sock, ust_cmd->reg_msg.name,
2325 ust_cmd->reg_msg.major, ust_cmd->reg_msg.minor);
2326
2327 /*
2328 * Lock free enqueue the registration request. The red pill
2329 * has been taken! This apps will be part of the *system*.
2330 */
2331 cds_wfcq_enqueue(&ust_cmd_queue.head, &ust_cmd_queue.tail, &ust_cmd->node);
2332
2333 /*
2334 * Wake the registration queue futex. Implicit memory
2335 * barrier with the exchange in cds_wfcq_enqueue.
2336 */
2337 futex_nto1_wake(&ust_cmd_queue.futex);
2338 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2339 ERR("Register apps socket poll error");
2340 goto error;
2341 } else {
2342 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
2343 goto error;
2344 }
2345 }
2346 }
2347 }
2348
2349exit:
2350error:
2351 /* Notify that the registration thread is gone */
2352 notify_ust_apps(0);
2353
2354 if (apps_sock >= 0) {
2355 ret = close(apps_sock);
2356 if (ret) {
2357 PERROR("close");
2358 }
2359 }
2360 if (sock >= 0) {
2361 ret = close(sock);
2362 if (ret) {
2363 PERROR("close");
2364 }
2365 lttng_fd_put(LTTNG_FD_APPS, 1);
2366 }
2367 unlink(apps_unix_sock_path);
2368
2369error_poll_add:
2370 lttng_poll_clean(&events);
2371error_listen:
2372error_create_poll:
2373error_testpoint:
2374 DBG("UST Registration thread cleanup complete");
2375 if (err) {
2376 health_error();
2377 ERR("Health error occurred in %s", __func__);
2378 }
2379 health_unregister(health_sessiond);
2380
2381 return NULL;
2382}
2383
2384/*
2385 * Start the thread_manage_consumer. This must be done after a lttng-consumerd
2386 * exec or it will fails.
2387 */
2388static int spawn_consumer_thread(struct consumer_data *consumer_data)
2389{
2390 int ret, clock_ret;
2391 struct timespec timeout;
2392
2393 /*
2394 * Make sure we set the readiness flag to 0 because we are NOT ready.
2395 * This access to consumer_thread_is_ready does not need to be
2396 * protected by consumer_data.cond_mutex (yet) since the consumer
2397 * management thread has not been started at this point.
2398 */
2399 consumer_data->consumer_thread_is_ready = 0;
2400
2401 /* Setup pthread condition */
2402 ret = pthread_condattr_init(&consumer_data->condattr);
2403 if (ret) {
2404 errno = ret;
2405 PERROR("pthread_condattr_init consumer data");
2406 goto error;
2407 }
2408
2409 /*
2410 * Set the monotonic clock in order to make sure we DO NOT jump in time
2411 * between the clock_gettime() call and the timedwait call. See bug #324
2412 * for a more details and how we noticed it.
2413 */
2414 ret = pthread_condattr_setclock(&consumer_data->condattr, CLOCK_MONOTONIC);
2415 if (ret) {
2416 errno = ret;
2417 PERROR("pthread_condattr_setclock consumer data");
2418 goto error;
2419 }
2420
2421 ret = pthread_cond_init(&consumer_data->cond, &consumer_data->condattr);
2422 if (ret) {
2423 errno = ret;
2424 PERROR("pthread_cond_init consumer data");
2425 goto error;
2426 }
2427
2428 ret = pthread_create(&consumer_data->thread, default_pthread_attr(),
2429 thread_manage_consumer, consumer_data);
2430 if (ret) {
2431 errno = ret;
2432 PERROR("pthread_create consumer");
2433 ret = -1;
2434 goto error;
2435 }
2436
2437 /* We are about to wait on a pthread condition */
2438 pthread_mutex_lock(&consumer_data->cond_mutex);
2439
2440 /* Get time for sem_timedwait absolute timeout */
2441 clock_ret = lttng_clock_gettime(CLOCK_MONOTONIC, &timeout);
2442 /*
2443 * Set the timeout for the condition timed wait even if the clock gettime
2444 * call fails since we might loop on that call and we want to avoid to
2445 * increment the timeout too many times.
2446 */
2447 timeout.tv_sec += DEFAULT_SEM_WAIT_TIMEOUT;
2448
2449 /*
2450 * The following loop COULD be skipped in some conditions so this is why we
2451 * set ret to 0 in order to make sure at least one round of the loop is
2452 * done.
2453 */
2454 ret = 0;
2455
2456 /*
2457 * Loop until the condition is reached or when a timeout is reached. Note
2458 * that the pthread_cond_timedwait(P) man page specifies that EINTR can NOT
2459 * be returned but the pthread_cond(3), from the glibc-doc, says that it is
2460 * possible. This loop does not take any chances and works with both of
2461 * them.
2462 */
2463 while (!consumer_data->consumer_thread_is_ready && ret != ETIMEDOUT) {
2464 if (clock_ret < 0) {
2465 PERROR("clock_gettime spawn consumer");
2466 /* Infinite wait for the consumerd thread to be ready */
2467 ret = pthread_cond_wait(&consumer_data->cond,
2468 &consumer_data->cond_mutex);
2469 } else {
2470 ret = pthread_cond_timedwait(&consumer_data->cond,
2471 &consumer_data->cond_mutex, &timeout);
2472 }
2473 }
2474
2475 /* Release the pthread condition */
2476 pthread_mutex_unlock(&consumer_data->cond_mutex);
2477
2478 if (ret != 0) {
2479 errno = ret;
2480 if (ret == ETIMEDOUT) {
2481 int pth_ret;
2482
2483 /*
2484 * Call has timed out so we kill the kconsumerd_thread and return
2485 * an error.
2486 */
2487 ERR("Condition timed out. The consumer thread was never ready."
2488 " Killing it");
2489 pth_ret = pthread_cancel(consumer_data->thread);
2490 if (pth_ret < 0) {
2491 PERROR("pthread_cancel consumer thread");
2492 }
2493 } else {
2494 PERROR("pthread_cond_wait failed consumer thread");
2495 }
2496 /* Caller is expecting a negative value on failure. */
2497 ret = -1;
2498 goto error;
2499 }
2500
2501 pthread_mutex_lock(&consumer_data->pid_mutex);
2502 if (consumer_data->pid == 0) {
2503 ERR("Consumerd did not start");
2504 pthread_mutex_unlock(&consumer_data->pid_mutex);
2505 goto error;
2506 }
2507 pthread_mutex_unlock(&consumer_data->pid_mutex);
2508
2509 return 0;
2510
2511error:
2512 return ret;
2513}
2514
2515/*
2516 * Join consumer thread
2517 */
2518static int join_consumer_thread(struct consumer_data *consumer_data)
2519{
2520 void *status;
2521
2522 /* Consumer pid must be a real one. */
2523 if (consumer_data->pid > 0) {
2524 int ret;
2525 ret = kill(consumer_data->pid, SIGTERM);
2526 if (ret) {
2527 PERROR("Error killing consumer daemon");
2528 return ret;
2529 }
2530 return pthread_join(consumer_data->thread, &status);
2531 } else {
2532 return 0;
2533 }
2534}
2535
2536/*
2537 * Fork and exec a consumer daemon (consumerd).
2538 *
2539 * Return pid if successful else -1.
2540 */
2541static pid_t spawn_consumerd(struct consumer_data *consumer_data)
2542{
2543 int ret;
2544 pid_t pid;
2545 const char *consumer_to_use;
2546 const char *verbosity;
2547 struct stat st;
2548
2549 DBG("Spawning consumerd");
2550
2551 pid = fork();
2552 if (pid == 0) {
2553 /*
2554 * Exec consumerd.
2555 */
2556 if (opt_verbose_consumer) {
2557 verbosity = "--verbose";
2558 } else if (lttng_opt_quiet) {
2559 verbosity = "--quiet";
2560 } else {
2561 verbosity = "";
2562 }
2563
2564 switch (consumer_data->type) {
2565 case LTTNG_CONSUMER_KERNEL:
2566 /*
2567 * Find out which consumerd to execute. We will first try the
2568 * 64-bit path, then the sessiond's installation directory, and
2569 * fallback on the 32-bit one,
2570 */
2571 DBG3("Looking for a kernel consumer at these locations:");
2572 DBG3(" 1) %s", consumerd64_bin);
2573 DBG3(" 2) %s/%s", INSTALL_BIN_PATH, CONSUMERD_FILE);
2574 DBG3(" 3) %s", consumerd32_bin);
2575 if (stat(consumerd64_bin, &st) == 0) {
2576 DBG3("Found location #1");
2577 consumer_to_use = consumerd64_bin;
2578 } else if (stat(INSTALL_BIN_PATH "/" CONSUMERD_FILE, &st) == 0) {
2579 DBG3("Found location #2");
2580 consumer_to_use = INSTALL_BIN_PATH "/" CONSUMERD_FILE;
2581 } else if (stat(consumerd32_bin, &st) == 0) {
2582 DBG3("Found location #3");
2583 consumer_to_use = consumerd32_bin;
2584 } else {
2585 DBG("Could not find any valid consumerd executable");
2586 ret = -EINVAL;
2587 break;
2588 }
2589 DBG("Using kernel consumer at: %s", consumer_to_use);
2590 ret = execl(consumer_to_use,
2591 "lttng-consumerd", verbosity, "-k",
2592 "--consumerd-cmd-sock", consumer_data->cmd_unix_sock_path,
2593 "--consumerd-err-sock", consumer_data->err_unix_sock_path,
2594 "--group", tracing_group_name,
2595 NULL);
2596 break;
2597 case LTTNG_CONSUMER64_UST:
2598 {
2599 char *tmpnew = NULL;
2600
2601 if (consumerd64_libdir[0] != '\0') {
2602 char *tmp;
2603 size_t tmplen;
2604
2605 tmp = lttng_secure_getenv("LD_LIBRARY_PATH");
2606 if (!tmp) {
2607 tmp = "";
2608 }
2609 tmplen = strlen("LD_LIBRARY_PATH=")
2610 + strlen(consumerd64_libdir) + 1 /* : */ + strlen(tmp);
2611 tmpnew = zmalloc(tmplen + 1 /* \0 */);
2612 if (!tmpnew) {
2613 ret = -ENOMEM;
2614 goto error;
2615 }
2616 strcpy(tmpnew, "LD_LIBRARY_PATH=");
2617 strcat(tmpnew, consumerd64_libdir);
2618 if (tmp[0] != '\0') {
2619 strcat(tmpnew, ":");
2620 strcat(tmpnew, tmp);
2621 }
2622 ret = putenv(tmpnew);
2623 if (ret) {
2624 ret = -errno;
2625 free(tmpnew);
2626 goto error;
2627 }
2628 }
2629 DBG("Using 64-bit UST consumer at: %s", consumerd64_bin);
2630 ret = execl(consumerd64_bin, "lttng-consumerd", verbosity, "-u",
2631 "--consumerd-cmd-sock", consumer_data->cmd_unix_sock_path,
2632 "--consumerd-err-sock", consumer_data->err_unix_sock_path,
2633 "--group", tracing_group_name,
2634 NULL);
2635 if (consumerd64_libdir[0] != '\0') {
2636 free(tmpnew);
2637 }
2638 break;
2639 }
2640 case LTTNG_CONSUMER32_UST:
2641 {
2642 char *tmpnew = NULL;
2643
2644 if (consumerd32_libdir[0] != '\0') {
2645 char *tmp;
2646 size_t tmplen;
2647
2648 tmp = lttng_secure_getenv("LD_LIBRARY_PATH");
2649 if (!tmp) {
2650 tmp = "";
2651 }
2652 tmplen = strlen("LD_LIBRARY_PATH=")
2653 + strlen(consumerd32_libdir) + 1 /* : */ + strlen(tmp);
2654 tmpnew = zmalloc(tmplen + 1 /* \0 */);
2655 if (!tmpnew) {
2656 ret = -ENOMEM;
2657 goto error;
2658 }
2659 strcpy(tmpnew, "LD_LIBRARY_PATH=");
2660 strcat(tmpnew, consumerd32_libdir);
2661 if (tmp[0] != '\0') {
2662 strcat(tmpnew, ":");
2663 strcat(tmpnew, tmp);
2664 }
2665 ret = putenv(tmpnew);
2666 if (ret) {
2667 ret = -errno;
2668 free(tmpnew);
2669 goto error;
2670 }
2671 }
2672 DBG("Using 32-bit UST consumer at: %s", consumerd32_bin);
2673 ret = execl(consumerd32_bin, "lttng-consumerd", verbosity, "-u",
2674 "--consumerd-cmd-sock", consumer_data->cmd_unix_sock_path,
2675 "--consumerd-err-sock", consumer_data->err_unix_sock_path,
2676 "--group", tracing_group_name,
2677 NULL);
2678 if (consumerd32_libdir[0] != '\0') {
2679 free(tmpnew);
2680 }
2681 break;
2682 }
2683 default:
2684 PERROR("unknown consumer type");
2685 exit(EXIT_FAILURE);
2686 }
2687 if (errno != 0) {
2688 PERROR("Consumer execl()");
2689 }
2690 /* Reaching this point, we got a failure on our execl(). */
2691 exit(EXIT_FAILURE);
2692 } else if (pid > 0) {
2693 ret = pid;
2694 } else {
2695 PERROR("start consumer fork");
2696 ret = -errno;
2697 }
2698error:
2699 return ret;
2700}
2701
2702/*
2703 * Spawn the consumerd daemon and session daemon thread.
2704 */
2705static int start_consumerd(struct consumer_data *consumer_data)
2706{
2707 int ret;
2708
2709 /*
2710 * Set the listen() state on the socket since there is a possible race
2711 * between the exec() of the consumer daemon and this call if place in the
2712 * consumer thread. See bug #366 for more details.
2713 */
2714 ret = lttcomm_listen_unix_sock(consumer_data->err_sock);
2715 if (ret < 0) {
2716 goto error;
2717 }
2718
2719 pthread_mutex_lock(&consumer_data->pid_mutex);
2720 if (consumer_data->pid != 0) {
2721 pthread_mutex_unlock(&consumer_data->pid_mutex);
2722 goto end;
2723 }
2724
2725 ret = spawn_consumerd(consumer_data);
2726 if (ret < 0) {
2727 ERR("Spawning consumerd failed");
2728 pthread_mutex_unlock(&consumer_data->pid_mutex);
2729 goto error;
2730 }
2731
2732 /* Setting up the consumer_data pid */
2733 consumer_data->pid = ret;
2734 DBG2("Consumer pid %d", consumer_data->pid);
2735 pthread_mutex_unlock(&consumer_data->pid_mutex);
2736
2737 DBG2("Spawning consumer control thread");
2738 ret = spawn_consumer_thread(consumer_data);
2739 if (ret < 0) {
2740 ERR("Fatal error spawning consumer control thread");
2741 goto error;
2742 }
2743
2744end:
2745 return 0;
2746
2747error:
2748 /* Cleanup already created sockets on error. */
2749 if (consumer_data->err_sock >= 0) {
2750 int err;
2751
2752 err = close(consumer_data->err_sock);
2753 if (err < 0) {
2754 PERROR("close consumer data error socket");
2755 }
2756 }
2757 return ret;
2758}
2759
2760/*
2761 * Setup necessary data for kernel tracer action.
2762 */
2763static int init_kernel_tracer(void)
2764{
2765 int ret;
2766
2767 /* Modprobe lttng kernel modules */
2768 ret = modprobe_lttng_control();
2769 if (ret < 0) {
2770 goto error;
2771 }
2772
2773 /* Open debugfs lttng */
2774 kernel_tracer_fd = open(module_proc_lttng, O_RDWR);
2775 if (kernel_tracer_fd < 0) {
2776 DBG("Failed to open %s", module_proc_lttng);
2777 ret = -1;
2778 goto error_open;
2779 }
2780
2781 /* Validate kernel version */
2782 ret = kernel_validate_version(kernel_tracer_fd);
2783 if (ret < 0) {
2784 goto error_version;
2785 }
2786
2787 ret = modprobe_lttng_data();
2788 if (ret < 0) {
2789 goto error_modules;
2790 }
2791
2792 DBG("Kernel tracer fd %d", kernel_tracer_fd);
2793 return 0;
2794
2795error_version:
2796 modprobe_remove_lttng_control();
2797 ret = close(kernel_tracer_fd);
2798 if (ret) {
2799 PERROR("close");
2800 }
2801 kernel_tracer_fd = -1;
2802 return LTTNG_ERR_KERN_VERSION;
2803
2804error_modules:
2805 ret = close(kernel_tracer_fd);
2806 if (ret) {
2807 PERROR("close");
2808 }
2809
2810error_open:
2811 modprobe_remove_lttng_control();
2812
2813error:
2814 WARN("No kernel tracer available");
2815 kernel_tracer_fd = -1;
2816 if (!is_root) {
2817 return LTTNG_ERR_NEED_ROOT_SESSIOND;
2818 } else {
2819 return LTTNG_ERR_KERN_NA;
2820 }
2821}
2822
2823
2824/*
2825 * Copy consumer output from the tracing session to the domain session. The
2826 * function also applies the right modification on a per domain basis for the
2827 * trace files destination directory.
2828 *
2829 * Should *NOT* be called with RCU read-side lock held.
2830 */
2831static int copy_session_consumer(int domain, struct ltt_session *session)
2832{
2833 int ret;
2834 const char *dir_name;
2835 struct consumer_output *consumer;
2836
2837 assert(session);
2838 assert(session->consumer);
2839
2840 switch (domain) {
2841 case LTTNG_DOMAIN_KERNEL:
2842 DBG3("Copying tracing session consumer output in kernel session");
2843 /*
2844 * XXX: We should audit the session creation and what this function
2845 * does "extra" in order to avoid a destroy since this function is used
2846 * in the domain session creation (kernel and ust) only. Same for UST
2847 * domain.
2848 */
2849 if (session->kernel_session->consumer) {
2850 consumer_output_put(session->kernel_session->consumer);
2851 }
2852 session->kernel_session->consumer =
2853 consumer_copy_output(session->consumer);
2854 /* Ease our life a bit for the next part */
2855 consumer = session->kernel_session->consumer;
2856 dir_name = DEFAULT_KERNEL_TRACE_DIR;
2857 break;
2858 case LTTNG_DOMAIN_JUL:
2859 case LTTNG_DOMAIN_LOG4J:
2860 case LTTNG_DOMAIN_PYTHON:
2861 case LTTNG_DOMAIN_UST:
2862 DBG3("Copying tracing session consumer output in UST session");
2863 if (session->ust_session->consumer) {
2864 consumer_output_put(session->ust_session->consumer);
2865 }
2866 session->ust_session->consumer =
2867 consumer_copy_output(session->consumer);
2868 /* Ease our life a bit for the next part */
2869 consumer = session->ust_session->consumer;
2870 dir_name = DEFAULT_UST_TRACE_DIR;
2871 break;
2872 default:
2873 ret = LTTNG_ERR_UNKNOWN_DOMAIN;
2874 goto error;
2875 }
2876
2877 /* Append correct directory to subdir */
2878 strncat(consumer->subdir, dir_name,
2879 sizeof(consumer->subdir) - strlen(consumer->subdir) - 1);
2880 DBG3("Copy session consumer subdir %s", consumer->subdir);
2881
2882 ret = LTTNG_OK;
2883
2884error:
2885 return ret;
2886}
2887
2888/*
2889 * Create an UST session and add it to the session ust list.
2890 *
2891 * Should *NOT* be called with RCU read-side lock held.
2892 */
2893static int create_ust_session(struct ltt_session *session,
2894 struct lttng_domain *domain)
2895{
2896 int ret;
2897 struct ltt_ust_session *lus = NULL;
2898
2899 assert(session);
2900 assert(domain);
2901 assert(session->consumer);
2902
2903 switch (domain->type) {
2904 case LTTNG_DOMAIN_JUL:
2905 case LTTNG_DOMAIN_LOG4J:
2906 case LTTNG_DOMAIN_PYTHON:
2907 case LTTNG_DOMAIN_UST:
2908 break;
2909 default:
2910 ERR("Unknown UST domain on create session %d", domain->type);
2911 ret = LTTNG_ERR_UNKNOWN_DOMAIN;
2912 goto error;
2913 }
2914
2915 DBG("Creating UST session");
2916
2917 lus = trace_ust_create_session(session->id);
2918 if (lus == NULL) {
2919 ret = LTTNG_ERR_UST_SESS_FAIL;
2920 goto error;
2921 }
2922
2923 lus->uid = session->uid;
2924 lus->gid = session->gid;
2925 lus->output_traces = session->output_traces;
2926 lus->snapshot_mode = session->snapshot_mode;
2927 lus->live_timer_interval = session->live_timer;
2928 session->ust_session = lus;
2929 if (session->shm_path[0]) {
2930 strncpy(lus->root_shm_path, session->shm_path,
2931 sizeof(lus->root_shm_path));
2932 lus->root_shm_path[sizeof(lus->root_shm_path) - 1] = '\0';
2933 strncpy(lus->shm_path, session->shm_path,
2934 sizeof(lus->shm_path));
2935 lus->shm_path[sizeof(lus->shm_path) - 1] = '\0';
2936 strncat(lus->shm_path, "/ust",
2937 sizeof(lus->shm_path) - strlen(lus->shm_path) - 1);
2938 }
2939 /* Copy session output to the newly created UST session */
2940 ret = copy_session_consumer(domain->type, session);
2941 if (ret != LTTNG_OK) {
2942 goto error;
2943 }
2944
2945 return LTTNG_OK;
2946
2947error:
2948 free(lus);
2949 session->ust_session = NULL;
2950 return ret;
2951}
2952
2953/*
2954 * Create a kernel tracer session then create the default channel.
2955 */
2956static int create_kernel_session(struct ltt_session *session)
2957{
2958 int ret;
2959
2960 DBG("Creating kernel session");
2961
2962 ret = kernel_create_session(session, kernel_tracer_fd);
2963 if (ret < 0) {
2964 ret = LTTNG_ERR_KERN_SESS_FAIL;
2965 goto error;
2966 }
2967
2968 /* Code flow safety */
2969 assert(session->kernel_session);
2970
2971 /* Copy session output to the newly created Kernel session */
2972 ret = copy_session_consumer(LTTNG_DOMAIN_KERNEL, session);
2973 if (ret != LTTNG_OK) {
2974 goto error;
2975 }
2976
2977 /* Create directory(ies) on local filesystem. */
2978 if (session->kernel_session->consumer->type == CONSUMER_DST_LOCAL &&
2979 strlen(session->kernel_session->consumer->dst.trace_path) > 0) {
2980 ret = run_as_mkdir_recursive(
2981 session->kernel_session->consumer->dst.trace_path,
2982 S_IRWXU | S_IRWXG, session->uid, session->gid);
2983 if (ret < 0) {
2984 if (errno != EEXIST) {
2985 ERR("Trace directory creation error");
2986 goto error;
2987 }
2988 }
2989 }
2990
2991 session->kernel_session->uid = session->uid;
2992 session->kernel_session->gid = session->gid;
2993 session->kernel_session->output_traces = session->output_traces;
2994 session->kernel_session->snapshot_mode = session->snapshot_mode;
2995
2996 return LTTNG_OK;
2997
2998error:
2999 trace_kernel_destroy_session(session->kernel_session);
3000 session->kernel_session = NULL;
3001 return ret;
3002}
3003
3004/*
3005 * Count number of session permitted by uid/gid.
3006 */
3007static unsigned int lttng_sessions_count(uid_t uid, gid_t gid)
3008{
3009 unsigned int i = 0;
3010 struct ltt_session *session;
3011
3012 DBG("Counting number of available session for UID %d GID %d",
3013 uid, gid);
3014 cds_list_for_each_entry(session, &session_list_ptr->head, list) {
3015 /*
3016 * Only list the sessions the user can control.
3017 */
3018 if (!session_access_ok(session, uid, gid)) {
3019 continue;
3020 }
3021 i++;
3022 }
3023 return i;
3024}
3025
3026/*
3027 * Process the command requested by the lttng client within the command
3028 * context structure. This function make sure that the return structure (llm)
3029 * is set and ready for transmission before returning.
3030 *
3031 * Return any error encountered or 0 for success.
3032 *
3033 * "sock" is only used for special-case var. len data.
3034 *
3035 * Should *NOT* be called with RCU read-side lock held.
3036 */
3037static int process_client_msg(struct command_ctx *cmd_ctx, int sock,
3038 int *sock_error)
3039{
3040 int ret = LTTNG_OK;
3041 int need_tracing_session = 1;
3042 int need_domain;
3043
3044 DBG("Processing client command %d", cmd_ctx->lsm->cmd_type);
3045
3046 assert(!rcu_read_ongoing());
3047
3048 *sock_error = 0;
3049
3050 switch (cmd_ctx->lsm->cmd_type) {
3051 case LTTNG_CREATE_SESSION:
3052 case LTTNG_CREATE_SESSION_SNAPSHOT:
3053 case LTTNG_CREATE_SESSION_LIVE:
3054 case LTTNG_DESTROY_SESSION:
3055 case LTTNG_LIST_SESSIONS:
3056 case LTTNG_LIST_DOMAINS:
3057 case LTTNG_START_TRACE:
3058 case LTTNG_STOP_TRACE:
3059 case LTTNG_DATA_PENDING:
3060 case LTTNG_SNAPSHOT_ADD_OUTPUT:
3061 case LTTNG_SNAPSHOT_DEL_OUTPUT:
3062 case LTTNG_SNAPSHOT_LIST_OUTPUT:
3063 case LTTNG_SNAPSHOT_RECORD:
3064 case LTTNG_SAVE_SESSION:
3065 case LTTNG_SET_SESSION_SHM_PATH:
3066 case LTTNG_REGENERATE_METADATA:
3067 case LTTNG_REGENERATE_STATEDUMP:
3068 case LTTNG_REGISTER_TRIGGER:
3069 case LTTNG_UNREGISTER_TRIGGER:
3070 need_domain = 0;
3071 break;
3072 default:
3073 need_domain = 1;
3074 }
3075
3076 if (opt_no_kernel && need_domain
3077 && cmd_ctx->lsm->domain.type == LTTNG_DOMAIN_KERNEL) {
3078 if (!is_root) {
3079 ret = LTTNG_ERR_NEED_ROOT_SESSIOND;
3080 } else {
3081 ret = LTTNG_ERR_KERN_NA;
3082 }
3083 goto error;
3084 }
3085
3086 /* Deny register consumer if we already have a spawned consumer. */
3087 if (cmd_ctx->lsm->cmd_type == LTTNG_REGISTER_CONSUMER) {
3088 pthread_mutex_lock(&kconsumer_data.pid_mutex);
3089 if (kconsumer_data.pid > 0) {
3090 ret = LTTNG_ERR_KERN_CONSUMER_FAIL;
3091 pthread_mutex_unlock(&kconsumer_data.pid_mutex);
3092 goto error;
3093 }
3094 pthread_mutex_unlock(&kconsumer_data.pid_mutex);
3095 }
3096
3097 /*
3098 * Check for command that don't needs to allocate a returned payload. We do
3099 * this here so we don't have to make the call for no payload at each
3100 * command.
3101 */
3102 switch(cmd_ctx->lsm->cmd_type) {
3103 case LTTNG_LIST_SESSIONS:
3104 case LTTNG_LIST_TRACEPOINTS:
3105 case LTTNG_LIST_TRACEPOINT_FIELDS:
3106 case LTTNG_LIST_DOMAINS:
3107 case LTTNG_LIST_CHANNELS:
3108 case LTTNG_LIST_EVENTS:
3109 case LTTNG_LIST_SYSCALLS:
3110 case LTTNG_LIST_TRACKER_PIDS:
3111 case LTTNG_DATA_PENDING:
3112 break;
3113 default:
3114 /* Setup lttng message with no payload */
3115 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, NULL, 0);
3116 if (ret < 0) {
3117 /* This label does not try to unlock the session */
3118 goto init_setup_error;
3119 }
3120 }
3121
3122 /* Commands that DO NOT need a session. */
3123 switch (cmd_ctx->lsm->cmd_type) {
3124 case LTTNG_CREATE_SESSION:
3125 case LTTNG_CREATE_SESSION_SNAPSHOT:
3126 case LTTNG_CREATE_SESSION_LIVE:
3127 case LTTNG_LIST_SESSIONS:
3128 case LTTNG_LIST_TRACEPOINTS:
3129 case LTTNG_LIST_SYSCALLS:
3130 case LTTNG_LIST_TRACEPOINT_FIELDS:
3131 case LTTNG_SAVE_SESSION:
3132 case LTTNG_REGISTER_TRIGGER:
3133 case LTTNG_UNREGISTER_TRIGGER:
3134 need_tracing_session = 0;
3135 break;
3136 default:
3137 DBG("Getting session %s by name", cmd_ctx->lsm->session.name);
3138 /*
3139 * We keep the session list lock across _all_ commands
3140 * for now, because the per-session lock does not
3141 * handle teardown properly.
3142 */
3143 session_lock_list();
3144 cmd_ctx->session = session_find_by_name(cmd_ctx->lsm->session.name);
3145 if (cmd_ctx->session == NULL) {
3146 ret = LTTNG_ERR_SESS_NOT_FOUND;
3147 goto error;
3148 } else {
3149 /* Acquire lock for the session */
3150 session_lock(cmd_ctx->session);
3151 }
3152 break;
3153 }
3154
3155 /*
3156 * Commands that need a valid session but should NOT create one if none
3157 * exists. Instead of creating one and destroying it when the command is
3158 * handled, process that right before so we save some round trip in useless
3159 * code path.
3160 */
3161 switch (cmd_ctx->lsm->cmd_type) {
3162 case LTTNG_DISABLE_CHANNEL:
3163 case LTTNG_DISABLE_EVENT:
3164 switch (cmd_ctx->lsm->domain.type) {
3165 case LTTNG_DOMAIN_KERNEL:
3166 if (!cmd_ctx->session->kernel_session) {
3167 ret = LTTNG_ERR_NO_CHANNEL;
3168 goto error;
3169 }
3170 break;
3171 case LTTNG_DOMAIN_JUL:
3172 case LTTNG_DOMAIN_LOG4J:
3173 case LTTNG_DOMAIN_PYTHON:
3174 case LTTNG_DOMAIN_UST:
3175 if (!cmd_ctx->session->ust_session) {
3176 ret = LTTNG_ERR_NO_CHANNEL;
3177 goto error;
3178 }
3179 break;
3180 default:
3181 ret = LTTNG_ERR_UNKNOWN_DOMAIN;
3182 goto error;
3183 }
3184 default:
3185 break;
3186 }
3187
3188 if (!need_domain) {
3189 goto skip_domain;
3190 }
3191
3192 /*
3193 * Check domain type for specific "pre-action".
3194 */
3195 switch (cmd_ctx->lsm->domain.type) {
3196 case LTTNG_DOMAIN_KERNEL:
3197 if (!is_root) {
3198 ret = LTTNG_ERR_NEED_ROOT_SESSIOND;
3199 goto error;
3200 }
3201
3202 /* Kernel tracer check */
3203 if (kernel_tracer_fd == -1) {
3204 /* Basically, load kernel tracer modules */
3205 ret = init_kernel_tracer();
3206 if (ret != 0) {
3207 goto error;
3208 }
3209 }
3210
3211 /* Consumer is in an ERROR state. Report back to client */
3212 if (uatomic_read(&kernel_consumerd_state) == CONSUMER_ERROR) {
3213 ret = LTTNG_ERR_NO_KERNCONSUMERD;
3214 goto error;
3215 }
3216
3217 /* Need a session for kernel command */
3218 if (need_tracing_session) {
3219 if (cmd_ctx->session->kernel_session == NULL) {
3220 ret = create_kernel_session(cmd_ctx->session);
3221 if (ret < 0) {
3222 ret = LTTNG_ERR_KERN_SESS_FAIL;
3223 goto error;
3224 }
3225 }
3226
3227 /* Start the kernel consumer daemon */
3228 pthread_mutex_lock(&kconsumer_data.pid_mutex);
3229 if (kconsumer_data.pid == 0 &&
3230 cmd_ctx->lsm->cmd_type != LTTNG_REGISTER_CONSUMER) {
3231 pthread_mutex_unlock(&kconsumer_data.pid_mutex);
3232 ret = start_consumerd(&kconsumer_data);
3233 if (ret < 0) {
3234 ret = LTTNG_ERR_KERN_CONSUMER_FAIL;
3235 goto error;
3236 }
3237 uatomic_set(&kernel_consumerd_state, CONSUMER_STARTED);
3238 } else {
3239 pthread_mutex_unlock(&kconsumer_data.pid_mutex);
3240 }
3241
3242 /*
3243 * The consumer was just spawned so we need to add the socket to
3244 * the consumer output of the session if exist.
3245 */
3246 ret = consumer_create_socket(&kconsumer_data,
3247 cmd_ctx->session->kernel_session->consumer);
3248 if (ret < 0) {
3249 goto error;
3250 }
3251 }
3252
3253 break;
3254 case LTTNG_DOMAIN_JUL:
3255 case LTTNG_DOMAIN_LOG4J:
3256 case LTTNG_DOMAIN_PYTHON:
3257 case LTTNG_DOMAIN_UST:
3258 {
3259 if (!ust_app_supported()) {
3260 ret = LTTNG_ERR_NO_UST;
3261 goto error;
3262 }
3263 /* Consumer is in an ERROR state. Report back to client */
3264 if (uatomic_read(&ust_consumerd_state) == CONSUMER_ERROR) {
3265 ret = LTTNG_ERR_NO_USTCONSUMERD;
3266 goto error;
3267 }
3268
3269 if (need_tracing_session) {
3270 /* Create UST session if none exist. */
3271 if (cmd_ctx->session->ust_session == NULL) {
3272 ret = create_ust_session(cmd_ctx->session,
3273 &cmd_ctx->lsm->domain);
3274 if (ret != LTTNG_OK) {
3275 goto error;
3276 }
3277 }
3278
3279 /* Start the UST consumer daemons */
3280 /* 64-bit */
3281 pthread_mutex_lock(&ustconsumer64_data.pid_mutex);
3282 if (consumerd64_bin[0] != '\0' &&
3283 ustconsumer64_data.pid == 0 &&
3284 cmd_ctx->lsm->cmd_type != LTTNG_REGISTER_CONSUMER) {
3285 pthread_mutex_unlock(&ustconsumer64_data.pid_mutex);
3286 ret = start_consumerd(&ustconsumer64_data);
3287 if (ret < 0) {
3288 ret = LTTNG_ERR_UST_CONSUMER64_FAIL;
3289 uatomic_set(&ust_consumerd64_fd, -EINVAL);
3290 goto error;
3291 }
3292
3293 uatomic_set(&ust_consumerd64_fd, ustconsumer64_data.cmd_sock);
3294 uatomic_set(&ust_consumerd_state, CONSUMER_STARTED);
3295 } else {
3296 pthread_mutex_unlock(&ustconsumer64_data.pid_mutex);
3297 }
3298
3299 /*
3300 * Setup socket for consumer 64 bit. No need for atomic access
3301 * since it was set above and can ONLY be set in this thread.
3302 */
3303 ret = consumer_create_socket(&ustconsumer64_data,
3304 cmd_ctx->session->ust_session->consumer);
3305 if (ret < 0) {
3306 goto error;
3307 }
3308
3309 /* 32-bit */
3310 pthread_mutex_lock(&ustconsumer32_data.pid_mutex);
3311 if (consumerd32_bin[0] != '\0' &&
3312 ustconsumer32_data.pid == 0 &&
3313 cmd_ctx->lsm->cmd_type != LTTNG_REGISTER_CONSUMER) {
3314 pthread_mutex_unlock(&ustconsumer32_data.pid_mutex);
3315 ret = start_consumerd(&ustconsumer32_data);
3316 if (ret < 0) {
3317 ret = LTTNG_ERR_UST_CONSUMER32_FAIL;
3318 uatomic_set(&ust_consumerd32_fd, -EINVAL);
3319 goto error;
3320 }
3321
3322 uatomic_set(&ust_consumerd32_fd, ustconsumer32_data.cmd_sock);
3323 uatomic_set(&ust_consumerd_state, CONSUMER_STARTED);
3324 } else {
3325 pthread_mutex_unlock(&ustconsumer32_data.pid_mutex);
3326 }
3327
3328 /*
3329 * Setup socket for consumer 64 bit. No need for atomic access
3330 * since it was set above and can ONLY be set in this thread.
3331 */
3332 ret = consumer_create_socket(&ustconsumer32_data,
3333 cmd_ctx->session->ust_session->consumer);
3334 if (ret < 0) {
3335 goto error;
3336 }
3337 }
3338 break;
3339 }
3340 default:
3341 break;
3342 }
3343skip_domain:
3344
3345 /* Validate consumer daemon state when start/stop trace command */
3346 if (cmd_ctx->lsm->cmd_type == LTTNG_START_TRACE ||
3347 cmd_ctx->lsm->cmd_type == LTTNG_STOP_TRACE) {
3348 switch (cmd_ctx->lsm->domain.type) {
3349 case LTTNG_DOMAIN_NONE:
3350 break;
3351 case LTTNG_DOMAIN_JUL:
3352 case LTTNG_DOMAIN_LOG4J:
3353 case LTTNG_DOMAIN_PYTHON:
3354 case LTTNG_DOMAIN_UST:
3355 if (uatomic_read(&ust_consumerd_state) != CONSUMER_STARTED) {
3356 ret = LTTNG_ERR_NO_USTCONSUMERD;
3357 goto error;
3358 }
3359 break;
3360 case LTTNG_DOMAIN_KERNEL:
3361 if (uatomic_read(&kernel_consumerd_state) != CONSUMER_STARTED) {
3362 ret = LTTNG_ERR_NO_KERNCONSUMERD;
3363 goto error;
3364 }
3365 break;
3366 default:
3367 ret = LTTNG_ERR_UNKNOWN_DOMAIN;
3368 goto error;
3369 }
3370 }
3371
3372 /*
3373 * Check that the UID or GID match that of the tracing session.
3374 * The root user can interact with all sessions.
3375 */
3376 if (need_tracing_session) {
3377 if (!session_access_ok(cmd_ctx->session,
3378 LTTNG_SOCK_GET_UID_CRED(&cmd_ctx->creds),
3379 LTTNG_SOCK_GET_GID_CRED(&cmd_ctx->creds))) {
3380 ret = LTTNG_ERR_EPERM;
3381 goto error;
3382 }
3383 }
3384
3385 /*
3386 * Send relayd information to consumer as soon as we have a domain and a
3387 * session defined.
3388 */
3389 if (cmd_ctx->session && need_domain) {
3390 /*
3391 * Setup relayd if not done yet. If the relayd information was already
3392 * sent to the consumer, this call will gracefully return.
3393 */
3394 ret = cmd_setup_relayd(cmd_ctx->session);
3395 if (ret != LTTNG_OK) {
3396 goto error;
3397 }
3398 }
3399
3400 /* Process by command type */
3401 switch (cmd_ctx->lsm->cmd_type) {
3402 case LTTNG_ADD_CONTEXT:
3403 {
3404 /*
3405 * An LTTNG_ADD_CONTEXT command might have a supplementary
3406 * payload if the context being added is an application context.
3407 */
3408 if (cmd_ctx->lsm->u.context.ctx.ctx ==
3409 LTTNG_EVENT_CONTEXT_APP_CONTEXT) {
3410 char *provider_name = NULL, *context_name = NULL;
3411 size_t provider_name_len =
3412 cmd_ctx->lsm->u.context.provider_name_len;
3413 size_t context_name_len =
3414 cmd_ctx->lsm->u.context.context_name_len;
3415
3416 if (provider_name_len == 0 || context_name_len == 0) {
3417 /*
3418 * Application provider and context names MUST
3419 * be provided.
3420 */
3421 ret = -LTTNG_ERR_INVALID;
3422 goto error;
3423 }
3424
3425 provider_name = zmalloc(provider_name_len + 1);
3426 if (!provider_name) {
3427 ret = -LTTNG_ERR_NOMEM;
3428 goto error;
3429 }
3430 cmd_ctx->lsm->u.context.ctx.u.app_ctx.provider_name =
3431 provider_name;
3432
3433 context_name = zmalloc(context_name_len + 1);
3434 if (!context_name) {
3435 ret = -LTTNG_ERR_NOMEM;
3436 goto error_add_context;
3437 }
3438 cmd_ctx->lsm->u.context.ctx.u.app_ctx.ctx_name =
3439 context_name;
3440
3441 ret = lttcomm_recv_unix_sock(sock, provider_name,
3442 provider_name_len);
3443 if (ret < 0) {
3444 goto error_add_context;
3445 }
3446
3447 ret = lttcomm_recv_unix_sock(sock, context_name,
3448 context_name_len);
3449 if (ret < 0) {
3450 goto error_add_context;
3451 }
3452 }
3453
3454 /*
3455 * cmd_add_context assumes ownership of the provider and context
3456 * names.
3457 */
3458 ret = cmd_add_context(cmd_ctx->session,
3459 cmd_ctx->lsm->domain.type,
3460 cmd_ctx->lsm->u.context.channel_name,
3461 &cmd_ctx->lsm->u.context.ctx,
3462 kernel_poll_pipe[1]);
3463
3464 cmd_ctx->lsm->u.context.ctx.u.app_ctx.provider_name = NULL;
3465 cmd_ctx->lsm->u.context.ctx.u.app_ctx.ctx_name = NULL;
3466error_add_context:
3467 free(cmd_ctx->lsm->u.context.ctx.u.app_ctx.provider_name);
3468 free(cmd_ctx->lsm->u.context.ctx.u.app_ctx.ctx_name);
3469 if (ret < 0) {
3470 goto error;
3471 }
3472 break;
3473 }
3474 case LTTNG_DISABLE_CHANNEL:
3475 {
3476 ret = cmd_disable_channel(cmd_ctx->session, cmd_ctx->lsm->domain.type,
3477 cmd_ctx->lsm->u.disable.channel_name);
3478 break;
3479 }
3480 case LTTNG_DISABLE_EVENT:
3481 {
3482
3483 /*
3484 * FIXME: handle filter; for now we just receive the filter's
3485 * bytecode along with the filter expression which are sent by
3486 * liblttng-ctl and discard them.
3487 *
3488 * This fixes an issue where the client may block while sending
3489 * the filter payload and encounter an error because the session
3490 * daemon closes the socket without ever handling this data.
3491 */
3492 size_t count = cmd_ctx->lsm->u.disable.expression_len +
3493 cmd_ctx->lsm->u.disable.bytecode_len;
3494
3495 if (count) {
3496 char data[LTTNG_FILTER_MAX_LEN];
3497
3498 DBG("Discarding disable event command payload of size %zu", count);
3499 while (count) {
3500 ret = lttcomm_recv_unix_sock(sock, data,
3501 count > sizeof(data) ? sizeof(data) : count);
3502 if (ret < 0) {
3503 goto error;
3504 }
3505
3506 count -= (size_t) ret;
3507 }
3508 }
3509 /* FIXME: passing packed structure to non-packed pointer */
3510 ret = cmd_disable_event(cmd_ctx->session, cmd_ctx->lsm->domain.type,
3511 cmd_ctx->lsm->u.disable.channel_name,
3512 &cmd_ctx->lsm->u.disable.event);
3513 break;
3514 }
3515 case LTTNG_ENABLE_CHANNEL:
3516 {
3517 ret = cmd_enable_channel(cmd_ctx->session, &cmd_ctx->lsm->domain,
3518 &cmd_ctx->lsm->u.channel.chan, kernel_poll_pipe[1]);
3519 break;
3520 }
3521 case LTTNG_TRACK_PID:
3522 {
3523 ret = cmd_track_pid(cmd_ctx->session,
3524 cmd_ctx->lsm->domain.type,
3525 cmd_ctx->lsm->u.pid_tracker.pid);
3526 break;
3527 }
3528 case LTTNG_UNTRACK_PID:
3529 {
3530 ret = cmd_untrack_pid(cmd_ctx->session,
3531 cmd_ctx->lsm->domain.type,
3532 cmd_ctx->lsm->u.pid_tracker.pid);
3533 break;
3534 }
3535 case LTTNG_ENABLE_EVENT:
3536 {
3537 struct lttng_event_exclusion *exclusion = NULL;
3538 struct lttng_filter_bytecode *bytecode = NULL;
3539 char *filter_expression = NULL;
3540
3541 /* Handle exclusion events and receive it from the client. */
3542 if (cmd_ctx->lsm->u.enable.exclusion_count > 0) {
3543 size_t count = cmd_ctx->lsm->u.enable.exclusion_count;
3544
3545 exclusion = zmalloc(sizeof(struct lttng_event_exclusion) +
3546 (count * LTTNG_SYMBOL_NAME_LEN));
3547 if (!exclusion) {
3548 ret = LTTNG_ERR_EXCLUSION_NOMEM;
3549 goto error;
3550 }
3551
3552 DBG("Receiving var len exclusion event list from client ...");
3553 exclusion->count = count;
3554 ret = lttcomm_recv_unix_sock(sock, exclusion->names,
3555 count * LTTNG_SYMBOL_NAME_LEN);
3556 if (ret <= 0) {
3557 DBG("Nothing recv() from client var len data... continuing");
3558 *sock_error = 1;
3559 free(exclusion);
3560 ret = LTTNG_ERR_EXCLUSION_INVAL;
3561 goto error;
3562 }
3563 }
3564
3565 /* Get filter expression from client. */
3566 if (cmd_ctx->lsm->u.enable.expression_len > 0) {
3567 size_t expression_len =
3568 cmd_ctx->lsm->u.enable.expression_len;
3569
3570 if (expression_len > LTTNG_FILTER_MAX_LEN) {
3571 ret = LTTNG_ERR_FILTER_INVAL;
3572 free(exclusion);
3573 goto error;
3574 }
3575
3576 filter_expression = zmalloc(expression_len);
3577 if (!filter_expression) {
3578 free(exclusion);
3579 ret = LTTNG_ERR_FILTER_NOMEM;
3580 goto error;
3581 }
3582
3583 /* Receive var. len. data */
3584 DBG("Receiving var len filter's expression from client ...");
3585 ret = lttcomm_recv_unix_sock(sock, filter_expression,
3586 expression_len);
3587 if (ret <= 0) {
3588 DBG("Nothing recv() from client car len data... continuing");
3589 *sock_error = 1;
3590 free(filter_expression);
3591 free(exclusion);
3592 ret = LTTNG_ERR_FILTER_INVAL;
3593 goto error;
3594 }
3595 }
3596
3597 /* Handle filter and get bytecode from client. */
3598 if (cmd_ctx->lsm->u.enable.bytecode_len > 0) {
3599 size_t bytecode_len = cmd_ctx->lsm->u.enable.bytecode_len;
3600
3601 if (bytecode_len > LTTNG_FILTER_MAX_LEN) {
3602 ret = LTTNG_ERR_FILTER_INVAL;
3603 free(filter_expression);
3604 free(exclusion);
3605 goto error;
3606 }
3607
3608 bytecode = zmalloc(bytecode_len);
3609 if (!bytecode) {
3610 free(filter_expression);
3611 free(exclusion);
3612 ret = LTTNG_ERR_FILTER_NOMEM;
3613 goto error;
3614 }
3615
3616 /* Receive var. len. data */
3617 DBG("Receiving var len filter's bytecode from client ...");
3618 ret = lttcomm_recv_unix_sock(sock, bytecode, bytecode_len);
3619 if (ret <= 0) {
3620 DBG("Nothing recv() from client car len data... continuing");
3621 *sock_error = 1;
3622 free(filter_expression);
3623 free(bytecode);
3624 free(exclusion);
3625 ret = LTTNG_ERR_FILTER_INVAL;
3626 goto error;
3627 }
3628
3629 if ((bytecode->len + sizeof(*bytecode)) != bytecode_len) {
3630 free(filter_expression);
3631 free(bytecode);
3632 free(exclusion);
3633 ret = LTTNG_ERR_FILTER_INVAL;
3634 goto error;
3635 }
3636 }
3637
3638 ret = cmd_enable_event(cmd_ctx->session, &cmd_ctx->lsm->domain,
3639 cmd_ctx->lsm->u.enable.channel_name,
3640 &cmd_ctx->lsm->u.enable.event,
3641 filter_expression, bytecode, exclusion,
3642 kernel_poll_pipe[1]);
3643 break;
3644 }
3645 case LTTNG_LIST_TRACEPOINTS:
3646 {
3647 struct lttng_event *events;
3648 ssize_t nb_events;
3649
3650 session_lock_list();
3651 nb_events = cmd_list_tracepoints(cmd_ctx->lsm->domain.type, &events);
3652 session_unlock_list();
3653 if (nb_events < 0) {
3654 /* Return value is a negative lttng_error_code. */
3655 ret = -nb_events;
3656 goto error;
3657 }
3658
3659 /*
3660 * Setup lttng message with payload size set to the event list size in
3661 * bytes and then copy list into the llm payload.
3662 */
3663 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, events,
3664 sizeof(struct lttng_event) * nb_events);
3665 free(events);
3666
3667 if (ret < 0) {
3668 goto setup_error;
3669 }
3670
3671 ret = LTTNG_OK;
3672 break;
3673 }
3674 case LTTNG_LIST_TRACEPOINT_FIELDS:
3675 {
3676 struct lttng_event_field *fields;
3677 ssize_t nb_fields;
3678
3679 session_lock_list();
3680 nb_fields = cmd_list_tracepoint_fields(cmd_ctx->lsm->domain.type,
3681 &fields);
3682 session_unlock_list();
3683 if (nb_fields < 0) {
3684 /* Return value is a negative lttng_error_code. */
3685 ret = -nb_fields;
3686 goto error;
3687 }
3688
3689 /*
3690 * Setup lttng message with payload size set to the event list size in
3691 * bytes and then copy list into the llm payload.
3692 */
3693 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, fields,
3694 sizeof(struct lttng_event_field) * nb_fields);
3695 free(fields);
3696
3697 if (ret < 0) {
3698 goto setup_error;
3699 }
3700
3701 ret = LTTNG_OK;
3702 break;
3703 }
3704 case LTTNG_LIST_SYSCALLS:
3705 {
3706 struct lttng_event *events;
3707 ssize_t nb_events;
3708
3709 nb_events = cmd_list_syscalls(&events);
3710 if (nb_events < 0) {
3711 /* Return value is a negative lttng_error_code. */
3712 ret = -nb_events;
3713 goto error;
3714 }
3715
3716 /*
3717 * Setup lttng message with payload size set to the event list size in
3718 * bytes and then copy list into the llm payload.
3719 */
3720 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, events,
3721 sizeof(struct lttng_event) * nb_events);
3722 free(events);
3723
3724 if (ret < 0) {
3725 goto setup_error;
3726 }
3727
3728 ret = LTTNG_OK;
3729 break;
3730 }
3731 case LTTNG_LIST_TRACKER_PIDS:
3732 {
3733 int32_t *pids = NULL;
3734 ssize_t nr_pids;
3735
3736 nr_pids = cmd_list_tracker_pids(cmd_ctx->session,
3737 cmd_ctx->lsm->domain.type, &pids);
3738 if (nr_pids < 0) {
3739 /* Return value is a negative lttng_error_code. */
3740 ret = -nr_pids;
3741 goto error;
3742 }
3743
3744 /*
3745 * Setup lttng message with payload size set to the event list size in
3746 * bytes and then copy list into the llm payload.
3747 */
3748 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, pids,
3749 sizeof(int32_t) * nr_pids);
3750 free(pids);
3751
3752 if (ret < 0) {
3753 goto setup_error;
3754 }
3755
3756 ret = LTTNG_OK;
3757 break;
3758 }
3759 case LTTNG_SET_CONSUMER_URI:
3760 {
3761 size_t nb_uri, len;
3762 struct lttng_uri *uris;
3763
3764 nb_uri = cmd_ctx->lsm->u.uri.size;
3765 len = nb_uri * sizeof(struct lttng_uri);
3766
3767 if (nb_uri == 0) {
3768 ret = LTTNG_ERR_INVALID;
3769 goto error;
3770 }
3771
3772 uris = zmalloc(len);
3773 if (uris == NULL) {
3774 ret = LTTNG_ERR_FATAL;
3775 goto error;
3776 }
3777
3778 /* Receive variable len data */
3779 DBG("Receiving %zu URI(s) from client ...", nb_uri);
3780 ret = lttcomm_recv_unix_sock(sock, uris, len);
3781 if (ret <= 0) {
3782 DBG("No URIs received from client... continuing");
3783 *sock_error = 1;
3784 ret = LTTNG_ERR_SESSION_FAIL;
3785 free(uris);
3786 goto error;
3787 }
3788
3789 ret = cmd_set_consumer_uri(cmd_ctx->session, nb_uri, uris);
3790 free(uris);
3791 if (ret != LTTNG_OK) {
3792 goto error;
3793 }
3794
3795
3796 break;
3797 }
3798 case LTTNG_START_TRACE:
3799 {
3800 ret = cmd_start_trace(cmd_ctx->session);
3801 break;
3802 }
3803 case LTTNG_STOP_TRACE:
3804 {
3805 ret = cmd_stop_trace(cmd_ctx->session);
3806 break;
3807 }
3808 case LTTNG_CREATE_SESSION:
3809 {
3810 size_t nb_uri, len;
3811 struct lttng_uri *uris = NULL;
3812
3813 nb_uri = cmd_ctx->lsm->u.uri.size;
3814 len = nb_uri * sizeof(struct lttng_uri);
3815
3816 if (nb_uri > 0) {
3817 uris = zmalloc(len);
3818 if (uris == NULL) {
3819 ret = LTTNG_ERR_FATAL;
3820 goto error;
3821 }
3822
3823 /* Receive variable len data */
3824 DBG("Waiting for %zu URIs from client ...", nb_uri);
3825 ret = lttcomm_recv_unix_sock(sock, uris, len);
3826 if (ret <= 0) {
3827 DBG("No URIs received from client... continuing");
3828 *sock_error = 1;
3829 ret = LTTNG_ERR_SESSION_FAIL;
3830 free(uris);
3831 goto error;
3832 }
3833
3834 if (nb_uri == 1 && uris[0].dtype != LTTNG_DST_PATH) {
3835 DBG("Creating session with ONE network URI is a bad call");
3836 ret = LTTNG_ERR_SESSION_FAIL;
3837 free(uris);
3838 goto error;
3839 }
3840 }
3841
3842 ret = cmd_create_session_uri(cmd_ctx->lsm->session.name, uris, nb_uri,
3843 &cmd_ctx->creds, 0);
3844
3845 free(uris);
3846
3847 break;
3848 }
3849 case LTTNG_DESTROY_SESSION:
3850 {
3851 ret = cmd_destroy_session(cmd_ctx->session, kernel_poll_pipe[1]);
3852
3853 /* Set session to NULL so we do not unlock it after free. */
3854 cmd_ctx->session = NULL;
3855 break;
3856 }
3857 case LTTNG_LIST_DOMAINS:
3858 {
3859 ssize_t nb_dom;
3860 struct lttng_domain *domains = NULL;
3861
3862 nb_dom = cmd_list_domains(cmd_ctx->session, &domains);
3863 if (nb_dom < 0) {
3864 /* Return value is a negative lttng_error_code. */
3865 ret = -nb_dom;
3866 goto error;
3867 }
3868
3869 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, domains,
3870 nb_dom * sizeof(struct lttng_domain));
3871 free(domains);
3872
3873 if (ret < 0) {
3874 goto setup_error;
3875 }
3876
3877 ret = LTTNG_OK;
3878 break;
3879 }
3880 case LTTNG_LIST_CHANNELS:
3881 {
3882 ssize_t payload_size;
3883 struct lttng_channel *channels = NULL;
3884
3885 payload_size = cmd_list_channels(cmd_ctx->lsm->domain.type,
3886 cmd_ctx->session, &channels);
3887 if (payload_size < 0) {
3888 /* Return value is a negative lttng_error_code. */
3889 ret = -payload_size;
3890 goto error;
3891 }
3892
3893 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, channels,
3894 payload_size);
3895 free(channels);
3896
3897 if (ret < 0) {
3898 goto setup_error;
3899 }
3900
3901 ret = LTTNG_OK;
3902 break;
3903 }
3904 case LTTNG_LIST_EVENTS:
3905 {
3906 ssize_t nb_event;
3907 struct lttng_event *events = NULL;
3908 struct lttcomm_event_command_header cmd_header;
3909 size_t total_size;
3910
3911 memset(&cmd_header, 0, sizeof(cmd_header));
3912 /* Extended infos are included at the end of events */
3913 nb_event = cmd_list_events(cmd_ctx->lsm->domain.type,
3914 cmd_ctx->session, cmd_ctx->lsm->u.list.channel_name,
3915 &events, &total_size);
3916
3917 if (nb_event < 0) {
3918 /* Return value is a negative lttng_error_code. */
3919 ret = -nb_event;
3920 goto error;
3921 }
3922
3923 cmd_header.nb_events = nb_event;
3924 ret = setup_lttng_msg(cmd_ctx, events, total_size,
3925 &cmd_header, sizeof(cmd_header));
3926 free(events);
3927
3928 if (ret < 0) {
3929 goto setup_error;
3930 }
3931
3932 ret = LTTNG_OK;
3933 break;
3934 }
3935 case LTTNG_LIST_SESSIONS:
3936 {
3937 unsigned int nr_sessions;
3938 void *sessions_payload;
3939 size_t payload_len;
3940
3941 session_lock_list();
3942 nr_sessions = lttng_sessions_count(
3943 LTTNG_SOCK_GET_UID_CRED(&cmd_ctx->creds),
3944 LTTNG_SOCK_GET_GID_CRED(&cmd_ctx->creds));
3945 payload_len = sizeof(struct lttng_session) * nr_sessions;
3946 sessions_payload = zmalloc(payload_len);
3947
3948 if (!sessions_payload) {
3949 session_unlock_list();
3950 ret = -ENOMEM;
3951 goto setup_error;
3952 }
3953
3954 cmd_list_lttng_sessions(sessions_payload,
3955 LTTNG_SOCK_GET_UID_CRED(&cmd_ctx->creds),
3956 LTTNG_SOCK_GET_GID_CRED(&cmd_ctx->creds));
3957 session_unlock_list();
3958
3959 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, sessions_payload,
3960 payload_len);
3961 free(sessions_payload);
3962
3963 if (ret < 0) {
3964 goto setup_error;
3965 }
3966
3967 ret = LTTNG_OK;
3968 break;
3969 }
3970 case LTTNG_REGISTER_CONSUMER:
3971 {
3972 struct consumer_data *cdata;
3973
3974 switch (cmd_ctx->lsm->domain.type) {
3975 case LTTNG_DOMAIN_KERNEL:
3976 cdata = &kconsumer_data;
3977 break;
3978 default:
3979 ret = LTTNG_ERR_UND;
3980 goto error;
3981 }
3982
3983 ret = cmd_register_consumer(cmd_ctx->session, cmd_ctx->lsm->domain.type,
3984 cmd_ctx->lsm->u.reg.path, cdata);
3985 break;
3986 }
3987 case LTTNG_DATA_PENDING:
3988 {
3989 int pending_ret;
3990 uint8_t pending_ret_byte;
3991
3992 pending_ret = cmd_data_pending(cmd_ctx->session);
3993
3994 /*
3995 * FIXME
3996 *
3997 * This function may returns 0 or 1 to indicate whether or not
3998 * there is data pending. In case of error, it should return an
3999 * LTTNG_ERR code. However, some code paths may still return
4000 * a nondescript error code, which we handle by returning an
4001 * "unknown" error.
4002 */
4003 if (pending_ret == 0 || pending_ret == 1) {
4004 /*
4005 * ret will be set to LTTNG_OK at the end of
4006 * this function.
4007 */
4008 } else if (pending_ret < 0) {
4009 ret = LTTNG_ERR_UNK;
4010 goto setup_error;
4011 } else {
4012 ret = pending_ret;
4013 goto setup_error;
4014 }
4015
4016 pending_ret_byte = (uint8_t) pending_ret;
4017
4018 /* 1 byte to return whether or not data is pending */
4019 ret = setup_lttng_msg_no_cmd_header(cmd_ctx,
4020 &pending_ret_byte, 1);
4021
4022 if (ret < 0) {
4023 goto setup_error;
4024 }
4025
4026 ret = LTTNG_OK;
4027 break;
4028 }
4029 case LTTNG_SNAPSHOT_ADD_OUTPUT:
4030 {
4031 struct lttcomm_lttng_output_id reply;
4032
4033 ret = cmd_snapshot_add_output(cmd_ctx->session,
4034 &cmd_ctx->lsm->u.snapshot_output.output, &reply.id);
4035 if (ret != LTTNG_OK) {
4036 goto error;
4037 }
4038
4039 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, &reply,
4040 sizeof(reply));
4041 if (ret < 0) {
4042 goto setup_error;
4043 }
4044
4045 /* Copy output list into message payload */
4046 ret = LTTNG_OK;
4047 break;
4048 }
4049 case LTTNG_SNAPSHOT_DEL_OUTPUT:
4050 {
4051 ret = cmd_snapshot_del_output(cmd_ctx->session,
4052 &cmd_ctx->lsm->u.snapshot_output.output);
4053 break;
4054 }
4055 case LTTNG_SNAPSHOT_LIST_OUTPUT:
4056 {
4057 ssize_t nb_output;
4058 struct lttng_snapshot_output *outputs = NULL;
4059
4060 nb_output = cmd_snapshot_list_outputs(cmd_ctx->session, &outputs);
4061 if (nb_output < 0) {
4062 ret = -nb_output;
4063 goto error;
4064 }
4065
4066 assert((nb_output > 0 && outputs) || nb_output == 0);
4067 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, outputs,
4068 nb_output * sizeof(struct lttng_snapshot_output));
4069 free(outputs);
4070
4071 if (ret < 0) {
4072 goto setup_error;
4073 }
4074
4075 ret = LTTNG_OK;
4076 break;
4077 }
4078 case LTTNG_SNAPSHOT_RECORD:
4079 {
4080 ret = cmd_snapshot_record(cmd_ctx->session,
4081 &cmd_ctx->lsm->u.snapshot_record.output,
4082 cmd_ctx->lsm->u.snapshot_record.wait);
4083 break;
4084 }
4085 case LTTNG_CREATE_SESSION_SNAPSHOT:
4086 {
4087 size_t nb_uri, len;
4088 struct lttng_uri *uris = NULL;
4089
4090 nb_uri = cmd_ctx->lsm->u.uri.size;
4091 len = nb_uri * sizeof(struct lttng_uri);
4092
4093 if (nb_uri > 0) {
4094 uris = zmalloc(len);
4095 if (uris == NULL) {
4096 ret = LTTNG_ERR_FATAL;
4097 goto error;
4098 }
4099
4100 /* Receive variable len data */
4101 DBG("Waiting for %zu URIs from client ...", nb_uri);
4102 ret = lttcomm_recv_unix_sock(sock, uris, len);
4103 if (ret <= 0) {
4104 DBG("No URIs received from client... continuing");
4105 *sock_error = 1;
4106 ret = LTTNG_ERR_SESSION_FAIL;
4107 free(uris);
4108 goto error;
4109 }
4110
4111 if (nb_uri == 1 && uris[0].dtype != LTTNG_DST_PATH) {
4112 DBG("Creating session with ONE network URI is a bad call");
4113 ret = LTTNG_ERR_SESSION_FAIL;
4114 free(uris);
4115 goto error;
4116 }
4117 }
4118
4119 ret = cmd_create_session_snapshot(cmd_ctx->lsm->session.name, uris,
4120 nb_uri, &cmd_ctx->creds);
4121 free(uris);
4122 break;
4123 }
4124 case LTTNG_CREATE_SESSION_LIVE:
4125 {
4126 size_t nb_uri, len;
4127 struct lttng_uri *uris = NULL;
4128
4129 nb_uri = cmd_ctx->lsm->u.uri.size;
4130 len = nb_uri * sizeof(struct lttng_uri);
4131
4132 if (nb_uri > 0) {
4133 uris = zmalloc(len);
4134 if (uris == NULL) {
4135 ret = LTTNG_ERR_FATAL;
4136 goto error;
4137 }
4138
4139 /* Receive variable len data */
4140 DBG("Waiting for %zu URIs from client ...", nb_uri);
4141 ret = lttcomm_recv_unix_sock(sock, uris, len);
4142 if (ret <= 0) {
4143 DBG("No URIs received from client... continuing");
4144 *sock_error = 1;
4145 ret = LTTNG_ERR_SESSION_FAIL;
4146 free(uris);
4147 goto error;
4148 }
4149
4150 if (nb_uri == 1 && uris[0].dtype != LTTNG_DST_PATH) {
4151 DBG("Creating session with ONE network URI is a bad call");
4152 ret = LTTNG_ERR_SESSION_FAIL;
4153 free(uris);
4154 goto error;
4155 }
4156 }
4157
4158 ret = cmd_create_session_uri(cmd_ctx->lsm->session.name, uris,
4159 nb_uri, &cmd_ctx->creds, cmd_ctx->lsm->u.session_live.timer_interval);
4160 free(uris);
4161 break;
4162 }
4163 case LTTNG_SAVE_SESSION:
4164 {
4165 ret = cmd_save_sessions(&cmd_ctx->lsm->u.save_session.attr,
4166 &cmd_ctx->creds);
4167 break;
4168 }
4169 case LTTNG_SET_SESSION_SHM_PATH:
4170 {
4171 ret = cmd_set_session_shm_path(cmd_ctx->session,
4172 cmd_ctx->lsm->u.set_shm_path.shm_path);
4173 break;
4174 }
4175 case LTTNG_REGENERATE_METADATA:
4176 {
4177 ret = cmd_regenerate_metadata(cmd_ctx->session);
4178 break;
4179 }
4180 case LTTNG_REGENERATE_STATEDUMP:
4181 {
4182 ret = cmd_regenerate_statedump(cmd_ctx->session);
4183 break;
4184 }
4185 case LTTNG_REGISTER_TRIGGER:
4186 {
4187 ret = cmd_register_trigger(cmd_ctx, sock,
4188 notification_thread_handle);
4189 break;
4190 }
4191 case LTTNG_UNREGISTER_TRIGGER:
4192 {
4193 ret = cmd_unregister_trigger(cmd_ctx, sock,
4194 notification_thread_handle);
4195 break;
4196 }
4197 default:
4198 ret = LTTNG_ERR_UND;
4199 break;
4200 }
4201
4202error:
4203 if (cmd_ctx->llm == NULL) {
4204 DBG("Missing llm structure. Allocating one.");
4205 if (setup_lttng_msg_no_cmd_header(cmd_ctx, NULL, 0) < 0) {
4206 goto setup_error;
4207 }
4208 }
4209 /* Set return code */
4210 cmd_ctx->llm->ret_code = ret;
4211setup_error:
4212 if (cmd_ctx->session) {
4213 session_unlock(cmd_ctx->session);
4214 }
4215 if (need_tracing_session) {
4216 session_unlock_list();
4217 }
4218init_setup_error:
4219 assert(!rcu_read_ongoing());
4220 return ret;
4221}
4222
4223/*
4224 * Thread managing health check socket.
4225 */
4226static void *thread_manage_health(void *data)
4227{
4228 int sock = -1, new_sock = -1, ret, i, pollfd, err = -1;
4229 uint32_t revents, nb_fd;
4230 struct lttng_poll_event events;
4231 struct health_comm_msg msg;
4232 struct health_comm_reply reply;
4233
4234 DBG("[thread] Manage health check started");
4235
4236 rcu_register_thread();
4237
4238 /* We might hit an error path before this is created. */
4239 lttng_poll_init(&events);
4240
4241 /* Create unix socket */
4242 sock = lttcomm_create_unix_sock(health_unix_sock_path);
4243 if (sock < 0) {
4244 ERR("Unable to create health check Unix socket");
4245 goto error;
4246 }
4247
4248 if (is_root) {
4249 /* lttng health client socket path permissions */
4250 ret = chown(health_unix_sock_path, 0,
4251 utils_get_group_id(tracing_group_name));
4252 if (ret < 0) {
4253 ERR("Unable to set group on %s", health_unix_sock_path);
4254 PERROR("chown");
4255 goto error;
4256 }
4257
4258 ret = chmod(health_unix_sock_path,
4259 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
4260 if (ret < 0) {
4261 ERR("Unable to set permissions on %s", health_unix_sock_path);
4262 PERROR("chmod");
4263 goto error;
4264 }
4265 }
4266
4267 /*
4268 * Set the CLOEXEC flag. Return code is useless because either way, the
4269 * show must go on.
4270 */
4271 (void) utils_set_fd_cloexec(sock);
4272
4273 ret = lttcomm_listen_unix_sock(sock);
4274 if (ret < 0) {
4275 goto error;
4276 }
4277
4278 /*
4279 * Pass 2 as size here for the thread quit pipe and client_sock. Nothing
4280 * more will be added to this poll set.
4281 */
4282 ret = sessiond_set_thread_pollset(&events, 2);
4283 if (ret < 0) {
4284 goto error;
4285 }
4286
4287 /* Add the application registration socket */
4288 ret = lttng_poll_add(&events, sock, LPOLLIN | LPOLLPRI);
4289 if (ret < 0) {
4290 goto error;
4291 }
4292
4293 sessiond_notify_ready();
4294
4295 while (1) {
4296 DBG("Health check ready");
4297
4298 /* Inifinite blocking call, waiting for transmission */
4299restart:
4300 ret = lttng_poll_wait(&events, -1);
4301 if (ret < 0) {
4302 /*
4303 * Restart interrupted system call.
4304 */
4305 if (errno == EINTR) {
4306 goto restart;
4307 }
4308 goto error;
4309 }
4310
4311 nb_fd = ret;
4312
4313 for (i = 0; i < nb_fd; i++) {
4314 /* Fetch once the poll data */
4315 revents = LTTNG_POLL_GETEV(&events, i);
4316 pollfd = LTTNG_POLL_GETFD(&events, i);
4317
4318 if (!revents) {
4319 /* No activity for this FD (poll implementation). */
4320 continue;
4321 }
4322
4323 /* Thread quit pipe has been closed. Killing thread. */
4324 ret = sessiond_check_thread_quit_pipe(pollfd, revents);
4325 if (ret) {
4326 err = 0;
4327 goto exit;
4328 }
4329
4330 /* Event on the registration socket */
4331 if (pollfd == sock) {
4332 if (revents & LPOLLIN) {
4333 continue;
4334 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
4335 ERR("Health socket poll error");
4336 goto error;
4337 } else {
4338 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
4339 goto error;
4340 }
4341 }
4342 }
4343
4344 new_sock = lttcomm_accept_unix_sock(sock);
4345 if (new_sock < 0) {
4346 goto error;
4347 }
4348
4349 /*
4350 * Set the CLOEXEC flag. Return code is useless because either way, the
4351 * show must go on.
4352 */
4353 (void) utils_set_fd_cloexec(new_sock);
4354
4355 DBG("Receiving data from client for health...");
4356 ret = lttcomm_recv_unix_sock(new_sock, (void *)&msg, sizeof(msg));
4357 if (ret <= 0) {
4358 DBG("Nothing recv() from client... continuing");
4359 ret = close(new_sock);
4360 if (ret) {
4361 PERROR("close");
4362 }
4363 continue;
4364 }
4365
4366 rcu_thread_online();
4367
4368 memset(&reply, 0, sizeof(reply));
4369 for (i = 0; i < NR_HEALTH_SESSIOND_TYPES; i++) {
4370 /*
4371 * health_check_state returns 0 if health is
4372 * bad.
4373 */
4374 if (!health_check_state(health_sessiond, i)) {
4375 reply.ret_code |= 1ULL << i;
4376 }
4377 }
4378
4379 DBG2("Health check return value %" PRIx64, reply.ret_code);
4380
4381 ret = send_unix_sock(new_sock, (void *) &reply, sizeof(reply));
4382 if (ret < 0) {
4383 ERR("Failed to send health data back to client");
4384 }
4385
4386 /* End of transmission */
4387 ret = close(new_sock);
4388 if (ret) {
4389 PERROR("close");
4390 }
4391 }
4392
4393exit:
4394error:
4395 if (err) {
4396 ERR("Health error occurred in %s", __func__);
4397 }
4398 DBG("Health check thread dying");
4399 unlink(health_unix_sock_path);
4400 if (sock >= 0) {
4401 ret = close(sock);
4402 if (ret) {
4403 PERROR("close");
4404 }
4405 }
4406
4407 lttng_poll_clean(&events);
4408 stop_threads();
4409 rcu_unregister_thread();
4410 return NULL;
4411}
4412
4413/*
4414 * This thread manage all clients request using the unix client socket for
4415 * communication.
4416 */
4417static void *thread_manage_clients(void *data)
4418{
4419 int sock = -1, ret, i, pollfd, err = -1;
4420 int sock_error;
4421 uint32_t revents, nb_fd;
4422 struct command_ctx *cmd_ctx = NULL;
4423 struct lttng_poll_event events;
4424
4425 DBG("[thread] Manage client started");
4426
4427 rcu_register_thread();
4428
4429 health_register(health_sessiond, HEALTH_SESSIOND_TYPE_CMD);
4430
4431 health_code_update();
4432
4433 ret = lttcomm_listen_unix_sock(client_sock);
4434 if (ret < 0) {
4435 goto error_listen;
4436 }
4437
4438 /*
4439 * Pass 2 as size here for the thread quit pipe and client_sock. Nothing
4440 * more will be added to this poll set.
4441 */
4442 ret = sessiond_set_thread_pollset(&events, 2);
4443 if (ret < 0) {
4444 goto error_create_poll;
4445 }
4446
4447 /* Add the application registration socket */
4448 ret = lttng_poll_add(&events, client_sock, LPOLLIN | LPOLLPRI);
4449 if (ret < 0) {
4450 goto error;
4451 }
4452
4453 sessiond_notify_ready();
4454 ret = sem_post(&load_info->message_thread_ready);
4455 if (ret) {
4456 PERROR("sem_post message_thread_ready");
4457 goto error;
4458 }
4459
4460 /* This testpoint is after we signal readiness to the parent. */
4461 if (testpoint(sessiond_thread_manage_clients)) {
4462 goto error;
4463 }
4464
4465 if (testpoint(sessiond_thread_manage_clients_before_loop)) {
4466 goto error;
4467 }
4468
4469 health_code_update();
4470
4471 while (1) {
4472 DBG("Accepting client command ...");
4473
4474 /* Inifinite blocking call, waiting for transmission */
4475 restart:
4476 health_poll_entry();
4477 ret = lttng_poll_wait(&events, -1);
4478 health_poll_exit();
4479 if (ret < 0) {
4480 /*
4481 * Restart interrupted system call.
4482 */
4483 if (errno == EINTR) {
4484 goto restart;
4485 }
4486 goto error;
4487 }
4488
4489 nb_fd = ret;
4490
4491 for (i = 0; i < nb_fd; i++) {
4492 /* Fetch once the poll data */
4493 revents = LTTNG_POLL_GETEV(&events, i);
4494 pollfd = LTTNG_POLL_GETFD(&events, i);
4495
4496 health_code_update();
4497
4498 if (!revents) {
4499 /* No activity for this FD (poll implementation). */
4500 continue;
4501 }
4502
4503 /* Thread quit pipe has been closed. Killing thread. */
4504 ret = sessiond_check_thread_quit_pipe(pollfd, revents);
4505 if (ret) {
4506 err = 0;
4507 goto exit;
4508 }
4509
4510 /* Event on the registration socket */
4511 if (pollfd == client_sock) {
4512 if (revents & LPOLLIN) {
4513 continue;
4514 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
4515 ERR("Client socket poll error");
4516 goto error;
4517 } else {
4518 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
4519 goto error;
4520 }
4521 }
4522 }
4523
4524 DBG("Wait for client response");
4525
4526 health_code_update();
4527
4528 sock = lttcomm_accept_unix_sock(client_sock);
4529 if (sock < 0) {
4530 goto error;
4531 }
4532
4533 /*
4534 * Set the CLOEXEC flag. Return code is useless because either way, the
4535 * show must go on.
4536 */
4537 (void) utils_set_fd_cloexec(sock);
4538
4539 /* Set socket option for credentials retrieval */
4540 ret = lttcomm_setsockopt_creds_unix_sock(sock);
4541 if (ret < 0) {
4542 goto error;
4543 }
4544
4545 /* Allocate context command to process the client request */
4546 cmd_ctx = zmalloc(sizeof(struct command_ctx));
4547 if (cmd_ctx == NULL) {
4548 PERROR("zmalloc cmd_ctx");
4549 goto error;
4550 }
4551
4552 /* Allocate data buffer for reception */
4553 cmd_ctx->lsm = zmalloc(sizeof(struct lttcomm_session_msg));
4554 if (cmd_ctx->lsm == NULL) {
4555 PERROR("zmalloc cmd_ctx->lsm");
4556 goto error;
4557 }
4558
4559 cmd_ctx->llm = NULL;
4560 cmd_ctx->session = NULL;
4561
4562 health_code_update();
4563
4564 /*
4565 * Data is received from the lttng client. The struct
4566 * lttcomm_session_msg (lsm) contains the command and data request of
4567 * the client.
4568 */
4569 DBG("Receiving data from client ...");
4570 ret = lttcomm_recv_creds_unix_sock(sock, cmd_ctx->lsm,
4571 sizeof(struct lttcomm_session_msg), &cmd_ctx->creds);
4572 if (ret <= 0) {
4573 DBG("Nothing recv() from client... continuing");
4574 ret = close(sock);
4575 if (ret) {
4576 PERROR("close");
4577 }
4578 sock = -1;
4579 clean_command_ctx(&cmd_ctx);
4580 continue;
4581 }
4582
4583 health_code_update();
4584
4585 // TODO: Validate cmd_ctx including sanity check for
4586 // security purpose.
4587
4588 rcu_thread_online();
4589 /*
4590 * This function dispatch the work to the kernel or userspace tracer
4591 * libs and fill the lttcomm_lttng_msg data structure of all the needed
4592 * informations for the client. The command context struct contains
4593 * everything this function may needs.
4594 */
4595 ret = process_client_msg(cmd_ctx, sock, &sock_error);
4596 rcu_thread_offline();
4597 if (ret < 0) {
4598 ret = close(sock);
4599 if (ret) {
4600 PERROR("close");
4601 }
4602 sock = -1;
4603 /*
4604 * TODO: Inform client somehow of the fatal error. At
4605 * this point, ret < 0 means that a zmalloc failed
4606 * (ENOMEM). Error detected but still accept
4607 * command, unless a socket error has been
4608 * detected.
4609 */
4610 clean_command_ctx(&cmd_ctx);
4611 continue;
4612 }
4613
4614 health_code_update();
4615
4616 DBG("Sending response (size: %d, retcode: %s (%d))",
4617 cmd_ctx->lttng_msg_size,
4618 lttng_strerror(-cmd_ctx->llm->ret_code),
4619 cmd_ctx->llm->ret_code);
4620 ret = send_unix_sock(sock, cmd_ctx->llm, cmd_ctx->lttng_msg_size);
4621 if (ret < 0) {
4622 ERR("Failed to send data back to client");
4623 }
4624
4625 /* End of transmission */
4626 ret = close(sock);
4627 if (ret) {
4628 PERROR("close");
4629 }
4630 sock = -1;
4631
4632 clean_command_ctx(&cmd_ctx);
4633
4634 health_code_update();
4635 }
4636
4637exit:
4638error:
4639 if (sock >= 0) {
4640 ret = close(sock);
4641 if (ret) {
4642 PERROR("close");
4643 }
4644 }
4645
4646 lttng_poll_clean(&events);
4647 clean_command_ctx(&cmd_ctx);
4648
4649error_listen:
4650error_create_poll:
4651 unlink(client_unix_sock_path);
4652 if (client_sock >= 0) {
4653 ret = close(client_sock);
4654 if (ret) {
4655 PERROR("close");
4656 }
4657 }
4658
4659 if (err) {
4660 health_error();
4661 ERR("Health error occurred in %s", __func__);
4662 }
4663
4664 health_unregister(health_sessiond);
4665
4666 DBG("Client thread dying");
4667
4668 rcu_unregister_thread();
4669
4670 /*
4671 * Since we are creating the consumer threads, we own them, so we need
4672 * to join them before our thread exits.
4673 */
4674 ret = join_consumer_thread(&kconsumer_data);
4675 if (ret) {
4676 errno = ret;
4677 PERROR("join_consumer");
4678 }
4679
4680 ret = join_consumer_thread(&ustconsumer32_data);
4681 if (ret) {
4682 errno = ret;
4683 PERROR("join_consumer ust32");
4684 }
4685
4686 ret = join_consumer_thread(&ustconsumer64_data);
4687 if (ret) {
4688 errno = ret;
4689 PERROR("join_consumer ust64");
4690 }
4691 return NULL;
4692}
4693
4694static int string_match(const char *str1, const char *str2)
4695{
4696 return (str1 && str2) && !strcmp(str1, str2);
4697}
4698
4699/*
4700 * Take an option from the getopt output and set it in the right variable to be
4701 * used later.
4702 *
4703 * Return 0 on success else a negative value.
4704 */
4705static int set_option(int opt, const char *arg, const char *optname)
4706{
4707 int ret = 0;
4708
4709 if (string_match(optname, "client-sock") || opt == 'c') {
4710 if (!arg || *arg == '\0') {
4711 ret = -EINVAL;
4712 goto end;
4713 }
4714 if (lttng_is_setuid_setgid()) {
4715 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4716 "-c, --client-sock");
4717 } else {
4718 snprintf(client_unix_sock_path, PATH_MAX, "%s", arg);
4719 }
4720 } else if (string_match(optname, "apps-sock") || opt == 'a') {
4721 if (!arg || *arg == '\0') {
4722 ret = -EINVAL;
4723 goto end;
4724 }
4725 if (lttng_is_setuid_setgid()) {
4726 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4727 "-a, --apps-sock");
4728 } else {
4729 snprintf(apps_unix_sock_path, PATH_MAX, "%s", arg);
4730 }
4731 } else if (string_match(optname, "daemonize") || opt == 'd') {
4732 opt_daemon = 1;
4733 } else if (string_match(optname, "background") || opt == 'b') {
4734 opt_background = 1;
4735 } else if (string_match(optname, "group") || opt == 'g') {
4736 if (!arg || *arg == '\0') {
4737 ret = -EINVAL;
4738 goto end;
4739 }
4740 if (lttng_is_setuid_setgid()) {
4741 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4742 "-g, --group");
4743 } else {
4744 /*
4745 * If the override option is set, the pointer points to a
4746 * *non* const thus freeing it even though the variable type is
4747 * set to const.
4748 */
4749 if (tracing_group_name_override) {
4750 free((void *) tracing_group_name);
4751 }
4752 tracing_group_name = strdup(arg);
4753 if (!tracing_group_name) {
4754 PERROR("strdup");
4755 ret = -ENOMEM;
4756 }
4757 tracing_group_name_override = 1;
4758 }
4759 } else if (string_match(optname, "help") || opt == 'h') {
4760 ret = utils_show_man_page(8, "lttng-sessiond");
4761 if (ret) {
4762 ERR("Cannot view man page lttng-sessiond(8)");
4763 perror("exec");
4764 }
4765 exit(ret ? EXIT_FAILURE : EXIT_SUCCESS);
4766 } else if (string_match(optname, "version") || opt == 'V') {
4767 fprintf(stdout, "%s\n", VERSION);
4768 exit(EXIT_SUCCESS);
4769 } else if (string_match(optname, "sig-parent") || opt == 'S') {
4770 opt_sig_parent = 1;
4771 } else if (string_match(optname, "kconsumerd-err-sock")) {
4772 if (!arg || *arg == '\0') {
4773 ret = -EINVAL;
4774 goto end;
4775 }
4776 if (lttng_is_setuid_setgid()) {
4777 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4778 "--kconsumerd-err-sock");
4779 } else {
4780 snprintf(kconsumer_data.err_unix_sock_path, PATH_MAX, "%s", arg);
4781 }
4782 } else if (string_match(optname, "kconsumerd-cmd-sock")) {
4783 if (!arg || *arg == '\0') {
4784 ret = -EINVAL;
4785 goto end;
4786 }
4787 if (lttng_is_setuid_setgid()) {
4788 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4789 "--kconsumerd-cmd-sock");
4790 } else {
4791 snprintf(kconsumer_data.cmd_unix_sock_path, PATH_MAX, "%s", arg);
4792 }
4793 } else if (string_match(optname, "ustconsumerd64-err-sock")) {
4794 if (!arg || *arg == '\0') {
4795 ret = -EINVAL;
4796 goto end;
4797 }
4798 if (lttng_is_setuid_setgid()) {
4799 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4800 "--ustconsumerd64-err-sock");
4801 } else {
4802 snprintf(ustconsumer64_data.err_unix_sock_path, PATH_MAX, "%s", arg);
4803 }
4804 } else if (string_match(optname, "ustconsumerd64-cmd-sock")) {
4805 if (!arg || *arg == '\0') {
4806 ret = -EINVAL;
4807 goto end;
4808 }
4809 if (lttng_is_setuid_setgid()) {
4810 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4811 "--ustconsumerd64-cmd-sock");
4812 } else {
4813 snprintf(ustconsumer64_data.cmd_unix_sock_path, PATH_MAX, "%s", arg);
4814 }
4815 } else if (string_match(optname, "ustconsumerd32-err-sock")) {
4816 if (!arg || *arg == '\0') {
4817 ret = -EINVAL;
4818 goto end;
4819 }
4820 if (lttng_is_setuid_setgid()) {
4821 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4822 "--ustconsumerd32-err-sock");
4823 } else {
4824 snprintf(ustconsumer32_data.err_unix_sock_path, PATH_MAX, "%s", arg);
4825 }
4826 } else if (string_match(optname, "ustconsumerd32-cmd-sock")) {
4827 if (!arg || *arg == '\0') {
4828 ret = -EINVAL;
4829 goto end;
4830 }
4831 if (lttng_is_setuid_setgid()) {
4832 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4833 "--ustconsumerd32-cmd-sock");
4834 } else {
4835 snprintf(ustconsumer32_data.cmd_unix_sock_path, PATH_MAX, "%s", arg);
4836 }
4837 } else if (string_match(optname, "no-kernel")) {
4838 opt_no_kernel = 1;
4839 } else if (string_match(optname, "quiet") || opt == 'q') {
4840 lttng_opt_quiet = 1;
4841 } else if (string_match(optname, "verbose") || opt == 'v') {
4842 /* Verbose level can increase using multiple -v */
4843 if (arg) {
4844 /* Value obtained from config file */
4845 lttng_opt_verbose = config_parse_value(arg);
4846 } else {
4847 /* -v used on command line */
4848 lttng_opt_verbose++;
4849 }
4850 /* Clamp value to [0, 3] */
4851 lttng_opt_verbose = lttng_opt_verbose < 0 ? 0 :
4852 (lttng_opt_verbose <= 3 ? lttng_opt_verbose : 3);
4853 } else if (string_match(optname, "verbose-consumer")) {
4854 if (arg) {
4855 opt_verbose_consumer = config_parse_value(arg);
4856 } else {
4857 opt_verbose_consumer++;
4858 }
4859 } else if (string_match(optname, "consumerd32-path")) {
4860 if (!arg || *arg == '\0') {
4861 ret = -EINVAL;
4862 goto end;
4863 }
4864 if (lttng_is_setuid_setgid()) {
4865 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4866 "--consumerd32-path");
4867 } else {
4868 if (consumerd32_bin_override) {
4869 free((void *) consumerd32_bin);
4870 }
4871 consumerd32_bin = strdup(arg);
4872 if (!consumerd32_bin) {
4873 PERROR("strdup");
4874 ret = -ENOMEM;
4875 }
4876 consumerd32_bin_override = 1;
4877 }
4878 } else if (string_match(optname, "consumerd32-libdir")) {
4879 if (!arg || *arg == '\0') {
4880 ret = -EINVAL;
4881 goto end;
4882 }
4883 if (lttng_is_setuid_setgid()) {
4884 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4885 "--consumerd32-libdir");
4886 } else {
4887 if (consumerd32_libdir_override) {
4888 free((void *) consumerd32_libdir);
4889 }
4890 consumerd32_libdir = strdup(arg);
4891 if (!consumerd32_libdir) {
4892 PERROR("strdup");
4893 ret = -ENOMEM;
4894 }
4895 consumerd32_libdir_override = 1;
4896 }
4897 } else if (string_match(optname, "consumerd64-path")) {
4898 if (!arg || *arg == '\0') {
4899 ret = -EINVAL;
4900 goto end;
4901 }
4902 if (lttng_is_setuid_setgid()) {
4903 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4904 "--consumerd64-path");
4905 } else {
4906 if (consumerd64_bin_override) {
4907 free((void *) consumerd64_bin);
4908 }
4909 consumerd64_bin = strdup(arg);
4910 if (!consumerd64_bin) {
4911 PERROR("strdup");
4912 ret = -ENOMEM;
4913 }
4914 consumerd64_bin_override = 1;
4915 }
4916 } else if (string_match(optname, "consumerd64-libdir")) {
4917 if (!arg || *arg == '\0') {
4918 ret = -EINVAL;
4919 goto end;
4920 }
4921 if (lttng_is_setuid_setgid()) {
4922 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4923 "--consumerd64-libdir");
4924 } else {
4925 if (consumerd64_libdir_override) {
4926 free((void *) consumerd64_libdir);
4927 }
4928 consumerd64_libdir = strdup(arg);
4929 if (!consumerd64_libdir) {
4930 PERROR("strdup");
4931 ret = -ENOMEM;
4932 }
4933 consumerd64_libdir_override = 1;
4934 }
4935 } else if (string_match(optname, "pidfile") || opt == 'p') {
4936 if (!arg || *arg == '\0') {
4937 ret = -EINVAL;
4938 goto end;
4939 }
4940 if (lttng_is_setuid_setgid()) {
4941 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4942 "-p, --pidfile");
4943 } else {
4944 free(opt_pidfile);
4945 opt_pidfile = strdup(arg);
4946 if (!opt_pidfile) {
4947 PERROR("strdup");
4948 ret = -ENOMEM;
4949 }
4950 }
4951 } else if (string_match(optname, "agent-tcp-port")) {
4952 if (!arg || *arg == '\0') {
4953 ret = -EINVAL;
4954 goto end;
4955 }
4956 if (lttng_is_setuid_setgid()) {
4957 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4958 "--agent-tcp-port");
4959 } else {
4960 unsigned long v;
4961
4962 errno = 0;
4963 v = strtoul(arg, NULL, 0);
4964 if (errno != 0 || !isdigit(arg[0])) {
4965 ERR("Wrong value in --agent-tcp-port parameter: %s", arg);
4966 return -1;
4967 }
4968 if (v == 0 || v >= 65535) {
4969 ERR("Port overflow in --agent-tcp-port parameter: %s", arg);
4970 return -1;
4971 }
4972 agent_tcp_port = (uint32_t) v;
4973 DBG3("Agent TCP port set to non default: %u", agent_tcp_port);
4974 }
4975 } else if (string_match(optname, "load") || opt == 'l') {
4976 if (!arg || *arg == '\0') {
4977 ret = -EINVAL;
4978 goto end;
4979 }
4980 if (lttng_is_setuid_setgid()) {
4981 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4982 "-l, --load");
4983 } else {
4984 free(opt_load_session_path);
4985 opt_load_session_path = strdup(arg);
4986 if (!opt_load_session_path) {
4987 PERROR("strdup");
4988 ret = -ENOMEM;
4989 }
4990 }
4991 } else if (string_match(optname, "kmod-probes")) {
4992 if (!arg || *arg == '\0') {
4993 ret = -EINVAL;
4994 goto end;
4995 }
4996 if (lttng_is_setuid_setgid()) {
4997 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4998 "--kmod-probes");
4999 } else {
5000 free(kmod_probes_list);
5001 kmod_probes_list = strdup(arg);
5002 if (!kmod_probes_list) {
5003 PERROR("strdup");
5004 ret = -ENOMEM;
5005 }
5006 }
5007 } else if (string_match(optname, "extra-kmod-probes")) {
5008 if (!arg || *arg == '\0') {
5009 ret = -EINVAL;
5010 goto end;
5011 }
5012 if (lttng_is_setuid_setgid()) {
5013 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
5014 "--extra-kmod-probes");
5015 } else {
5016 free(kmod_extra_probes_list);
5017 kmod_extra_probes_list = strdup(arg);
5018 if (!kmod_extra_probes_list) {
5019 PERROR("strdup");
5020 ret = -ENOMEM;
5021 }
5022 }
5023 } else if (string_match(optname, "config") || opt == 'f') {
5024 /* This is handled in set_options() thus silent skip. */
5025 goto end;
5026 } else {
5027 /* Unknown option or other error.
5028 * Error is printed by getopt, just return */
5029 ret = -1;
5030 }
5031
5032end:
5033 if (ret == -EINVAL) {
5034 const char *opt_name = "unknown";
5035 int i;
5036
5037 for (i = 0; i < sizeof(long_options) / sizeof(struct option);
5038 i++) {
5039 if (opt == long_options[i].val) {
5040 opt_name = long_options[i].name;
5041 break;
5042 }
5043 }
5044
5045 WARN("Invalid argument provided for option \"%s\", using default value.",
5046 opt_name);
5047 }
5048
5049 return ret;
5050}
5051
5052/*
5053 * config_entry_handler_cb used to handle options read from a config file.
5054 * See config_entry_handler_cb comment in common/config/session-config.h for the
5055 * return value conventions.
5056 */
5057static int config_entry_handler(const struct config_entry *entry, void *unused)
5058{
5059 int ret = 0, i;
5060
5061 if (!entry || !entry->name || !entry->value) {
5062 ret = -EINVAL;
5063 goto end;
5064 }
5065
5066 /* Check if the option is to be ignored */
5067 for (i = 0; i < sizeof(config_ignore_options) / sizeof(char *); i++) {
5068 if (!strcmp(entry->name, config_ignore_options[i])) {
5069 goto end;
5070 }
5071 }
5072
5073 for (i = 0; i < (sizeof(long_options) / sizeof(struct option)) - 1;
5074 i++) {
5075
5076 /* Ignore if not fully matched. */
5077 if (strcmp(entry->name, long_options[i].name)) {
5078 continue;
5079 }
5080
5081 /*
5082 * If the option takes no argument on the command line, we have to
5083 * check if the value is "true". We support non-zero numeric values,
5084 * true, on and yes.
5085 */
5086 if (!long_options[i].has_arg) {
5087 ret = config_parse_value(entry->value);
5088 if (ret <= 0) {
5089 if (ret) {
5090 WARN("Invalid configuration value \"%s\" for option %s",
5091 entry->value, entry->name);
5092 }
5093 /* False, skip boolean config option. */
5094 goto end;
5095 }
5096 }
5097
5098 ret = set_option(long_options[i].val, entry->value, entry->name);
5099 goto end;
5100 }
5101
5102 WARN("Unrecognized option \"%s\" in daemon configuration file.", entry->name);
5103
5104end:
5105 return ret;
5106}
5107
5108/*
5109 * daemon configuration loading and argument parsing
5110 */
5111static int set_options(int argc, char **argv)
5112{
5113 int ret = 0, c = 0, option_index = 0;
5114 int orig_optopt = optopt, orig_optind = optind;
5115 char *optstring;
5116 const char *config_path = NULL;
5117
5118 optstring = utils_generate_optstring(long_options,
5119 sizeof(long_options) / sizeof(struct option));
5120 if (!optstring) {
5121 ret = -ENOMEM;
5122 goto end;
5123 }
5124
5125 /* Check for the --config option */
5126 while ((c = getopt_long(argc, argv, optstring, long_options,
5127 &option_index)) != -1) {
5128 if (c == '?') {
5129 ret = -EINVAL;
5130 goto end;
5131 } else if (c != 'f') {
5132 /* if not equal to --config option. */
5133 continue;
5134 }
5135
5136 if (lttng_is_setuid_setgid()) {
5137 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
5138 "-f, --config");
5139 } else {
5140 config_path = utils_expand_path(optarg);
5141 if (!config_path) {
5142 ERR("Failed to resolve path: %s", optarg);
5143 }
5144 }
5145 }
5146
5147 ret = config_get_section_entries(config_path, config_section_name,
5148 config_entry_handler, NULL);
5149 if (ret) {
5150 if (ret > 0) {
5151 ERR("Invalid configuration option at line %i", ret);
5152 ret = -1;
5153 }
5154 goto end;
5155 }
5156
5157 /* Reset getopt's global state */
5158 optopt = orig_optopt;
5159 optind = orig_optind;
5160 while (1) {
5161 option_index = -1;
5162 /*
5163 * getopt_long() will not set option_index if it encounters a
5164 * short option.
5165 */
5166 c = getopt_long(argc, argv, optstring, long_options,
5167 &option_index);
5168 if (c == -1) {
5169 break;
5170 }
5171
5172 /*
5173 * Pass NULL as the long option name if popt left the index
5174 * unset.
5175 */
5176 ret = set_option(c, optarg,
5177 option_index < 0 ? NULL :
5178 long_options[option_index].name);
5179 if (ret < 0) {
5180 break;
5181 }
5182 }
5183
5184end:
5185 free(optstring);
5186 return ret;
5187}
5188
5189/*
5190 * Creates the two needed socket by the daemon.
5191 * apps_sock - The communication socket for all UST apps.
5192 * client_sock - The communication of the cli tool (lttng).
5193 */
5194static int init_daemon_socket(void)
5195{
5196 int ret = 0;
5197 mode_t old_umask;
5198
5199 old_umask = umask(0);
5200
5201 /* Create client tool unix socket */
5202 client_sock = lttcomm_create_unix_sock(client_unix_sock_path);
5203 if (client_sock < 0) {
5204 ERR("Create unix sock failed: %s", client_unix_sock_path);
5205 ret = -1;
5206 goto end;
5207 }
5208
5209 /* Set the cloexec flag */
5210 ret = utils_set_fd_cloexec(client_sock);
5211 if (ret < 0) {
5212 ERR("Unable to set CLOEXEC flag to the client Unix socket (fd: %d). "
5213 "Continuing but note that the consumer daemon will have a "
5214 "reference to this socket on exec()", client_sock);
5215 }
5216
5217 /* File permission MUST be 660 */
5218 ret = chmod(client_unix_sock_path, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
5219 if (ret < 0) {
5220 ERR("Set file permissions failed: %s", client_unix_sock_path);
5221 PERROR("chmod");
5222 goto end;
5223 }
5224
5225 /* Create the application unix socket */
5226 apps_sock = lttcomm_create_unix_sock(apps_unix_sock_path);
5227 if (apps_sock < 0) {
5228 ERR("Create unix sock failed: %s", apps_unix_sock_path);
5229 ret = -1;
5230 goto end;
5231 }
5232
5233 /* Set the cloexec flag */
5234 ret = utils_set_fd_cloexec(apps_sock);
5235 if (ret < 0) {
5236 ERR("Unable to set CLOEXEC flag to the app Unix socket (fd: %d). "
5237 "Continuing but note that the consumer daemon will have a "
5238 "reference to this socket on exec()", apps_sock);
5239 }
5240
5241 /* File permission MUST be 666 */
5242 ret = chmod(apps_unix_sock_path,
5243 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
5244 if (ret < 0) {
5245 ERR("Set file permissions failed: %s", apps_unix_sock_path);
5246 PERROR("chmod");
5247 goto end;
5248 }
5249
5250 DBG3("Session daemon client socket %d and application socket %d created",
5251 client_sock, apps_sock);
5252
5253end:
5254 umask(old_umask);
5255 return ret;
5256}
5257
5258/*
5259 * Check if the global socket is available, and if a daemon is answering at the
5260 * other side. If yes, error is returned.
5261 */
5262static int check_existing_daemon(void)
5263{
5264 /* Is there anybody out there ? */
5265 if (lttng_session_daemon_alive()) {
5266 return -EEXIST;
5267 }
5268
5269 return 0;
5270}
5271
5272/*
5273 * Set the tracing group gid onto the client socket.
5274 *
5275 * Race window between mkdir and chown is OK because we are going from more
5276 * permissive (root.root) to less permissive (root.tracing).
5277 */
5278static int set_permissions(char *rundir)
5279{
5280 int ret;
5281 gid_t gid;
5282
5283 gid = utils_get_group_id(tracing_group_name);
5284
5285 /* Set lttng run dir */
5286 ret = chown(rundir, 0, gid);
5287 if (ret < 0) {
5288 ERR("Unable to set group on %s", rundir);
5289 PERROR("chown");
5290 }
5291
5292 /*
5293 * Ensure all applications and tracing group can search the run
5294 * dir. Allow everyone to read the directory, since it does not
5295 * buy us anything to hide its content.
5296 */
5297 ret = chmod(rundir, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
5298 if (ret < 0) {
5299 ERR("Unable to set permissions on %s", rundir);
5300 PERROR("chmod");
5301 }
5302
5303 /* lttng client socket path */
5304 ret = chown(client_unix_sock_path, 0, gid);
5305 if (ret < 0) {
5306 ERR("Unable to set group on %s", client_unix_sock_path);
5307 PERROR("chown");
5308 }
5309
5310 /* kconsumer error socket path */
5311 ret = chown(kconsumer_data.err_unix_sock_path, 0, 0);
5312 if (ret < 0) {
5313 ERR("Unable to set group on %s", kconsumer_data.err_unix_sock_path);
5314 PERROR("chown");
5315 }
5316
5317 /* 64-bit ustconsumer error socket path */
5318 ret = chown(ustconsumer64_data.err_unix_sock_path, 0, 0);
5319 if (ret < 0) {
5320 ERR("Unable to set group on %s", ustconsumer64_data.err_unix_sock_path);
5321 PERROR("chown");
5322 }
5323
5324 /* 32-bit ustconsumer compat32 error socket path */
5325 ret = chown(ustconsumer32_data.err_unix_sock_path, 0, 0);
5326 if (ret < 0) {
5327 ERR("Unable to set group on %s", ustconsumer32_data.err_unix_sock_path);
5328 PERROR("chown");
5329 }
5330
5331 DBG("All permissions are set");
5332
5333 return ret;
5334}
5335
5336/*
5337 * Create the lttng run directory needed for all global sockets and pipe.
5338 */
5339static int create_lttng_rundir(const char *rundir)
5340{
5341 int ret;
5342
5343 DBG3("Creating LTTng run directory: %s", rundir);
5344
5345 ret = mkdir(rundir, S_IRWXU);
5346 if (ret < 0) {
5347 if (errno != EEXIST) {
5348 ERR("Unable to create %s", rundir);
5349 goto error;
5350 } else {
5351 ret = 0;
5352 }
5353 }
5354
5355error:
5356 return ret;
5357}
5358
5359/*
5360 * Setup sockets and directory needed by the kconsumerd communication with the
5361 * session daemon.
5362 */
5363static int set_consumer_sockets(struct consumer_data *consumer_data,
5364 const char *rundir)
5365{
5366 int ret;
5367 char path[PATH_MAX];
5368
5369 switch (consumer_data->type) {
5370 case LTTNG_CONSUMER_KERNEL:
5371 snprintf(path, PATH_MAX, DEFAULT_KCONSUMERD_PATH, rundir);
5372 break;
5373 case LTTNG_CONSUMER64_UST:
5374 snprintf(path, PATH_MAX, DEFAULT_USTCONSUMERD64_PATH, rundir);
5375 break;
5376 case LTTNG_CONSUMER32_UST:
5377 snprintf(path, PATH_MAX, DEFAULT_USTCONSUMERD32_PATH, rundir);
5378 break;
5379 default:
5380 ERR("Consumer type unknown");
5381 ret = -EINVAL;
5382 goto error;
5383 }
5384
5385 DBG2("Creating consumer directory: %s", path);
5386
5387 ret = mkdir(path, S_IRWXU | S_IRGRP | S_IXGRP);
5388 if (ret < 0) {
5389 if (errno != EEXIST) {
5390 PERROR("mkdir");
5391 ERR("Failed to create %s", path);
5392 goto error;
5393 }
5394 ret = -1;
5395 }
5396 if (is_root) {
5397 ret = chown(path, 0, utils_get_group_id(tracing_group_name));
5398 if (ret < 0) {
5399 ERR("Unable to set group on %s", path);
5400 PERROR("chown");
5401 goto error;
5402 }
5403 }
5404
5405 /* Create the kconsumerd error unix socket */
5406 consumer_data->err_sock =
5407 lttcomm_create_unix_sock(consumer_data->err_unix_sock_path);
5408 if (consumer_data->err_sock < 0) {
5409 ERR("Create unix sock failed: %s", consumer_data->err_unix_sock_path);
5410 ret = -1;
5411 goto error;
5412 }
5413
5414 /*
5415 * Set the CLOEXEC flag. Return code is useless because either way, the
5416 * show must go on.
5417 */
5418 ret = utils_set_fd_cloexec(consumer_data->err_sock);
5419 if (ret < 0) {
5420 PERROR("utils_set_fd_cloexec");
5421 /* continue anyway */
5422 }
5423
5424 /* File permission MUST be 660 */
5425 ret = chmod(consumer_data->err_unix_sock_path,
5426 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
5427 if (ret < 0) {
5428 ERR("Set file permissions failed: %s", consumer_data->err_unix_sock_path);
5429 PERROR("chmod");
5430 goto error;
5431 }
5432
5433error:
5434 return ret;
5435}
5436
5437/*
5438 * Signal handler for the daemon
5439 *
5440 * Simply stop all worker threads, leaving main() return gracefully after
5441 * joining all threads and calling cleanup().
5442 */
5443static void sighandler(int sig)
5444{
5445 switch (sig) {
5446 case SIGINT:
5447 DBG("SIGINT caught");
5448 stop_threads();
5449 break;
5450 case SIGTERM:
5451 DBG("SIGTERM caught");
5452 stop_threads();
5453 break;
5454 case SIGUSR1:
5455 CMM_STORE_SHARED(recv_child_signal, 1);
5456 break;
5457 default:
5458 break;
5459 }
5460}
5461
5462/*
5463 * Setup signal handler for :
5464 * SIGINT, SIGTERM, SIGPIPE
5465 */
5466static int set_signal_handler(void)
5467{
5468 int ret = 0;
5469 struct sigaction sa;
5470 sigset_t sigset;
5471
5472 if ((ret = sigemptyset(&sigset)) < 0) {
5473 PERROR("sigemptyset");
5474 return ret;
5475 }
5476
5477 sa.sa_mask = sigset;
5478 sa.sa_flags = 0;
5479
5480 sa.sa_handler = sighandler;
5481 if ((ret = sigaction(SIGTERM, &sa, NULL)) < 0) {
5482 PERROR("sigaction");
5483 return ret;
5484 }
5485
5486 if ((ret = sigaction(SIGINT, &sa, NULL)) < 0) {
5487 PERROR("sigaction");
5488 return ret;
5489 }
5490
5491 if ((ret = sigaction(SIGUSR1, &sa, NULL)) < 0) {
5492 PERROR("sigaction");
5493 return ret;
5494 }
5495
5496 sa.sa_handler = SIG_IGN;
5497 if ((ret = sigaction(SIGPIPE, &sa, NULL)) < 0) {
5498 PERROR("sigaction");
5499 return ret;
5500 }
5501
5502 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
5503
5504 return ret;
5505}
5506
5507/*
5508 * Set open files limit to unlimited. This daemon can open a large number of
5509 * file descriptors in order to consume multiple kernel traces.
5510 */
5511static void set_ulimit(void)
5512{
5513 int ret;
5514 struct rlimit lim;
5515
5516 /* The kernel does not allow an infinite limit for open files */
5517 lim.rlim_cur = 65535;
5518 lim.rlim_max = 65535;
5519
5520 ret = setrlimit(RLIMIT_NOFILE, &lim);
5521 if (ret < 0) {
5522 PERROR("failed to set open files limit");
5523 }
5524}
5525
5526/*
5527 * Write pidfile using the rundir and opt_pidfile.
5528 */
5529static int write_pidfile(void)
5530{
5531 int ret;
5532 char pidfile_path[PATH_MAX];
5533
5534 assert(rundir);
5535
5536 if (opt_pidfile) {
5537 if (lttng_strncpy(pidfile_path, opt_pidfile, sizeof(pidfile_path))) {
5538 ret = -1;
5539 goto error;
5540 }
5541 } else {
5542 /* Build pidfile path from rundir and opt_pidfile. */
5543 ret = snprintf(pidfile_path, sizeof(pidfile_path), "%s/"
5544 DEFAULT_LTTNG_SESSIOND_PIDFILE, rundir);
5545 if (ret < 0) {
5546 PERROR("snprintf pidfile path");
5547 goto error;
5548 }
5549 }
5550
5551 /*
5552 * Create pid file in rundir.
5553 */
5554 ret = utils_create_pid_file(getpid(), pidfile_path);
5555error:
5556 return ret;
5557}
5558
5559/*
5560 * Create lockfile using the rundir and return its fd.
5561 */
5562static int create_lockfile(void)
5563{
5564 int ret;
5565 char lockfile_path[PATH_MAX];
5566
5567 ret = generate_lock_file_path(lockfile_path, sizeof(lockfile_path));
5568 if (ret < 0) {
5569 goto error;
5570 }
5571
5572 ret = utils_create_lock_file(lockfile_path);
5573error:
5574 return ret;
5575}
5576
5577/*
5578 * Write agent TCP port using the rundir.
5579 */
5580static int write_agent_port(void)
5581{
5582 int ret;
5583 char path[PATH_MAX];
5584
5585 assert(rundir);
5586
5587 ret = snprintf(path, sizeof(path), "%s/"
5588 DEFAULT_LTTNG_SESSIOND_AGENTPORT_FILE, rundir);
5589 if (ret < 0) {
5590 PERROR("snprintf agent port path");
5591 goto error;
5592 }
5593
5594 /*
5595 * Create TCP agent port file in rundir.
5596 */
5597 ret = utils_create_pid_file(agent_tcp_port, path);
5598
5599error:
5600 return ret;
5601}
5602
5603/*
5604 * main
5605 */
5606int main(int argc, char **argv)
5607{
5608 int ret = 0, retval = 0;
5609 void *status;
5610 const char *home_path, *env_app_timeout;
5611 struct lttng_pipe *ust32_channel_monitor_pipe = NULL,
5612 *ust64_channel_monitor_pipe = NULL,
5613 *kernel_channel_monitor_pipe = NULL;
5614
5615 init_kernel_workarounds();
5616
5617 rcu_register_thread();
5618
5619 if (set_signal_handler()) {
5620 retval = -1;
5621 goto exit_set_signal_handler;
5622 }
5623
5624 setup_consumerd_path();
5625
5626 page_size = sysconf(_SC_PAGESIZE);
5627 if (page_size < 0) {
5628 PERROR("sysconf _SC_PAGESIZE");
5629 page_size = LONG_MAX;
5630 WARN("Fallback page size to %ld", page_size);
5631 }
5632
5633 /*
5634 * Parse arguments and load the daemon configuration file.
5635 *
5636 * We have an exit_options exit path to free memory reserved by
5637 * set_options. This is needed because the rest of sessiond_cleanup()
5638 * depends on ht_cleanup_thread, which depends on lttng_daemonize, which
5639 * depends on set_options.
5640 */
5641 progname = argv[0];
5642 if (set_options(argc, argv)) {
5643 retval = -1;
5644 goto exit_options;
5645 }
5646
5647 /* Daemonize */
5648 if (opt_daemon || opt_background) {
5649 int i;
5650
5651 ret = lttng_daemonize(&child_ppid, &recv_child_signal,
5652 !opt_background);
5653 if (ret < 0) {
5654 retval = -1;
5655 goto exit_options;
5656 }
5657
5658 /*
5659 * We are in the child. Make sure all other file descriptors are
5660 * closed, in case we are called with more opened file
5661 * descriptors than the standard ones.
5662 */
5663 for (i = 3; i < sysconf(_SC_OPEN_MAX); i++) {
5664 (void) close(i);
5665 }
5666 }
5667
5668 if (run_as_create_worker(argv[0]) < 0) {
5669 goto exit_create_run_as_worker_cleanup;
5670 }
5671
5672 /*
5673 * Starting from here, we can create threads. This needs to be after
5674 * lttng_daemonize due to RCU.
5675 */
5676
5677 /*
5678 * Initialize the health check subsystem. This call should set the
5679 * appropriate time values.
5680 */
5681 health_sessiond = health_app_create(NR_HEALTH_SESSIOND_TYPES);
5682 if (!health_sessiond) {
5683 PERROR("health_app_create error");
5684 retval = -1;
5685 goto exit_health_sessiond_cleanup;
5686 }
5687
5688 /* Create thread to clean up RCU hash tables */
5689 if (init_ht_cleanup_thread(&ht_cleanup_thread)) {
5690 retval = -1;
5691 goto exit_ht_cleanup;
5692 }
5693
5694 /* Create thread quit pipe */
5695 if (init_thread_quit_pipe()) {
5696 retval = -1;
5697 goto exit_init_data;
5698 }
5699
5700 /* Check if daemon is UID = 0 */
5701 is_root = !getuid();
5702
5703 if (is_root) {
5704 rundir = strdup(DEFAULT_LTTNG_RUNDIR);
5705 if (!rundir) {
5706 retval = -1;
5707 goto exit_init_data;
5708 }
5709
5710 /* Create global run dir with root access */
5711 if (create_lttng_rundir(rundir)) {
5712 retval = -1;
5713 goto exit_init_data;
5714 }
5715
5716 if (strlen(apps_unix_sock_path) == 0) {
5717 ret = snprintf(apps_unix_sock_path, PATH_MAX,
5718 DEFAULT_GLOBAL_APPS_UNIX_SOCK);
5719 if (ret < 0) {
5720 retval = -1;
5721 goto exit_init_data;
5722 }
5723 }
5724
5725 if (strlen(client_unix_sock_path) == 0) {
5726 ret = snprintf(client_unix_sock_path, PATH_MAX,
5727 DEFAULT_GLOBAL_CLIENT_UNIX_SOCK);
5728 if (ret < 0) {
5729 retval = -1;
5730 goto exit_init_data;
5731 }
5732 }
5733
5734 /* Set global SHM for ust */
5735 if (strlen(wait_shm_path) == 0) {
5736 ret = snprintf(wait_shm_path, PATH_MAX,
5737 DEFAULT_GLOBAL_APPS_WAIT_SHM_PATH);
5738 if (ret < 0) {
5739 retval = -1;
5740 goto exit_init_data;
5741 }
5742 }
5743
5744 if (strlen(health_unix_sock_path) == 0) {
5745 ret = snprintf(health_unix_sock_path,
5746 sizeof(health_unix_sock_path),
5747 DEFAULT_GLOBAL_HEALTH_UNIX_SOCK);
5748 if (ret < 0) {
5749 retval = -1;
5750 goto exit_init_data;
5751 }
5752 }
5753
5754 /* Setup kernel consumerd path */
5755 ret = snprintf(kconsumer_data.err_unix_sock_path, PATH_MAX,
5756 DEFAULT_KCONSUMERD_ERR_SOCK_PATH, rundir);
5757 if (ret < 0) {
5758 retval = -1;
5759 goto exit_init_data;
5760 }
5761 ret = snprintf(kconsumer_data.cmd_unix_sock_path, PATH_MAX,
5762 DEFAULT_KCONSUMERD_CMD_SOCK_PATH, rundir);
5763 if (ret < 0) {
5764 retval = -1;
5765 goto exit_init_data;
5766 }
5767
5768 DBG2("Kernel consumer err path: %s",
5769 kconsumer_data.err_unix_sock_path);
5770 DBG2("Kernel consumer cmd path: %s",
5771 kconsumer_data.cmd_unix_sock_path);
5772 kernel_channel_monitor_pipe = lttng_pipe_open(0);
5773 if (!kernel_channel_monitor_pipe) {
5774 ERR("Failed to create kernel consumer channel monitor pipe");
5775 retval = -1;
5776 goto exit_init_data;
5777 }
5778 kconsumer_data.channel_monitor_pipe =
5779 lttng_pipe_release_writefd(
5780 kernel_channel_monitor_pipe);
5781 if (kconsumer_data.channel_monitor_pipe < 0) {
5782 retval = -1;
5783 goto exit_init_data;
5784 }
5785 } else {
5786 home_path = utils_get_home_dir();
5787 if (home_path == NULL) {
5788 /* TODO: Add --socket PATH option */
5789 ERR("Can't get HOME directory for sockets creation.");
5790 retval = -1;
5791 goto exit_init_data;
5792 }
5793
5794 /*
5795 * Create rundir from home path. This will create something like
5796 * $HOME/.lttng
5797 */
5798 ret = asprintf(&rundir, DEFAULT_LTTNG_HOME_RUNDIR, home_path);
5799 if (ret < 0) {
5800 retval = -1;
5801 goto exit_init_data;
5802 }
5803
5804 if (create_lttng_rundir(rundir)) {
5805 retval = -1;
5806 goto exit_init_data;
5807 }
5808
5809 if (strlen(apps_unix_sock_path) == 0) {
5810 ret = snprintf(apps_unix_sock_path, PATH_MAX,
5811 DEFAULT_HOME_APPS_UNIX_SOCK,
5812 home_path);
5813 if (ret < 0) {
5814 retval = -1;
5815 goto exit_init_data;
5816 }
5817 }
5818
5819 /* Set the cli tool unix socket path */
5820 if (strlen(client_unix_sock_path) == 0) {
5821 ret = snprintf(client_unix_sock_path, PATH_MAX,
5822 DEFAULT_HOME_CLIENT_UNIX_SOCK,
5823 home_path);
5824 if (ret < 0) {
5825 retval = -1;
5826 goto exit_init_data;
5827 }
5828 }
5829
5830 /* Set global SHM for ust */
5831 if (strlen(wait_shm_path) == 0) {
5832 ret = snprintf(wait_shm_path, PATH_MAX,
5833 DEFAULT_HOME_APPS_WAIT_SHM_PATH,
5834 getuid());
5835 if (ret < 0) {
5836 retval = -1;
5837 goto exit_init_data;
5838 }
5839 }
5840
5841 /* Set health check Unix path */
5842 if (strlen(health_unix_sock_path) == 0) {
5843 ret = snprintf(health_unix_sock_path,
5844 sizeof(health_unix_sock_path),
5845 DEFAULT_HOME_HEALTH_UNIX_SOCK,
5846 home_path);
5847 if (ret < 0) {
5848 retval = -1;
5849 goto exit_init_data;
5850 }
5851 }
5852 }
5853
5854 lockfile_fd = create_lockfile();
5855 if (lockfile_fd < 0) {
5856 retval = -1;
5857 goto exit_init_data;
5858 }
5859
5860 /* Set consumer initial state */
5861 kernel_consumerd_state = CONSUMER_STOPPED;
5862 ust_consumerd_state = CONSUMER_STOPPED;
5863
5864 DBG("Client socket path %s", client_unix_sock_path);
5865 DBG("Application socket path %s", apps_unix_sock_path);
5866 DBG("Application wait path %s", wait_shm_path);
5867 DBG("LTTng run directory path: %s", rundir);
5868
5869 /* 32 bits consumerd path setup */
5870 ret = snprintf(ustconsumer32_data.err_unix_sock_path, PATH_MAX,
5871 DEFAULT_USTCONSUMERD32_ERR_SOCK_PATH, rundir);
5872 if (ret < 0) {
5873 PERROR("snprintf 32-bit consumer error socket path");
5874 retval = -1;
5875 goto exit_init_data;
5876 }
5877 ret = snprintf(ustconsumer32_data.cmd_unix_sock_path, PATH_MAX,
5878 DEFAULT_USTCONSUMERD32_CMD_SOCK_PATH, rundir);
5879 if (ret < 0) {
5880 PERROR("snprintf 32-bit consumer command socket path");
5881 retval = -1;
5882 goto exit_init_data;
5883 }
5884
5885 DBG2("UST consumer 32 bits err path: %s",
5886 ustconsumer32_data.err_unix_sock_path);
5887 DBG2("UST consumer 32 bits cmd path: %s",
5888 ustconsumer32_data.cmd_unix_sock_path);
5889 ust32_channel_monitor_pipe = lttng_pipe_open(0);
5890 if (!ust32_channel_monitor_pipe) {
5891 ERR("Failed to create 32-bit user space consumer channel monitor pipe");
5892 retval = -1;
5893 goto exit_init_data;
5894 }
5895 ustconsumer32_data.channel_monitor_pipe = lttng_pipe_release_writefd(
5896 ust32_channel_monitor_pipe);
5897 if (ustconsumer32_data.channel_monitor_pipe < 0) {
5898 retval = -1;
5899 goto exit_init_data;
5900 }
5901
5902 /* 64 bits consumerd path setup */
5903 ret = snprintf(ustconsumer64_data.err_unix_sock_path, PATH_MAX,
5904 DEFAULT_USTCONSUMERD64_ERR_SOCK_PATH, rundir);
5905 if (ret < 0) {
5906 PERROR("snprintf 64-bit consumer error socket path");
5907 retval = -1;
5908 goto exit_init_data;
5909 }
5910 ret = snprintf(ustconsumer64_data.cmd_unix_sock_path, PATH_MAX,
5911 DEFAULT_USTCONSUMERD64_CMD_SOCK_PATH, rundir);
5912 if (ret < 0) {
5913 PERROR("snprintf 64-bit consumer command socket path");
5914 retval = -1;
5915 goto exit_init_data;
5916 }
5917
5918 DBG2("UST consumer 64 bits err path: %s",
5919 ustconsumer64_data.err_unix_sock_path);
5920 DBG2("UST consumer 64 bits cmd path: %s",
5921 ustconsumer64_data.cmd_unix_sock_path);
5922 ust64_channel_monitor_pipe = lttng_pipe_open(0);
5923 if (!ust64_channel_monitor_pipe) {
5924 ERR("Failed to create 64-bit user space consumer channel monitor pipe");
5925 retval = -1;
5926 goto exit_init_data;
5927 }
5928 ustconsumer64_data.channel_monitor_pipe = lttng_pipe_release_writefd(
5929 ust64_channel_monitor_pipe);
5930 if (ustconsumer64_data.channel_monitor_pipe < 0) {
5931 retval = -1;
5932 goto exit_init_data;
5933 }
5934
5935 /*
5936 * See if daemon already exist.
5937 */
5938 if (check_existing_daemon()) {
5939 ERR("Already running daemon.\n");
5940 /*
5941 * We do not goto exit because we must not cleanup()
5942 * because a daemon is already running.
5943 */
5944 retval = -1;
5945 goto exit_init_data;
5946 }
5947
5948 /*
5949 * Init UST app hash table. Alloc hash table before this point since
5950 * cleanup() can get called after that point.
5951 */
5952 if (ust_app_ht_alloc()) {
5953 ERR("Failed to allocate UST app hash table");
5954 retval = -1;
5955 goto exit_init_data;
5956 }
5957
5958 /*
5959 * Initialize agent app hash table. We allocate the hash table here
5960 * since cleanup() can get called after this point.
5961 */
5962 if (agent_app_ht_alloc()) {
5963 ERR("Failed to allocate Agent app hash table");
5964 retval = -1;
5965 goto exit_init_data;
5966 }
5967
5968 /*
5969 * These actions must be executed as root. We do that *after* setting up
5970 * the sockets path because we MUST make the check for another daemon using
5971 * those paths *before* trying to set the kernel consumer sockets and init
5972 * kernel tracer.
5973 */
5974 if (is_root) {
5975 if (set_consumer_sockets(&kconsumer_data, rundir)) {
5976 retval = -1;
5977 goto exit_init_data;
5978 }
5979
5980 /* Setup kernel tracer */
5981 if (!opt_no_kernel) {
5982 init_kernel_tracer();
5983 if (kernel_tracer_fd >= 0) {
5984 ret = syscall_init_table();
5985 if (ret < 0) {
5986 ERR("Unable to populate syscall table. "
5987 "Syscall tracing won't work "
5988 "for this session daemon.");
5989 }
5990 }
5991 }
5992
5993 /* Set ulimit for open files */
5994 set_ulimit();
5995 }
5996 /* init lttng_fd tracking must be done after set_ulimit. */
5997 lttng_fd_init();
5998
5999 if (set_consumer_sockets(&ustconsumer64_data, rundir)) {
6000 retval = -1;
6001 goto exit_init_data;
6002 }
6003
6004 if (set_consumer_sockets(&ustconsumer32_data, rundir)) {
6005 retval = -1;
6006 goto exit_init_data;
6007 }
6008
6009 /* Setup the needed unix socket */
6010 if (init_daemon_socket()) {
6011 retval = -1;
6012 goto exit_init_data;
6013 }
6014
6015 /* Set credentials to socket */
6016 if (is_root && set_permissions(rundir)) {
6017 retval = -1;
6018 goto exit_init_data;
6019 }
6020
6021 /* Get parent pid if -S, --sig-parent is specified. */
6022 if (opt_sig_parent) {
6023 ppid = getppid();
6024 }
6025
6026 /* Setup the kernel pipe for waking up the kernel thread */
6027 if (is_root && !opt_no_kernel) {
6028 if (utils_create_pipe_cloexec(kernel_poll_pipe)) {
6029 retval = -1;
6030 goto exit_init_data;
6031 }
6032 }
6033
6034 /* Setup the thread apps communication pipe. */
6035 if (utils_create_pipe_cloexec(apps_cmd_pipe)) {
6036 retval = -1;
6037 goto exit_init_data;
6038 }
6039
6040 /* Setup the thread apps notify communication pipe. */
6041 if (utils_create_pipe_cloexec(apps_cmd_notify_pipe)) {
6042 retval = -1;
6043 goto exit_init_data;
6044 }
6045
6046 /* Initialize global buffer per UID and PID registry. */
6047 buffer_reg_init_uid_registry();
6048 buffer_reg_init_pid_registry();
6049
6050 /* Init UST command queue. */
6051 cds_wfcq_init(&ust_cmd_queue.head, &ust_cmd_queue.tail);
6052
6053 /*
6054 * Get session list pointer. This pointer MUST NOT be free'd. This list
6055 * is statically declared in session.c
6056 */
6057 session_list_ptr = session_get_list();
6058
6059 cmd_init();
6060
6061 /* Check for the application socket timeout env variable. */
6062 env_app_timeout = getenv(DEFAULT_APP_SOCKET_TIMEOUT_ENV);
6063 if (env_app_timeout) {
6064 app_socket_timeout = atoi(env_app_timeout);
6065 } else {
6066 app_socket_timeout = DEFAULT_APP_SOCKET_RW_TIMEOUT;
6067 }
6068
6069 ret = write_pidfile();
6070 if (ret) {
6071 ERR("Error in write_pidfile");
6072 retval = -1;
6073 goto exit_init_data;
6074 }
6075 ret = write_agent_port();
6076 if (ret) {
6077 ERR("Error in write_agent_port");
6078 retval = -1;
6079 goto exit_init_data;
6080 }
6081
6082 /* Initialize communication library */
6083 lttcomm_init();
6084 /* Initialize TCP timeout values */
6085 lttcomm_inet_init();
6086
6087 if (load_session_init_data(&load_info) < 0) {
6088 retval = -1;
6089 goto exit_init_data;
6090 }
6091 load_info->path = opt_load_session_path;
6092
6093 /* Create health-check thread. */
6094 ret = pthread_create(&health_thread, default_pthread_attr(),
6095 thread_manage_health, (void *) NULL);
6096 if (ret) {
6097 errno = ret;
6098 PERROR("pthread_create health");
6099 retval = -1;
6100 goto exit_health;
6101 }
6102
6103 /* notification_thread_data acquires the pipes' read side. */
6104 notification_thread_handle = notification_thread_handle_create(
6105 ust32_channel_monitor_pipe,
6106 ust64_channel_monitor_pipe,
6107 kernel_channel_monitor_pipe);
6108 if (!notification_thread_handle) {
6109 retval = -1;
6110 ERR("Failed to create notification thread shared data");
6111 stop_threads();
6112 goto exit_notification;
6113 }
6114
6115 /* Create notification thread. */
6116 ret = pthread_create(&notification_thread, default_pthread_attr(),
6117 thread_notification, notification_thread_handle);
6118 if (ret) {
6119 errno = ret;
6120 PERROR("pthread_create notification");
6121 retval = -1;
6122 stop_threads();
6123 goto exit_notification;
6124 }
6125
6126 /* Create thread to manage the client socket */
6127 ret = pthread_create(&client_thread, default_pthread_attr(),
6128 thread_manage_clients, (void *) NULL);
6129 if (ret) {
6130 errno = ret;
6131 PERROR("pthread_create clients");
6132 retval = -1;
6133 stop_threads();
6134 goto exit_client;
6135 }
6136
6137 /* Create thread to dispatch registration */
6138 ret = pthread_create(&dispatch_thread, default_pthread_attr(),
6139 thread_dispatch_ust_registration, (void *) NULL);
6140 if (ret) {
6141 errno = ret;
6142 PERROR("pthread_create dispatch");
6143 retval = -1;
6144 stop_threads();
6145 goto exit_dispatch;
6146 }
6147
6148 /* Create thread to manage application registration. */
6149 ret = pthread_create(&reg_apps_thread, default_pthread_attr(),
6150 thread_registration_apps, (void *) NULL);
6151 if (ret) {
6152 errno = ret;
6153 PERROR("pthread_create registration");
6154 retval = -1;
6155 stop_threads();
6156 goto exit_reg_apps;
6157 }
6158
6159 /* Create thread to manage application socket */
6160 ret = pthread_create(&apps_thread, default_pthread_attr(),
6161 thread_manage_apps, (void *) NULL);
6162 if (ret) {
6163 errno = ret;
6164 PERROR("pthread_create apps");
6165 retval = -1;
6166 stop_threads();
6167 goto exit_apps;
6168 }
6169
6170 /* Create thread to manage application notify socket */
6171 ret = pthread_create(&apps_notify_thread, default_pthread_attr(),
6172 ust_thread_manage_notify, (void *) NULL);
6173 if (ret) {
6174 errno = ret;
6175 PERROR("pthread_create notify");
6176 retval = -1;
6177 stop_threads();
6178 goto exit_apps_notify;
6179 }
6180
6181 /* Create agent registration thread. */
6182 ret = pthread_create(&agent_reg_thread, default_pthread_attr(),
6183 agent_thread_manage_registration, (void *) NULL);
6184 if (ret) {
6185 errno = ret;
6186 PERROR("pthread_create agent");
6187 retval = -1;
6188 stop_threads();
6189 goto exit_agent_reg;
6190 }
6191
6192 /* Don't start this thread if kernel tracing is not requested nor root */
6193 if (is_root && !opt_no_kernel) {
6194 /* Create kernel thread to manage kernel event */
6195 ret = pthread_create(&kernel_thread, default_pthread_attr(),
6196 thread_manage_kernel, (void *) NULL);
6197 if (ret) {
6198 errno = ret;
6199 PERROR("pthread_create kernel");
6200 retval = -1;
6201 stop_threads();
6202 goto exit_kernel;
6203 }
6204 }
6205
6206 /* Create session loading thread. */
6207 ret = pthread_create(&load_session_thread, default_pthread_attr(),
6208 thread_load_session, load_info);
6209 if (ret) {
6210 errno = ret;
6211 PERROR("pthread_create load_session_thread");
6212 retval = -1;
6213 stop_threads();
6214 goto exit_load_session;
6215 }
6216
6217 /*
6218 * This is where we start awaiting program completion (e.g. through
6219 * signal that asks threads to teardown).
6220 */
6221
6222 ret = pthread_join(load_session_thread, &status);
6223 if (ret) {
6224 errno = ret;
6225 PERROR("pthread_join load_session_thread");
6226 retval = -1;
6227 }
6228exit_load_session:
6229
6230 if (is_root && !opt_no_kernel) {
6231 ret = pthread_join(kernel_thread, &status);
6232 if (ret) {
6233 errno = ret;
6234 PERROR("pthread_join");
6235 retval = -1;
6236 }
6237 }
6238exit_kernel:
6239
6240 ret = pthread_join(agent_reg_thread, &status);
6241 if (ret) {
6242 errno = ret;
6243 PERROR("pthread_join agent");
6244 retval = -1;
6245 }
6246exit_agent_reg:
6247
6248 ret = pthread_join(apps_notify_thread, &status);
6249 if (ret) {
6250 errno = ret;
6251 PERROR("pthread_join apps notify");
6252 retval = -1;
6253 }
6254exit_apps_notify:
6255
6256 ret = pthread_join(apps_thread, &status);
6257 if (ret) {
6258 errno = ret;
6259 PERROR("pthread_join apps");
6260 retval = -1;
6261 }
6262exit_apps:
6263
6264 ret = pthread_join(reg_apps_thread, &status);
6265 if (ret) {
6266 errno = ret;
6267 PERROR("pthread_join");
6268 retval = -1;
6269 }
6270exit_reg_apps:
6271
6272 /*
6273 * Join dispatch thread after joining reg_apps_thread to ensure
6274 * we don't leak applications in the queue.
6275 */
6276 ret = pthread_join(dispatch_thread, &status);
6277 if (ret) {
6278 errno = ret;
6279 PERROR("pthread_join");
6280 retval = -1;
6281 }
6282exit_dispatch:
6283
6284 ret = pthread_join(client_thread, &status);
6285 if (ret) {
6286 errno = ret;
6287 PERROR("pthread_join");
6288 retval = -1;
6289 }
6290
6291exit_client:
6292 ret = pthread_join(notification_thread, &status);
6293 if (ret) {
6294 errno = ret;
6295 PERROR("pthread_join notification thread");
6296 retval = -1;
6297 }
6298
6299exit_notification:
6300 ret = pthread_join(health_thread, &status);
6301 if (ret) {
6302 errno = ret;
6303 PERROR("pthread_join health thread");
6304 retval = -1;
6305 }
6306
6307exit_health:
6308exit_init_data:
6309 /*
6310 * Wait for all pending call_rcu work to complete before tearing
6311 * down data structures. call_rcu worker may be trying to
6312 * perform lookups in those structures.
6313 */
6314 rcu_barrier();
6315 /*
6316 * sessiond_cleanup() is called when no other thread is running, except
6317 * the ht_cleanup thread, which is needed to destroy the hash tables.
6318 */
6319 rcu_thread_online();
6320 sessiond_cleanup();
6321 rcu_thread_offline();
6322 rcu_unregister_thread();
6323
6324 /*
6325 * Ensure all prior call_rcu are done. call_rcu callbacks may push
6326 * hash tables to the ht_cleanup thread. Therefore, we ensure that
6327 * the queue is empty before shutting down the clean-up thread.
6328 */
6329 rcu_barrier();
6330
6331 ret = fini_ht_cleanup_thread(&ht_cleanup_thread);
6332 if (ret) {
6333 retval = -1;
6334 }
6335 lttng_pipe_destroy(ust32_channel_monitor_pipe);
6336 lttng_pipe_destroy(ust64_channel_monitor_pipe);
6337 lttng_pipe_destroy(kernel_channel_monitor_pipe);
6338exit_ht_cleanup:
6339
6340 health_app_destroy(health_sessiond);
6341exit_health_sessiond_cleanup:
6342exit_create_run_as_worker_cleanup:
6343
6344exit_options:
6345 sessiond_cleanup_options();
6346
6347exit_set_signal_handler:
6348 if (!retval) {
6349 exit(EXIT_SUCCESS);
6350 } else {
6351 exit(EXIT_FAILURE);
6352 }
6353}
This page took 0.047409 seconds and 5 git commands to generate.