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>
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.
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.
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.
32 #include <sys/mount.h>
33 #include <sys/resource.h>
34 #include <sys/socket.h>
36 #include <sys/types.h>
38 #include <urcu/uatomic.h>
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 #include <common/dynamic-buffer.h>
54 #include "lttng-sessiond.h"
55 #include "buffer-registry.h"
62 #include "kernel-consumer.h"
66 #include "ust-consumer.h"
69 #include "health-sessiond.h"
70 #include "testpoint.h"
71 #include "ust-thread.h"
72 #include "agent-thread.h"
74 #include "load-session-thread.h"
77 #include "ht-cleanup.h"
79 #define CONSUMERD_FILE "lttng-consumerd"
82 static const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
83 static int tracing_group_name_override
;
84 static char *opt_pidfile
;
85 static int opt_sig_parent
;
86 static int opt_verbose_consumer
;
87 static int opt_daemon
, opt_background
;
88 static int opt_no_kernel
;
89 static char *opt_load_session_path
;
90 static pid_t ppid
; /* Parent PID for --sig-parent option */
91 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
93 static int lockfile_fd
= -1;
94 static int opt_print_version
;
96 /* Set to 1 when a SIGUSR1 signal is received. */
97 static int recv_child_signal
;
100 * Consumer daemon specific control data. Every value not initialized here is
101 * set to 0 by the static definition.
103 static struct consumer_data kconsumer_data
= {
104 .type
= LTTNG_CONSUMER_KERNEL
,
105 .err_unix_sock_path
= DEFAULT_KCONSUMERD_ERR_SOCK_PATH
,
106 .cmd_unix_sock_path
= DEFAULT_KCONSUMERD_CMD_SOCK_PATH
,
109 .pid_mutex
= PTHREAD_MUTEX_INITIALIZER
,
110 .lock
= PTHREAD_MUTEX_INITIALIZER
,
111 .cond
= PTHREAD_COND_INITIALIZER
,
112 .cond_mutex
= PTHREAD_MUTEX_INITIALIZER
,
114 static 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
,
120 .pid_mutex
= PTHREAD_MUTEX_INITIALIZER
,
121 .lock
= PTHREAD_MUTEX_INITIALIZER
,
122 .cond
= PTHREAD_COND_INITIALIZER
,
123 .cond_mutex
= PTHREAD_MUTEX_INITIALIZER
,
125 static struct consumer_data ustconsumer32_data
= {
126 .type
= LTTNG_CONSUMER32_UST
,
127 .err_unix_sock_path
= DEFAULT_USTCONSUMERD32_ERR_SOCK_PATH
,
128 .cmd_unix_sock_path
= DEFAULT_USTCONSUMERD32_CMD_SOCK_PATH
,
131 .pid_mutex
= PTHREAD_MUTEX_INITIALIZER
,
132 .lock
= PTHREAD_MUTEX_INITIALIZER
,
133 .cond
= PTHREAD_COND_INITIALIZER
,
134 .cond_mutex
= PTHREAD_MUTEX_INITIALIZER
,
137 /* Command line options */
138 static const struct option long_options
[] = {
139 { "client-sock", required_argument
, 0, 'c' },
140 { "apps-sock", required_argument
, 0, 'a' },
141 { "kconsumerd-cmd-sock", required_argument
, 0, '\0' },
142 { "kconsumerd-err-sock", required_argument
, 0, '\0' },
143 { "ustconsumerd32-cmd-sock", required_argument
, 0, '\0' },
144 { "ustconsumerd32-err-sock", required_argument
, 0, '\0' },
145 { "ustconsumerd64-cmd-sock", required_argument
, 0, '\0' },
146 { "ustconsumerd64-err-sock", required_argument
, 0, '\0' },
147 { "consumerd32-path", required_argument
, 0, '\0' },
148 { "consumerd32-libdir", required_argument
, 0, '\0' },
149 { "consumerd64-path", required_argument
, 0, '\0' },
150 { "consumerd64-libdir", required_argument
, 0, '\0' },
151 { "daemonize", no_argument
, 0, 'd' },
152 { "background", no_argument
, 0, 'b' },
153 { "sig-parent", no_argument
, 0, 'S' },
154 { "help", no_argument
, 0, 'h' },
155 { "group", required_argument
, 0, 'g' },
156 { "version", no_argument
, 0, 'V' },
157 { "quiet", no_argument
, 0, 'q' },
158 { "verbose", no_argument
, 0, 'v' },
159 { "verbose-consumer", no_argument
, 0, '\0' },
160 { "no-kernel", no_argument
, 0, '\0' },
161 { "pidfile", required_argument
, 0, 'p' },
162 { "agent-tcp-port", required_argument
, 0, '\0' },
163 { "config", required_argument
, 0, 'f' },
164 { "load", required_argument
, 0, 'l' },
165 { "kmod-probes", required_argument
, 0, '\0' },
166 { "extra-kmod-probes", required_argument
, 0, '\0' },
170 /* Command line options to ignore from configuration file */
171 static const char *config_ignore_options
[] = { "help", "version", "config" };
173 /* Shared between threads */
174 static int dispatch_thread_exit
;
176 /* Global application Unix socket path */
177 static char apps_unix_sock_path
[PATH_MAX
];
178 /* Global client Unix socket path */
179 static char client_unix_sock_path
[PATH_MAX
];
180 /* global wait shm path for UST */
181 static char wait_shm_path
[PATH_MAX
];
182 /* Global health check unix path */
183 static char health_unix_sock_path
[PATH_MAX
];
185 /* Sockets and FDs */
186 static int client_sock
= -1;
187 static int apps_sock
= -1;
188 int kernel_tracer_fd
= -1;
189 static int kernel_poll_pipe
[2] = { -1, -1 };
192 * Quit pipe for all threads. This permits a single cancellation point
193 * for all threads when receiving an event on the pipe.
195 static int thread_quit_pipe
[2] = { -1, -1 };
198 * This pipe is used to inform the thread managing application communication
199 * that a command is queued and ready to be processed.
201 static int apps_cmd_pipe
[2] = { -1, -1 };
203 int apps_cmd_notify_pipe
[2] = { -1, -1 };
205 /* Pthread, Mutexes and Semaphores */
206 static pthread_t apps_thread
;
207 static pthread_t apps_notify_thread
;
208 static pthread_t reg_apps_thread
;
209 static pthread_t client_thread
;
210 static pthread_t kernel_thread
;
211 static pthread_t dispatch_thread
;
212 static pthread_t health_thread
;
213 static pthread_t ht_cleanup_thread
;
214 static pthread_t agent_reg_thread
;
215 static pthread_t load_session_thread
;
218 * UST registration command queue. This queue is tied with a futex and uses a N
219 * wakers / 1 waiter implemented and detailed in futex.c/.h
221 * The thread_registration_apps and thread_dispatch_ust_registration uses this
222 * queue along with the wait/wake scheme. The thread_manage_apps receives down
223 * the line new application socket and monitors it for any I/O error or clean
224 * close that triggers an unregistration of the application.
226 static struct ust_cmd_queue ust_cmd_queue
;
229 * Pointer initialized before thread creation.
231 * This points to the tracing session list containing the session count and a
232 * mutex lock. The lock MUST be taken if you iterate over the list. The lock
233 * MUST NOT be taken if you call a public function in session.c.
235 * The lock is nested inside the structure: session_list_ptr->lock. Please use
236 * session_lock_list and session_unlock_list for lock acquisition.
238 static struct ltt_session_list
*session_list_ptr
;
240 int ust_consumerd64_fd
= -1;
241 int ust_consumerd32_fd
= -1;
243 static const char *consumerd32_bin
= CONFIG_CONSUMERD32_BIN
;
244 static const char *consumerd64_bin
= CONFIG_CONSUMERD64_BIN
;
245 static const char *consumerd32_libdir
= CONFIG_CONSUMERD32_LIBDIR
;
246 static const char *consumerd64_libdir
= CONFIG_CONSUMERD64_LIBDIR
;
247 static int consumerd32_bin_override
;
248 static int consumerd64_bin_override
;
249 static int consumerd32_libdir_override
;
250 static int consumerd64_libdir_override
;
252 static const char *module_proc_lttng
= "/proc/lttng";
255 * Consumer daemon state which is changed when spawning it, killing it or in
256 * case of a fatal error.
258 enum consumerd_state
{
259 CONSUMER_STARTED
= 1,
260 CONSUMER_STOPPED
= 2,
265 * This consumer daemon state is used to validate if a client command will be
266 * able to reach the consumer. If not, the client is informed. For instance,
267 * doing a "lttng start" when the consumer state is set to ERROR will return an
268 * error to the client.
270 * The following example shows a possible race condition of this scheme:
272 * consumer thread error happens
274 * client cmd checks state -> still OK
275 * consumer thread exit, sets error
276 * client cmd try to talk to consumer
279 * However, since the consumer is a different daemon, we have no way of making
280 * sure the command will reach it safely even with this state flag. This is why
281 * we consider that up to the state validation during command processing, the
282 * command is safe. After that, we can not guarantee the correctness of the
283 * client request vis-a-vis the consumer.
285 static enum consumerd_state ust_consumerd_state
;
286 static enum consumerd_state kernel_consumerd_state
;
289 * Socket timeout for receiving and sending in seconds.
291 static int app_socket_timeout
;
293 /* Set in main() with the current page size. */
296 /* Application health monitoring */
297 struct health_app
*health_sessiond
;
299 /* Agent TCP port for registration. Used by the agent thread. */
300 unsigned int agent_tcp_port
= DEFAULT_AGENT_TCP_PORT
;
302 /* Am I root or not. */
303 int is_root
; /* Set to 1 if the daemon is running as root */
305 const char * const config_section_name
= "sessiond";
307 /* Load session thread information to operate. */
308 struct load_session_thread_data
*load_info
;
310 /* Global hash tables */
311 struct lttng_ht
*agent_apps_ht_by_sock
= NULL
;
314 * Whether sessiond is ready for commands/health check requests.
315 * NR_LTTNG_SESSIOND_READY must match the number of calls to
316 * sessiond_notify_ready().
318 #define NR_LTTNG_SESSIOND_READY 4
319 int lttng_sessiond_ready
= NR_LTTNG_SESSIOND_READY
;
321 int sessiond_check_thread_quit_pipe(int fd
, uint32_t events
)
323 return (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) ? 1 : 0;
326 /* Notify parents that we are ready for cmd and health check */
328 void sessiond_notify_ready(void)
330 if (uatomic_sub_return(<tng_sessiond_ready
, 1) == 0) {
332 * Notify parent pid that we are ready to accept command
333 * for client side. This ppid is the one from the
334 * external process that spawned us.
336 if (opt_sig_parent
) {
341 * Notify the parent of the fork() process that we are
344 if (opt_daemon
|| opt_background
) {
345 kill(child_ppid
, SIGUSR1
);
351 void setup_consumerd_path(void)
353 const char *bin
, *libdir
;
356 * Allow INSTALL_BIN_PATH to be used as a target path for the
357 * native architecture size consumer if CONFIG_CONSUMER*_PATH
358 * has not been defined.
360 #if (CAA_BITS_PER_LONG == 32)
361 if (!consumerd32_bin
[0]) {
362 consumerd32_bin
= INSTALL_BIN_PATH
"/" CONSUMERD_FILE
;
364 if (!consumerd32_libdir
[0]) {
365 consumerd32_libdir
= INSTALL_LIB_PATH
;
367 #elif (CAA_BITS_PER_LONG == 64)
368 if (!consumerd64_bin
[0]) {
369 consumerd64_bin
= INSTALL_BIN_PATH
"/" CONSUMERD_FILE
;
371 if (!consumerd64_libdir
[0]) {
372 consumerd64_libdir
= INSTALL_LIB_PATH
;
375 #error "Unknown bitness"
379 * runtime env. var. overrides the build default.
381 bin
= lttng_secure_getenv("LTTNG_CONSUMERD32_BIN");
383 consumerd32_bin
= bin
;
385 bin
= lttng_secure_getenv("LTTNG_CONSUMERD64_BIN");
387 consumerd64_bin
= bin
;
389 libdir
= lttng_secure_getenv("LTTNG_CONSUMERD32_LIBDIR");
391 consumerd32_libdir
= libdir
;
393 libdir
= lttng_secure_getenv("LTTNG_CONSUMERD64_LIBDIR");
395 consumerd64_libdir
= libdir
;
400 int __sessiond_set_thread_pollset(struct lttng_poll_event
*events
, size_t size
,
407 ret
= lttng_poll_create(events
, size
, LTTNG_CLOEXEC
);
413 ret
= lttng_poll_add(events
, a_pipe
[0], LPOLLIN
| LPOLLERR
);
425 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
427 int sessiond_set_thread_pollset(struct lttng_poll_event
*events
, size_t size
)
429 return __sessiond_set_thread_pollset(events
, size
, thread_quit_pipe
);
433 * Init thread quit pipe.
435 * Return -1 on error or 0 if all pipes are created.
437 static int __init_thread_quit_pipe(int *a_pipe
)
443 PERROR("thread quit pipe");
447 for (i
= 0; i
< 2; i
++) {
448 ret
= fcntl(a_pipe
[i
], F_SETFD
, FD_CLOEXEC
);
459 static int init_thread_quit_pipe(void)
461 return __init_thread_quit_pipe(thread_quit_pipe
);
465 * Stop all threads by closing the thread quit pipe.
467 static void stop_threads(void)
471 /* Stopping all threads */
472 DBG("Terminating all threads");
473 ret
= notify_thread_pipe(thread_quit_pipe
[1]);
475 ERR("write error on thread quit pipe");
478 /* Dispatch thread */
479 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
480 futex_nto1_wake(&ust_cmd_queue
.futex
);
484 * Close every consumer sockets.
486 static void close_consumer_sockets(void)
490 if (kconsumer_data
.err_sock
>= 0) {
491 ret
= close(kconsumer_data
.err_sock
);
493 PERROR("kernel consumer err_sock close");
496 if (ustconsumer32_data
.err_sock
>= 0) {
497 ret
= close(ustconsumer32_data
.err_sock
);
499 PERROR("UST consumerd32 err_sock close");
502 if (ustconsumer64_data
.err_sock
>= 0) {
503 ret
= close(ustconsumer64_data
.err_sock
);
505 PERROR("UST consumerd64 err_sock close");
508 if (kconsumer_data
.cmd_sock
>= 0) {
509 ret
= close(kconsumer_data
.cmd_sock
);
511 PERROR("kernel consumer cmd_sock close");
514 if (ustconsumer32_data
.cmd_sock
>= 0) {
515 ret
= close(ustconsumer32_data
.cmd_sock
);
517 PERROR("UST consumerd32 cmd_sock close");
520 if (ustconsumer64_data
.cmd_sock
>= 0) {
521 ret
= close(ustconsumer64_data
.cmd_sock
);
523 PERROR("UST consumerd64 cmd_sock close");
529 * Generate the full lock file path using the rundir.
531 * Return the snprintf() return value thus a negative value is an error.
533 static int generate_lock_file_path(char *path
, size_t len
)
540 /* Build lockfile path from rundir. */
541 ret
= snprintf(path
, len
, "%s/" DEFAULT_LTTNG_SESSIOND_LOCKFILE
, rundir
);
543 PERROR("snprintf lockfile path");
550 * Wait on consumer process termination.
552 * Need to be called with the consumer data lock held or from a context
553 * ensuring no concurrent access to data (e.g: cleanup).
555 static void wait_consumer(struct consumer_data
*consumer_data
)
560 if (consumer_data
->pid
<= 0) {
564 DBG("Waiting for complete teardown of consumerd (PID: %d)",
566 ret
= waitpid(consumer_data
->pid
, &status
, 0);
568 PERROR("consumerd waitpid pid: %d", consumer_data
->pid
)
569 } else if (!WIFEXITED(status
)) {
570 ERR("consumerd termination with error: %d",
573 consumer_data
->pid
= 0;
577 * Cleanup the session daemon's data structures.
579 static void sessiond_cleanup(void)
582 struct ltt_session
*sess
, *stmp
;
585 DBG("Cleanup sessiond");
588 * Close the thread quit pipe. It has already done its job,
589 * since we are now called.
591 utils_close_pipe(thread_quit_pipe
);
594 * If opt_pidfile is undefined, the default file will be wiped when
595 * removing the rundir.
598 ret
= remove(opt_pidfile
);
600 PERROR("remove pidfile %s", opt_pidfile
);
604 DBG("Removing sessiond and consumerd content of directory %s", rundir
);
607 snprintf(path
, PATH_MAX
,
609 rundir
, DEFAULT_LTTNG_SESSIOND_PIDFILE
);
610 DBG("Removing %s", path
);
613 snprintf(path
, PATH_MAX
, "%s/%s", rundir
,
614 DEFAULT_LTTNG_SESSIOND_AGENTPORT_FILE
);
615 DBG("Removing %s", path
);
619 snprintf(path
, PATH_MAX
,
620 DEFAULT_KCONSUMERD_ERR_SOCK_PATH
,
622 DBG("Removing %s", path
);
625 snprintf(path
, PATH_MAX
,
626 DEFAULT_KCONSUMERD_PATH
,
628 DBG("Removing directory %s", path
);
631 /* ust consumerd 32 */
632 snprintf(path
, PATH_MAX
,
633 DEFAULT_USTCONSUMERD32_ERR_SOCK_PATH
,
635 DBG("Removing %s", path
);
638 snprintf(path
, PATH_MAX
,
639 DEFAULT_USTCONSUMERD32_PATH
,
641 DBG("Removing directory %s", path
);
644 /* ust consumerd 64 */
645 snprintf(path
, PATH_MAX
,
646 DEFAULT_USTCONSUMERD64_ERR_SOCK_PATH
,
648 DBG("Removing %s", path
);
651 snprintf(path
, PATH_MAX
,
652 DEFAULT_USTCONSUMERD64_PATH
,
654 DBG("Removing directory %s", path
);
657 DBG("Cleaning up all sessions");
659 /* Destroy session list mutex */
660 if (session_list_ptr
!= NULL
) {
661 pthread_mutex_destroy(&session_list_ptr
->lock
);
663 /* Cleanup ALL session */
664 cds_list_for_each_entry_safe(sess
, stmp
,
665 &session_list_ptr
->head
, list
) {
666 cmd_destroy_session(sess
, kernel_poll_pipe
[1]);
670 wait_consumer(&kconsumer_data
);
671 wait_consumer(&ustconsumer64_data
);
672 wait_consumer(&ustconsumer32_data
);
674 DBG("Cleaning up all agent apps");
675 agent_app_ht_clean();
677 DBG("Closing all UST sockets");
678 ust_app_clean_list();
679 buffer_reg_destroy_registries();
681 if (is_root
&& !opt_no_kernel
) {
682 DBG2("Closing kernel fd");
683 if (kernel_tracer_fd
>= 0) {
684 ret
= close(kernel_tracer_fd
);
689 DBG("Unloading kernel modules");
690 modprobe_remove_lttng_all();
694 close_consumer_sockets();
697 load_session_destroy_data(load_info
);
702 * Cleanup lock file by deleting it and finaly closing it which will
703 * release the file system lock.
705 if (lockfile_fd
>= 0) {
706 char lockfile_path
[PATH_MAX
];
708 ret
= generate_lock_file_path(lockfile_path
,
709 sizeof(lockfile_path
));
711 ret
= remove(lockfile_path
);
713 PERROR("remove lock file");
715 ret
= close(lockfile_fd
);
717 PERROR("close lock file");
723 * We do NOT rmdir rundir because there are other processes
724 * using it, for instance lttng-relayd, which can start in
725 * parallel with this teardown.
732 * Cleanup the daemon's option data structures.
734 static void sessiond_cleanup_options(void)
736 DBG("Cleaning up options");
739 * If the override option is set, the pointer points to a *non* const
740 * thus freeing it even though the variable type is set to const.
742 if (tracing_group_name_override
) {
743 free((void *) tracing_group_name
);
745 if (consumerd32_bin_override
) {
746 free((void *) consumerd32_bin
);
748 if (consumerd64_bin_override
) {
749 free((void *) consumerd64_bin
);
751 if (consumerd32_libdir_override
) {
752 free((void *) consumerd32_libdir
);
754 if (consumerd64_libdir_override
) {
755 free((void *) consumerd64_libdir
);
759 free(opt_load_session_path
);
760 free(kmod_probes_list
);
761 free(kmod_extra_probes_list
);
763 run_as_destroy_worker();
767 * Send data on a unix socket using the liblttsessiondcomm API.
769 * Return lttcomm error code.
771 static int send_unix_sock(int sock
, void *buf
, size_t len
)
773 /* Check valid length */
778 return lttcomm_send_unix_sock(sock
, buf
, len
);
782 * Free memory of a command context structure.
784 static void clean_command_ctx(struct command_ctx
**cmd_ctx
)
786 DBG("Clean command context structure");
788 if ((*cmd_ctx
)->llm
) {
789 free((*cmd_ctx
)->llm
);
791 if ((*cmd_ctx
)->lsm
) {
792 free((*cmd_ctx
)->lsm
);
800 * Notify UST applications using the shm mmap futex.
802 static int notify_ust_apps(int active
)
806 DBG("Notifying applications of session daemon state: %d", active
);
808 /* See shm.c for this call implying mmap, shm and futex calls */
809 wait_shm_mmap
= shm_ust_get_mmap(wait_shm_path
, is_root
);
810 if (wait_shm_mmap
== NULL
) {
814 /* Wake waiting process */
815 futex_wait_update((int32_t *) wait_shm_mmap
, active
);
817 /* Apps notified successfully */
825 * Setup the outgoing data buffer for the response (llm) by allocating the
826 * right amount of memory and copying the original information from the lsm
829 * Return 0 on success, negative value on error.
831 static int setup_lttng_msg(struct command_ctx
*cmd_ctx
,
832 const void *payload_buf
, size_t payload_len
,
833 const void *cmd_header_buf
, size_t cmd_header_len
)
836 const size_t header_len
= sizeof(struct lttcomm_lttng_msg
);
837 const size_t cmd_header_offset
= header_len
;
838 const size_t payload_offset
= cmd_header_offset
+ cmd_header_len
;
839 const size_t total_msg_size
= header_len
+ cmd_header_len
+ payload_len
;
841 cmd_ctx
->llm
= zmalloc(total_msg_size
);
843 if (cmd_ctx
->llm
== NULL
) {
849 /* Copy common data */
850 cmd_ctx
->llm
->cmd_type
= cmd_ctx
->lsm
->cmd_type
;
851 cmd_ctx
->llm
->pid
= cmd_ctx
->lsm
->domain
.attr
.pid
;
852 cmd_ctx
->llm
->cmd_header_size
= cmd_header_len
;
853 cmd_ctx
->llm
->data_size
= payload_len
;
854 cmd_ctx
->lttng_msg_size
= total_msg_size
;
856 /* Copy command header */
857 if (cmd_header_len
) {
858 memcpy(((uint8_t *) cmd_ctx
->llm
) + cmd_header_offset
, cmd_header_buf
,
864 memcpy(((uint8_t *) cmd_ctx
->llm
) + payload_offset
, payload_buf
,
873 * Version of setup_lttng_msg() without command header.
875 static int setup_lttng_msg_no_cmd_header(struct command_ctx
*cmd_ctx
,
876 void *payload_buf
, size_t payload_len
)
878 return setup_lttng_msg(cmd_ctx
, payload_buf
, payload_len
, NULL
, 0);
881 * Update the kernel poll set of all channel fd available over all tracing
882 * session. Add the wakeup pipe at the end of the set.
884 static int update_kernel_poll(struct lttng_poll_event
*events
)
887 struct ltt_session
*session
;
888 struct ltt_kernel_channel
*channel
;
890 DBG("Updating kernel poll set");
893 cds_list_for_each_entry(session
, &session_list_ptr
->head
, list
) {
894 session_lock(session
);
895 if (session
->kernel_session
== NULL
) {
896 session_unlock(session
);
900 cds_list_for_each_entry(channel
,
901 &session
->kernel_session
->channel_list
.head
, list
) {
902 /* Add channel fd to the kernel poll set */
903 ret
= lttng_poll_add(events
, channel
->fd
, LPOLLIN
| LPOLLRDNORM
);
905 session_unlock(session
);
908 DBG("Channel fd %d added to kernel set", channel
->fd
);
910 session_unlock(session
);
912 session_unlock_list();
917 session_unlock_list();
922 * Find the channel fd from 'fd' over all tracing session. When found, check
923 * for new channel stream and send those stream fds to the kernel consumer.
925 * Useful for CPU hotplug feature.
927 static int update_kernel_stream(struct consumer_data
*consumer_data
, int fd
)
930 struct ltt_session
*session
;
931 struct ltt_kernel_session
*ksess
;
932 struct ltt_kernel_channel
*channel
;
934 DBG("Updating kernel streams for channel fd %d", fd
);
937 cds_list_for_each_entry(session
, &session_list_ptr
->head
, list
) {
938 session_lock(session
);
939 if (session
->kernel_session
== NULL
) {
940 session_unlock(session
);
943 ksess
= session
->kernel_session
;
945 cds_list_for_each_entry(channel
,
946 &ksess
->channel_list
.head
, list
) {
947 struct lttng_ht_iter iter
;
948 struct consumer_socket
*socket
;
950 if (channel
->fd
!= fd
) {
953 DBG("Channel found, updating kernel streams");
954 ret
= kernel_open_channel_stream(channel
);
958 /* Update the stream global counter */
959 ksess
->stream_count_global
+= ret
;
962 * Have we already sent fds to the consumer? If yes, it
963 * means that tracing is started so it is safe to send
964 * our updated stream fds.
966 if (ksess
->consumer_fds_sent
!= 1
967 || ksess
->consumer
== NULL
) {
973 cds_lfht_for_each_entry(ksess
->consumer
->socks
->ht
,
974 &iter
.iter
, socket
, node
.node
) {
975 pthread_mutex_lock(socket
->lock
);
976 ret
= kernel_consumer_send_channel_stream(socket
,
978 session
->output_traces
? 1 : 0);
979 pthread_mutex_unlock(socket
->lock
);
987 session_unlock(session
);
989 session_unlock_list();
993 session_unlock(session
);
994 session_unlock_list();
999 * For each tracing session, update newly registered apps. The session list
1000 * lock MUST be acquired before calling this.
1002 static void update_ust_app(int app_sock
)
1004 struct ltt_session
*sess
, *stmp
;
1006 /* Consumer is in an ERROR state. Stop any application update. */
1007 if (uatomic_read(&ust_consumerd_state
) == CONSUMER_ERROR
) {
1008 /* Stop the update process since the consumer is dead. */
1012 /* For all tracing session(s) */
1013 cds_list_for_each_entry_safe(sess
, stmp
, &session_list_ptr
->head
, list
) {
1014 struct ust_app
*app
;
1017 if (!sess
->ust_session
) {
1018 goto unlock_session
;
1022 assert(app_sock
>= 0);
1023 app
= ust_app_find_by_sock(app_sock
);
1026 * Application can be unregistered before so
1027 * this is possible hence simply stopping the
1030 DBG3("UST app update failed to find app sock %d",
1034 ust_app_global_update(sess
->ust_session
, app
);
1038 session_unlock(sess
);
1043 * This thread manage event coming from the kernel.
1045 * Features supported in this thread:
1048 static void *thread_manage_kernel(void *data
)
1050 int ret
, i
, pollfd
, update_poll_flag
= 1, err
= -1;
1051 uint32_t revents
, nb_fd
;
1053 struct lttng_poll_event events
;
1055 DBG("[thread] Thread manage kernel started");
1057 health_register(health_sessiond
, HEALTH_SESSIOND_TYPE_KERNEL
);
1060 * This first step of the while is to clean this structure which could free
1061 * non NULL pointers so initialize it before the loop.
1063 lttng_poll_init(&events
);
1065 if (testpoint(sessiond_thread_manage_kernel
)) {
1066 goto error_testpoint
;
1069 health_code_update();
1071 if (testpoint(sessiond_thread_manage_kernel_before_loop
)) {
1072 goto error_testpoint
;
1076 health_code_update();
1078 if (update_poll_flag
== 1) {
1079 /* Clean events object. We are about to populate it again. */
1080 lttng_poll_clean(&events
);
1082 ret
= sessiond_set_thread_pollset(&events
, 2);
1084 goto error_poll_create
;
1087 ret
= lttng_poll_add(&events
, kernel_poll_pipe
[0], LPOLLIN
);
1092 /* This will add the available kernel channel if any. */
1093 ret
= update_kernel_poll(&events
);
1097 update_poll_flag
= 0;
1100 DBG("Thread kernel polling");
1102 /* Poll infinite value of time */
1104 health_poll_entry();
1105 ret
= lttng_poll_wait(&events
, -1);
1106 DBG("Thread kernel return from poll on %d fds",
1107 LTTNG_POLL_GETNB(&events
));
1111 * Restart interrupted system call.
1113 if (errno
== EINTR
) {
1117 } else if (ret
== 0) {
1118 /* Should not happen since timeout is infinite */
1119 ERR("Return value of poll is 0 with an infinite timeout.\n"
1120 "This should not have happened! Continuing...");
1126 for (i
= 0; i
< nb_fd
; i
++) {
1127 /* Fetch once the poll data */
1128 revents
= LTTNG_POLL_GETEV(&events
, i
);
1129 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
1131 health_code_update();
1134 /* No activity for this FD (poll implementation). */
1138 /* Thread quit pipe has been closed. Killing thread. */
1139 ret
= sessiond_check_thread_quit_pipe(pollfd
, revents
);
1145 /* Check for data on kernel pipe */
1146 if (revents
& LPOLLIN
) {
1147 if (pollfd
== kernel_poll_pipe
[0]) {
1148 (void) lttng_read(kernel_poll_pipe
[0],
1151 * Ret value is useless here, if this pipe gets any actions an
1152 * update is required anyway.
1154 update_poll_flag
= 1;
1158 * New CPU detected by the kernel. Adding kernel stream to
1159 * kernel session and updating the kernel consumer
1161 ret
= update_kernel_stream(&kconsumer_data
, pollfd
);
1167 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1168 update_poll_flag
= 1;
1171 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1179 lttng_poll_clean(&events
);
1182 utils_close_pipe(kernel_poll_pipe
);
1183 kernel_poll_pipe
[0] = kernel_poll_pipe
[1] = -1;
1186 ERR("Health error occurred in %s", __func__
);
1187 WARN("Kernel thread died unexpectedly. "
1188 "Kernel tracing can continue but CPU hotplug is disabled.");
1190 health_unregister(health_sessiond
);
1191 DBG("Kernel thread dying");
1196 * Signal pthread condition of the consumer data that the thread.
1198 static void signal_consumer_condition(struct consumer_data
*data
, int state
)
1200 pthread_mutex_lock(&data
->cond_mutex
);
1203 * The state is set before signaling. It can be any value, it's the waiter
1204 * job to correctly interpret this condition variable associated to the
1205 * consumer pthread_cond.
1207 * A value of 0 means that the corresponding thread of the consumer data
1208 * was not started. 1 indicates that the thread has started and is ready
1209 * for action. A negative value means that there was an error during the
1212 data
->consumer_thread_is_ready
= state
;
1213 (void) pthread_cond_signal(&data
->cond
);
1215 pthread_mutex_unlock(&data
->cond_mutex
);
1219 * This thread manage the consumer error sent back to the session daemon.
1221 static void *thread_manage_consumer(void *data
)
1223 int sock
= -1, i
, ret
, pollfd
, err
= -1, should_quit
= 0;
1224 uint32_t revents
, nb_fd
;
1225 enum lttcomm_return_code code
;
1226 struct lttng_poll_event events
;
1227 struct consumer_data
*consumer_data
= data
;
1229 DBG("[thread] Manage consumer started");
1231 rcu_register_thread();
1232 rcu_thread_online();
1234 health_register(health_sessiond
, HEALTH_SESSIOND_TYPE_CONSUMER
);
1236 health_code_update();
1239 * Pass 3 as size here for the thread quit pipe, consumerd_err_sock and the
1240 * metadata_sock. Nothing more will be added to this poll set.
1242 ret
= sessiond_set_thread_pollset(&events
, 3);
1248 * The error socket here is already in a listening state which was done
1249 * just before spawning this thread to avoid a race between the consumer
1250 * daemon exec trying to connect and the listen() call.
1252 ret
= lttng_poll_add(&events
, consumer_data
->err_sock
, LPOLLIN
| LPOLLRDHUP
);
1257 health_code_update();
1259 /* Infinite blocking call, waiting for transmission */
1261 health_poll_entry();
1263 if (testpoint(sessiond_thread_manage_consumer
)) {
1267 ret
= lttng_poll_wait(&events
, -1);
1271 * Restart interrupted system call.
1273 if (errno
== EINTR
) {
1281 for (i
= 0; i
< nb_fd
; i
++) {
1282 /* Fetch once the poll data */
1283 revents
= LTTNG_POLL_GETEV(&events
, i
);
1284 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
1286 health_code_update();
1289 /* No activity for this FD (poll implementation). */
1293 /* Thread quit pipe has been closed. Killing thread. */
1294 ret
= sessiond_check_thread_quit_pipe(pollfd
, revents
);
1300 /* Event on the registration socket */
1301 if (pollfd
== consumer_data
->err_sock
) {
1302 if (revents
& LPOLLIN
) {
1304 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1305 ERR("consumer err socket poll error");
1308 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1314 sock
= lttcomm_accept_unix_sock(consumer_data
->err_sock
);
1320 * Set the CLOEXEC flag. Return code is useless because either way, the
1323 (void) utils_set_fd_cloexec(sock
);
1325 health_code_update();
1327 DBG2("Receiving code from consumer err_sock");
1329 /* Getting status code from kconsumerd */
1330 ret
= lttcomm_recv_unix_sock(sock
, &code
,
1331 sizeof(enum lttcomm_return_code
));
1336 health_code_update();
1337 if (code
== LTTCOMM_CONSUMERD_COMMAND_SOCK_READY
) {
1338 /* Connect both socket, command and metadata. */
1339 consumer_data
->cmd_sock
=
1340 lttcomm_connect_unix_sock(consumer_data
->cmd_unix_sock_path
);
1341 consumer_data
->metadata_fd
=
1342 lttcomm_connect_unix_sock(consumer_data
->cmd_unix_sock_path
);
1343 if (consumer_data
->cmd_sock
< 0
1344 || consumer_data
->metadata_fd
< 0) {
1345 PERROR("consumer connect cmd socket");
1346 /* On error, signal condition and quit. */
1347 signal_consumer_condition(consumer_data
, -1);
1350 consumer_data
->metadata_sock
.fd_ptr
= &consumer_data
->metadata_fd
;
1351 /* Create metadata socket lock. */
1352 consumer_data
->metadata_sock
.lock
= zmalloc(sizeof(pthread_mutex_t
));
1353 if (consumer_data
->metadata_sock
.lock
== NULL
) {
1354 PERROR("zmalloc pthread mutex");
1357 pthread_mutex_init(consumer_data
->metadata_sock
.lock
, NULL
);
1359 signal_consumer_condition(consumer_data
, 1);
1360 DBG("Consumer command socket ready (fd: %d", consumer_data
->cmd_sock
);
1361 DBG("Consumer metadata socket ready (fd: %d)",
1362 consumer_data
->metadata_fd
);
1364 ERR("consumer error when waiting for SOCK_READY : %s",
1365 lttcomm_get_readable_code(-code
));
1369 /* Remove the consumerd error sock since we've established a connexion */
1370 ret
= lttng_poll_del(&events
, consumer_data
->err_sock
);
1375 /* Add new accepted error socket. */
1376 ret
= lttng_poll_add(&events
, sock
, LPOLLIN
| LPOLLRDHUP
);
1381 /* Add metadata socket that is successfully connected. */
1382 ret
= lttng_poll_add(&events
, consumer_data
->metadata_fd
,
1383 LPOLLIN
| LPOLLRDHUP
);
1388 health_code_update();
1390 /* Infinite blocking call, waiting for transmission */
1393 health_code_update();
1395 /* Exit the thread because the thread quit pipe has been triggered. */
1397 /* Not a health error. */
1402 health_poll_entry();
1403 ret
= lttng_poll_wait(&events
, -1);
1407 * Restart interrupted system call.
1409 if (errno
== EINTR
) {
1417 for (i
= 0; i
< nb_fd
; i
++) {
1418 /* Fetch once the poll data */
1419 revents
= LTTNG_POLL_GETEV(&events
, i
);
1420 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
1422 health_code_update();
1425 /* No activity for this FD (poll implementation). */
1430 * Thread quit pipe has been triggered, flag that we should stop
1431 * but continue the current loop to handle potential data from
1434 should_quit
= sessiond_check_thread_quit_pipe(pollfd
, revents
);
1436 if (pollfd
== sock
) {
1437 /* Event on the consumerd socket */
1438 if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)
1439 && !(revents
& LPOLLIN
)) {
1440 ERR("consumer err socket second poll error");
1443 health_code_update();
1444 /* Wait for any kconsumerd error */
1445 ret
= lttcomm_recv_unix_sock(sock
, &code
,
1446 sizeof(enum lttcomm_return_code
));
1448 ERR("consumer closed the command socket");
1452 ERR("consumer return code : %s",
1453 lttcomm_get_readable_code(-code
));
1456 } else if (pollfd
== consumer_data
->metadata_fd
) {
1457 if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)
1458 && !(revents
& LPOLLIN
)) {
1459 ERR("consumer err metadata socket second poll error");
1462 /* UST metadata requests */
1463 ret
= ust_consumer_metadata_request(
1464 &consumer_data
->metadata_sock
);
1466 ERR("Handling metadata request");
1470 /* No need for an else branch all FDs are tested prior. */
1472 health_code_update();
1478 * We lock here because we are about to close the sockets and some other
1479 * thread might be using them so get exclusive access which will abort all
1480 * other consumer command by other threads.
1482 pthread_mutex_lock(&consumer_data
->lock
);
1484 /* Immediately set the consumerd state to stopped */
1485 if (consumer_data
->type
== LTTNG_CONSUMER_KERNEL
) {
1486 uatomic_set(&kernel_consumerd_state
, CONSUMER_ERROR
);
1487 } else if (consumer_data
->type
== LTTNG_CONSUMER64_UST
||
1488 consumer_data
->type
== LTTNG_CONSUMER32_UST
) {
1489 uatomic_set(&ust_consumerd_state
, CONSUMER_ERROR
);
1491 /* Code flow error... */
1495 if (consumer_data
->err_sock
>= 0) {
1496 ret
= close(consumer_data
->err_sock
);
1500 consumer_data
->err_sock
= -1;
1502 if (consumer_data
->cmd_sock
>= 0) {
1503 ret
= close(consumer_data
->cmd_sock
);
1507 consumer_data
->cmd_sock
= -1;
1509 if (consumer_data
->metadata_sock
.fd_ptr
&&
1510 *consumer_data
->metadata_sock
.fd_ptr
>= 0) {
1511 ret
= close(*consumer_data
->metadata_sock
.fd_ptr
);
1523 unlink(consumer_data
->err_unix_sock_path
);
1524 unlink(consumer_data
->cmd_unix_sock_path
);
1525 pthread_mutex_unlock(&consumer_data
->lock
);
1527 /* Cleanup metadata socket mutex. */
1528 if (consumer_data
->metadata_sock
.lock
) {
1529 pthread_mutex_destroy(consumer_data
->metadata_sock
.lock
);
1530 free(consumer_data
->metadata_sock
.lock
);
1532 lttng_poll_clean(&events
);
1536 ERR("Health error occurred in %s", __func__
);
1538 health_unregister(health_sessiond
);
1539 DBG("consumer thread cleanup completed");
1541 rcu_thread_offline();
1542 rcu_unregister_thread();
1548 * This thread manage application communication.
1550 static void *thread_manage_apps(void *data
)
1552 int i
, ret
, pollfd
, err
= -1;
1554 uint32_t revents
, nb_fd
;
1555 struct lttng_poll_event events
;
1557 DBG("[thread] Manage application started");
1559 rcu_register_thread();
1560 rcu_thread_online();
1562 health_register(health_sessiond
, HEALTH_SESSIOND_TYPE_APP_MANAGE
);
1564 if (testpoint(sessiond_thread_manage_apps
)) {
1565 goto error_testpoint
;
1568 health_code_update();
1570 ret
= sessiond_set_thread_pollset(&events
, 2);
1572 goto error_poll_create
;
1575 ret
= lttng_poll_add(&events
, apps_cmd_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
1580 if (testpoint(sessiond_thread_manage_apps_before_loop
)) {
1584 health_code_update();
1587 DBG("Apps thread polling");
1589 /* Inifinite blocking call, waiting for transmission */
1591 health_poll_entry();
1592 ret
= lttng_poll_wait(&events
, -1);
1593 DBG("Apps thread return from poll on %d fds",
1594 LTTNG_POLL_GETNB(&events
));
1598 * Restart interrupted system call.
1600 if (errno
== EINTR
) {
1608 for (i
= 0; i
< nb_fd
; i
++) {
1609 /* Fetch once the poll data */
1610 revents
= LTTNG_POLL_GETEV(&events
, i
);
1611 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
1613 health_code_update();
1616 /* No activity for this FD (poll implementation). */
1620 /* Thread quit pipe has been closed. Killing thread. */
1621 ret
= sessiond_check_thread_quit_pipe(pollfd
, revents
);
1627 /* Inspect the apps cmd pipe */
1628 if (pollfd
== apps_cmd_pipe
[0]) {
1629 if (revents
& LPOLLIN
) {
1633 size_ret
= lttng_read(apps_cmd_pipe
[0], &sock
, sizeof(sock
));
1634 if (size_ret
< sizeof(sock
)) {
1635 PERROR("read apps cmd pipe");
1639 health_code_update();
1642 * Since this is a command socket (write then read),
1643 * we only monitor the error events of the socket.
1645 ret
= lttng_poll_add(&events
, sock
,
1646 LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
);
1651 DBG("Apps with sock %d added to poll set", sock
);
1652 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1653 ERR("Apps command pipe error");
1656 ERR("Unknown poll events %u for sock %d", revents
, pollfd
);
1661 * At this point, we know that a registered application made
1662 * the event at poll_wait.
1664 if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1665 /* Removing from the poll set */
1666 ret
= lttng_poll_del(&events
, pollfd
);
1671 /* Socket closed on remote end. */
1672 ust_app_unregister(pollfd
);
1674 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1679 health_code_update();
1685 lttng_poll_clean(&events
);
1688 utils_close_pipe(apps_cmd_pipe
);
1689 apps_cmd_pipe
[0] = apps_cmd_pipe
[1] = -1;
1692 * We don't clean the UST app hash table here since already registered
1693 * applications can still be controlled so let them be until the session
1694 * daemon dies or the applications stop.
1699 ERR("Health error occurred in %s", __func__
);
1701 health_unregister(health_sessiond
);
1702 DBG("Application communication apps thread cleanup complete");
1703 rcu_thread_offline();
1704 rcu_unregister_thread();
1709 * Send a socket to a thread This is called from the dispatch UST registration
1710 * thread once all sockets are set for the application.
1712 * The sock value can be invalid, we don't really care, the thread will handle
1713 * it and make the necessary cleanup if so.
1715 * On success, return 0 else a negative value being the errno message of the
1718 static int send_socket_to_thread(int fd
, int sock
)
1723 * It's possible that the FD is set as invalid with -1 concurrently just
1724 * before calling this function being a shutdown state of the thread.
1731 ret
= lttng_write(fd
, &sock
, sizeof(sock
));
1732 if (ret
< sizeof(sock
)) {
1733 PERROR("write apps pipe %d", fd
);
1740 /* All good. Don't send back the write positive ret value. */
1747 * Sanitize the wait queue of the dispatch registration thread meaning removing
1748 * invalid nodes from it. This is to avoid memory leaks for the case the UST
1749 * notify socket is never received.
1751 static void sanitize_wait_queue(struct ust_reg_wait_queue
*wait_queue
)
1753 int ret
, nb_fd
= 0, i
;
1754 unsigned int fd_added
= 0;
1755 struct lttng_poll_event events
;
1756 struct ust_reg_wait_node
*wait_node
= NULL
, *tmp_wait_node
;
1760 lttng_poll_init(&events
);
1762 /* Just skip everything for an empty queue. */
1763 if (!wait_queue
->count
) {
1767 ret
= lttng_poll_create(&events
, wait_queue
->count
, LTTNG_CLOEXEC
);
1772 cds_list_for_each_entry_safe(wait_node
, tmp_wait_node
,
1773 &wait_queue
->head
, head
) {
1774 assert(wait_node
->app
);
1775 ret
= lttng_poll_add(&events
, wait_node
->app
->sock
,
1776 LPOLLHUP
| LPOLLERR
);
1789 * Poll but don't block so we can quickly identify the faulty events and
1790 * clean them afterwards from the wait queue.
1792 ret
= lttng_poll_wait(&events
, 0);
1798 for (i
= 0; i
< nb_fd
; i
++) {
1799 /* Get faulty FD. */
1800 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
1801 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
1804 /* No activity for this FD (poll implementation). */
1808 cds_list_for_each_entry_safe(wait_node
, tmp_wait_node
,
1809 &wait_queue
->head
, head
) {
1810 if (pollfd
== wait_node
->app
->sock
&&
1811 (revents
& (LPOLLHUP
| LPOLLERR
))) {
1812 cds_list_del(&wait_node
->head
);
1813 wait_queue
->count
--;
1814 ust_app_destroy(wait_node
->app
);
1817 * Silence warning of use-after-free in
1818 * cds_list_for_each_entry_safe which uses
1819 * __typeof__(*wait_node).
1824 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1831 DBG("Wait queue sanitized, %d node were cleaned up", nb_fd
);
1835 lttng_poll_clean(&events
);
1839 lttng_poll_clean(&events
);
1841 ERR("Unable to sanitize wait queue");
1846 * Dispatch request from the registration threads to the application
1847 * communication thread.
1849 static void *thread_dispatch_ust_registration(void *data
)
1852 struct cds_wfcq_node
*node
;
1853 struct ust_command
*ust_cmd
= NULL
;
1854 struct ust_reg_wait_node
*wait_node
= NULL
, *tmp_wait_node
;
1855 struct ust_reg_wait_queue wait_queue
= {
1859 rcu_register_thread();
1861 health_register(health_sessiond
, HEALTH_SESSIOND_TYPE_APP_REG_DISPATCH
);
1863 if (testpoint(sessiond_thread_app_reg_dispatch
)) {
1864 goto error_testpoint
;
1867 health_code_update();
1869 CDS_INIT_LIST_HEAD(&wait_queue
.head
);
1871 DBG("[thread] Dispatch UST command started");
1874 health_code_update();
1876 /* Atomically prepare the queue futex */
1877 futex_nto1_prepare(&ust_cmd_queue
.futex
);
1879 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1884 struct ust_app
*app
= NULL
;
1888 * Make sure we don't have node(s) that have hung up before receiving
1889 * the notify socket. This is to clean the list in order to avoid
1890 * memory leaks from notify socket that are never seen.
1892 sanitize_wait_queue(&wait_queue
);
1894 health_code_update();
1895 /* Dequeue command for registration */
1896 node
= cds_wfcq_dequeue_blocking(&ust_cmd_queue
.head
, &ust_cmd_queue
.tail
);
1898 DBG("Woken up but nothing in the UST command queue");
1899 /* Continue thread execution */
1903 ust_cmd
= caa_container_of(node
, struct ust_command
, node
);
1905 DBG("Dispatching UST registration pid:%d ppid:%d uid:%d"
1906 " gid:%d sock:%d name:%s (version %d.%d)",
1907 ust_cmd
->reg_msg
.pid
, ust_cmd
->reg_msg
.ppid
,
1908 ust_cmd
->reg_msg
.uid
, ust_cmd
->reg_msg
.gid
,
1909 ust_cmd
->sock
, ust_cmd
->reg_msg
.name
,
1910 ust_cmd
->reg_msg
.major
, ust_cmd
->reg_msg
.minor
);
1912 if (ust_cmd
->reg_msg
.type
== USTCTL_SOCKET_CMD
) {
1913 wait_node
= zmalloc(sizeof(*wait_node
));
1915 PERROR("zmalloc wait_node dispatch");
1916 ret
= close(ust_cmd
->sock
);
1918 PERROR("close ust sock dispatch %d", ust_cmd
->sock
);
1920 lttng_fd_put(LTTNG_FD_APPS
, 1);
1924 CDS_INIT_LIST_HEAD(&wait_node
->head
);
1926 /* Create application object if socket is CMD. */
1927 wait_node
->app
= ust_app_create(&ust_cmd
->reg_msg
,
1929 if (!wait_node
->app
) {
1930 ret
= close(ust_cmd
->sock
);
1932 PERROR("close ust sock dispatch %d", ust_cmd
->sock
);
1934 lttng_fd_put(LTTNG_FD_APPS
, 1);
1940 * Add application to the wait queue so we can set the notify
1941 * socket before putting this object in the global ht.
1943 cds_list_add(&wait_node
->head
, &wait_queue
.head
);
1948 * We have to continue here since we don't have the notify
1949 * socket and the application MUST be added to the hash table
1950 * only at that moment.
1955 * Look for the application in the local wait queue and set the
1956 * notify socket if found.
1958 cds_list_for_each_entry_safe(wait_node
, tmp_wait_node
,
1959 &wait_queue
.head
, head
) {
1960 health_code_update();
1961 if (wait_node
->app
->pid
== ust_cmd
->reg_msg
.pid
) {
1962 wait_node
->app
->notify_sock
= ust_cmd
->sock
;
1963 cds_list_del(&wait_node
->head
);
1965 app
= wait_node
->app
;
1967 DBG3("UST app notify socket %d is set", ust_cmd
->sock
);
1973 * With no application at this stage the received socket is
1974 * basically useless so close it before we free the cmd data
1975 * structure for good.
1978 ret
= close(ust_cmd
->sock
);
1980 PERROR("close ust sock dispatch %d", ust_cmd
->sock
);
1982 lttng_fd_put(LTTNG_FD_APPS
, 1);
1989 * @session_lock_list
1991 * Lock the global session list so from the register up to the
1992 * registration done message, no thread can see the application
1993 * and change its state.
1995 session_lock_list();
1999 * Add application to the global hash table. This needs to be
2000 * done before the update to the UST registry can locate the
2005 /* Set app version. This call will print an error if needed. */
2006 (void) ust_app_version(app
);
2008 /* Send notify socket through the notify pipe. */
2009 ret
= send_socket_to_thread(apps_cmd_notify_pipe
[1],
2013 session_unlock_list();
2015 * No notify thread, stop the UST tracing. However, this is
2016 * not an internal error of the this thread thus setting
2017 * the health error code to a normal exit.
2024 * Update newly registered application with the tracing
2025 * registry info already enabled information.
2027 update_ust_app(app
->sock
);
2030 * Don't care about return value. Let the manage apps threads
2031 * handle app unregistration upon socket close.
2033 (void) ust_app_register_done(app
);
2036 * Even if the application socket has been closed, send the app
2037 * to the thread and unregistration will take place at that
2040 ret
= send_socket_to_thread(apps_cmd_pipe
[1], app
->sock
);
2043 session_unlock_list();
2045 * No apps. thread, stop the UST tracing. However, this is
2046 * not an internal error of the this thread thus setting
2047 * the health error code to a normal exit.
2054 session_unlock_list();
2056 } while (node
!= NULL
);
2058 health_poll_entry();
2059 /* Futex wait on queue. Blocking call on futex() */
2060 futex_nto1_wait(&ust_cmd_queue
.futex
);
2063 /* Normal exit, no error */
2067 /* Clean up wait queue. */
2068 cds_list_for_each_entry_safe(wait_node
, tmp_wait_node
,
2069 &wait_queue
.head
, head
) {
2070 cds_list_del(&wait_node
->head
);
2075 /* Empty command queue. */
2077 /* Dequeue command for registration */
2078 node
= cds_wfcq_dequeue_blocking(&ust_cmd_queue
.head
, &ust_cmd_queue
.tail
);
2082 ust_cmd
= caa_container_of(node
, struct ust_command
, node
);
2083 ret
= close(ust_cmd
->sock
);
2085 PERROR("close ust sock exit dispatch %d", ust_cmd
->sock
);
2087 lttng_fd_put(LTTNG_FD_APPS
, 1);
2092 DBG("Dispatch thread dying");
2095 ERR("Health error occurred in %s", __func__
);
2097 health_unregister(health_sessiond
);
2098 rcu_unregister_thread();
2103 * This thread manage application registration.
2105 static void *thread_registration_apps(void *data
)
2107 int sock
= -1, i
, ret
, pollfd
, err
= -1;
2108 uint32_t revents
, nb_fd
;
2109 struct lttng_poll_event events
;
2111 * Get allocated in this thread, enqueued to a global queue, dequeued and
2112 * freed in the manage apps thread.
2114 struct ust_command
*ust_cmd
= NULL
;
2116 DBG("[thread] Manage application registration started");
2118 health_register(health_sessiond
, HEALTH_SESSIOND_TYPE_APP_REG
);
2120 if (testpoint(sessiond_thread_registration_apps
)) {
2121 goto error_testpoint
;
2124 ret
= lttcomm_listen_unix_sock(apps_sock
);
2130 * Pass 2 as size here for the thread quit pipe and apps socket. Nothing
2131 * more will be added to this poll set.
2133 ret
= sessiond_set_thread_pollset(&events
, 2);
2135 goto error_create_poll
;
2138 /* Add the application registration socket */
2139 ret
= lttng_poll_add(&events
, apps_sock
, LPOLLIN
| LPOLLRDHUP
);
2141 goto error_poll_add
;
2144 /* Notify all applications to register */
2145 ret
= notify_ust_apps(1);
2147 ERR("Failed to notify applications or create the wait shared memory.\n"
2148 "Execution continues but there might be problem for already\n"
2149 "running applications that wishes to register.");
2153 DBG("Accepting application registration");
2155 /* Inifinite blocking call, waiting for transmission */
2157 health_poll_entry();
2158 ret
= lttng_poll_wait(&events
, -1);
2162 * Restart interrupted system call.
2164 if (errno
== EINTR
) {
2172 for (i
= 0; i
< nb_fd
; i
++) {
2173 health_code_update();
2175 /* Fetch once the poll data */
2176 revents
= LTTNG_POLL_GETEV(&events
, i
);
2177 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2180 /* No activity for this FD (poll implementation). */
2184 /* Thread quit pipe has been closed. Killing thread. */
2185 ret
= sessiond_check_thread_quit_pipe(pollfd
, revents
);
2191 /* Event on the registration socket */
2192 if (pollfd
== apps_sock
) {
2193 if (revents
& LPOLLIN
) {
2194 sock
= lttcomm_accept_unix_sock(apps_sock
);
2200 * Set socket timeout for both receiving and ending.
2201 * app_socket_timeout is in seconds, whereas
2202 * lttcomm_setsockopt_rcv_timeout and
2203 * lttcomm_setsockopt_snd_timeout expect msec as
2206 if (app_socket_timeout
>= 0) {
2207 (void) lttcomm_setsockopt_rcv_timeout(sock
,
2208 app_socket_timeout
* 1000);
2209 (void) lttcomm_setsockopt_snd_timeout(sock
,
2210 app_socket_timeout
* 1000);
2214 * Set the CLOEXEC flag. Return code is useless because
2215 * either way, the show must go on.
2217 (void) utils_set_fd_cloexec(sock
);
2219 /* Create UST registration command for enqueuing */
2220 ust_cmd
= zmalloc(sizeof(struct ust_command
));
2221 if (ust_cmd
== NULL
) {
2222 PERROR("ust command zmalloc");
2231 * Using message-based transmissions to ensure we don't
2232 * have to deal with partially received messages.
2234 ret
= lttng_fd_get(LTTNG_FD_APPS
, 1);
2236 ERR("Exhausted file descriptors allowed for applications.");
2246 health_code_update();
2247 ret
= ust_app_recv_registration(sock
, &ust_cmd
->reg_msg
);
2250 /* Close socket of the application. */
2255 lttng_fd_put(LTTNG_FD_APPS
, 1);
2259 health_code_update();
2261 ust_cmd
->sock
= sock
;
2264 DBG("UST registration received with pid:%d ppid:%d uid:%d"
2265 " gid:%d sock:%d name:%s (version %d.%d)",
2266 ust_cmd
->reg_msg
.pid
, ust_cmd
->reg_msg
.ppid
,
2267 ust_cmd
->reg_msg
.uid
, ust_cmd
->reg_msg
.gid
,
2268 ust_cmd
->sock
, ust_cmd
->reg_msg
.name
,
2269 ust_cmd
->reg_msg
.major
, ust_cmd
->reg_msg
.minor
);
2272 * Lock free enqueue the registration request. The red pill
2273 * has been taken! This apps will be part of the *system*.
2275 cds_wfcq_enqueue(&ust_cmd_queue
.head
, &ust_cmd_queue
.tail
, &ust_cmd
->node
);
2278 * Wake the registration queue futex. Implicit memory
2279 * barrier with the exchange in cds_wfcq_enqueue.
2281 futex_nto1_wake(&ust_cmd_queue
.futex
);
2282 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2283 ERR("Register apps socket poll error");
2286 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
2295 /* Notify that the registration thread is gone */
2298 if (apps_sock
>= 0) {
2299 ret
= close(apps_sock
);
2309 lttng_fd_put(LTTNG_FD_APPS
, 1);
2311 unlink(apps_unix_sock_path
);
2314 lttng_poll_clean(&events
);
2318 DBG("UST Registration thread cleanup complete");
2321 ERR("Health error occurred in %s", __func__
);
2323 health_unregister(health_sessiond
);
2329 * Start the thread_manage_consumer. This must be done after a lttng-consumerd
2330 * exec or it will fails.
2332 static int spawn_consumer_thread(struct consumer_data
*consumer_data
)
2335 struct timespec timeout
;
2338 * Make sure we set the readiness flag to 0 because we are NOT ready.
2339 * This access to consumer_thread_is_ready does not need to be
2340 * protected by consumer_data.cond_mutex (yet) since the consumer
2341 * management thread has not been started at this point.
2343 consumer_data
->consumer_thread_is_ready
= 0;
2345 /* Setup pthread condition */
2346 ret
= pthread_condattr_init(&consumer_data
->condattr
);
2349 PERROR("pthread_condattr_init consumer data");
2354 * Set the monotonic clock in order to make sure we DO NOT jump in time
2355 * between the clock_gettime() call and the timedwait call. See bug #324
2356 * for a more details and how we noticed it.
2358 ret
= pthread_condattr_setclock(&consumer_data
->condattr
, CLOCK_MONOTONIC
);
2361 PERROR("pthread_condattr_setclock consumer data");
2365 ret
= pthread_cond_init(&consumer_data
->cond
, &consumer_data
->condattr
);
2368 PERROR("pthread_cond_init consumer data");
2372 ret
= pthread_create(&consumer_data
->thread
, default_pthread_attr(),
2373 thread_manage_consumer
, consumer_data
);
2376 PERROR("pthread_create consumer");
2381 /* We are about to wait on a pthread condition */
2382 pthread_mutex_lock(&consumer_data
->cond_mutex
);
2384 /* Get time for sem_timedwait absolute timeout */
2385 clock_ret
= lttng_clock_gettime(CLOCK_MONOTONIC
, &timeout
);
2387 * Set the timeout for the condition timed wait even if the clock gettime
2388 * call fails since we might loop on that call and we want to avoid to
2389 * increment the timeout too many times.
2391 timeout
.tv_sec
+= DEFAULT_SEM_WAIT_TIMEOUT
;
2394 * The following loop COULD be skipped in some conditions so this is why we
2395 * set ret to 0 in order to make sure at least one round of the loop is
2401 * Loop until the condition is reached or when a timeout is reached. Note
2402 * that the pthread_cond_timedwait(P) man page specifies that EINTR can NOT
2403 * be returned but the pthread_cond(3), from the glibc-doc, says that it is
2404 * possible. This loop does not take any chances and works with both of
2407 while (!consumer_data
->consumer_thread_is_ready
&& ret
!= ETIMEDOUT
) {
2408 if (clock_ret
< 0) {
2409 PERROR("clock_gettime spawn consumer");
2410 /* Infinite wait for the consumerd thread to be ready */
2411 ret
= pthread_cond_wait(&consumer_data
->cond
,
2412 &consumer_data
->cond_mutex
);
2414 ret
= pthread_cond_timedwait(&consumer_data
->cond
,
2415 &consumer_data
->cond_mutex
, &timeout
);
2419 /* Release the pthread condition */
2420 pthread_mutex_unlock(&consumer_data
->cond_mutex
);
2424 if (ret
== ETIMEDOUT
) {
2428 * Call has timed out so we kill the kconsumerd_thread and return
2431 ERR("Condition timed out. The consumer thread was never ready."
2433 pth_ret
= pthread_cancel(consumer_data
->thread
);
2435 PERROR("pthread_cancel consumer thread");
2438 PERROR("pthread_cond_wait failed consumer thread");
2440 /* Caller is expecting a negative value on failure. */
2445 pthread_mutex_lock(&consumer_data
->pid_mutex
);
2446 if (consumer_data
->pid
== 0) {
2447 ERR("Consumerd did not start");
2448 pthread_mutex_unlock(&consumer_data
->pid_mutex
);
2451 pthread_mutex_unlock(&consumer_data
->pid_mutex
);
2460 * Join consumer thread
2462 static int join_consumer_thread(struct consumer_data
*consumer_data
)
2466 /* Consumer pid must be a real one. */
2467 if (consumer_data
->pid
> 0) {
2469 ret
= kill(consumer_data
->pid
, SIGTERM
);
2471 PERROR("Error killing consumer daemon");
2474 return pthread_join(consumer_data
->thread
, &status
);
2481 * Fork and exec a consumer daemon (consumerd).
2483 * Return pid if successful else -1.
2485 static pid_t
spawn_consumerd(struct consumer_data
*consumer_data
)
2489 const char *consumer_to_use
;
2490 const char *verbosity
;
2493 DBG("Spawning consumerd");
2500 if (opt_verbose_consumer
) {
2501 verbosity
= "--verbose";
2502 } else if (lttng_opt_quiet
) {
2503 verbosity
= "--quiet";
2508 switch (consumer_data
->type
) {
2509 case LTTNG_CONSUMER_KERNEL
:
2511 * Find out which consumerd to execute. We will first try the
2512 * 64-bit path, then the sessiond's installation directory, and
2513 * fallback on the 32-bit one,
2515 DBG3("Looking for a kernel consumer at these locations:");
2516 DBG3(" 1) %s", consumerd64_bin
);
2517 DBG3(" 2) %s/%s", INSTALL_BIN_PATH
, CONSUMERD_FILE
);
2518 DBG3(" 3) %s", consumerd32_bin
);
2519 if (stat(consumerd64_bin
, &st
) == 0) {
2520 DBG3("Found location #1");
2521 consumer_to_use
= consumerd64_bin
;
2522 } else if (stat(INSTALL_BIN_PATH
"/" CONSUMERD_FILE
, &st
) == 0) {
2523 DBG3("Found location #2");
2524 consumer_to_use
= INSTALL_BIN_PATH
"/" CONSUMERD_FILE
;
2525 } else if (stat(consumerd32_bin
, &st
) == 0) {
2526 DBG3("Found location #3");
2527 consumer_to_use
= consumerd32_bin
;
2529 DBG("Could not find any valid consumerd executable");
2533 DBG("Using kernel consumer at: %s", consumer_to_use
);
2534 ret
= execl(consumer_to_use
,
2535 "lttng-consumerd", verbosity
, "-k",
2536 "--consumerd-cmd-sock", consumer_data
->cmd_unix_sock_path
,
2537 "--consumerd-err-sock", consumer_data
->err_unix_sock_path
,
2538 "--group", tracing_group_name
,
2541 case LTTNG_CONSUMER64_UST
:
2543 char *tmpnew
= NULL
;
2545 if (consumerd64_libdir
[0] != '\0') {
2549 tmp
= lttng_secure_getenv("LD_LIBRARY_PATH");
2553 tmplen
= strlen("LD_LIBRARY_PATH=")
2554 + strlen(consumerd64_libdir
) + 1 /* : */ + strlen(tmp
);
2555 tmpnew
= zmalloc(tmplen
+ 1 /* \0 */);
2560 strcpy(tmpnew
, "LD_LIBRARY_PATH=");
2561 strcat(tmpnew
, consumerd64_libdir
);
2562 if (tmp
[0] != '\0') {
2563 strcat(tmpnew
, ":");
2564 strcat(tmpnew
, tmp
);
2566 ret
= putenv(tmpnew
);
2573 DBG("Using 64-bit UST consumer at: %s", consumerd64_bin
);
2574 ret
= execl(consumerd64_bin
, "lttng-consumerd", verbosity
, "-u",
2575 "--consumerd-cmd-sock", consumer_data
->cmd_unix_sock_path
,
2576 "--consumerd-err-sock", consumer_data
->err_unix_sock_path
,
2577 "--group", tracing_group_name
,
2579 if (consumerd64_libdir
[0] != '\0') {
2584 case LTTNG_CONSUMER32_UST
:
2586 char *tmpnew
= NULL
;
2588 if (consumerd32_libdir
[0] != '\0') {
2592 tmp
= lttng_secure_getenv("LD_LIBRARY_PATH");
2596 tmplen
= strlen("LD_LIBRARY_PATH=")
2597 + strlen(consumerd32_libdir
) + 1 /* : */ + strlen(tmp
);
2598 tmpnew
= zmalloc(tmplen
+ 1 /* \0 */);
2603 strcpy(tmpnew
, "LD_LIBRARY_PATH=");
2604 strcat(tmpnew
, consumerd32_libdir
);
2605 if (tmp
[0] != '\0') {
2606 strcat(tmpnew
, ":");
2607 strcat(tmpnew
, tmp
);
2609 ret
= putenv(tmpnew
);
2616 DBG("Using 32-bit UST consumer at: %s", consumerd32_bin
);
2617 ret
= execl(consumerd32_bin
, "lttng-consumerd", verbosity
, "-u",
2618 "--consumerd-cmd-sock", consumer_data
->cmd_unix_sock_path
,
2619 "--consumerd-err-sock", consumer_data
->err_unix_sock_path
,
2620 "--group", tracing_group_name
,
2622 if (consumerd32_libdir
[0] != '\0') {
2628 ERR("unknown consumer type");
2632 PERROR("Consumer execl()");
2634 /* Reaching this point, we got a failure on our execl(). */
2636 } else if (pid
> 0) {
2639 PERROR("start consumer fork");
2647 * Spawn the consumerd daemon and session daemon thread.
2649 static int start_consumerd(struct consumer_data
*consumer_data
)
2654 * Set the listen() state on the socket since there is a possible race
2655 * between the exec() of the consumer daemon and this call if place in the
2656 * consumer thread. See bug #366 for more details.
2658 ret
= lttcomm_listen_unix_sock(consumer_data
->err_sock
);
2663 pthread_mutex_lock(&consumer_data
->pid_mutex
);
2664 if (consumer_data
->pid
!= 0) {
2665 pthread_mutex_unlock(&consumer_data
->pid_mutex
);
2669 ret
= spawn_consumerd(consumer_data
);
2671 ERR("Spawning consumerd failed");
2672 pthread_mutex_unlock(&consumer_data
->pid_mutex
);
2676 /* Setting up the consumer_data pid */
2677 consumer_data
->pid
= ret
;
2678 DBG2("Consumer pid %d", consumer_data
->pid
);
2679 pthread_mutex_unlock(&consumer_data
->pid_mutex
);
2681 DBG2("Spawning consumer control thread");
2682 ret
= spawn_consumer_thread(consumer_data
);
2684 ERR("Fatal error spawning consumer control thread");
2692 /* Cleanup already created sockets on error. */
2693 if (consumer_data
->err_sock
>= 0) {
2696 err
= close(consumer_data
->err_sock
);
2698 PERROR("close consumer data error socket");
2705 * Setup necessary data for kernel tracer action.
2707 static int init_kernel_tracer(void)
2711 /* Modprobe lttng kernel modules */
2712 ret
= modprobe_lttng_control();
2717 /* Open debugfs lttng */
2718 kernel_tracer_fd
= open(module_proc_lttng
, O_RDWR
);
2719 if (kernel_tracer_fd
< 0) {
2720 DBG("Failed to open %s", module_proc_lttng
);
2724 /* Validate kernel version */
2725 ret
= kernel_validate_version(kernel_tracer_fd
);
2730 ret
= modprobe_lttng_data();
2735 DBG("Kernel tracer fd %d", kernel_tracer_fd
);
2739 modprobe_remove_lttng_control();
2740 ret
= close(kernel_tracer_fd
);
2744 kernel_tracer_fd
= -1;
2745 return LTTNG_ERR_KERN_VERSION
;
2748 ret
= close(kernel_tracer_fd
);
2754 modprobe_remove_lttng_control();
2757 WARN("No kernel tracer available");
2758 kernel_tracer_fd
= -1;
2760 return LTTNG_ERR_NEED_ROOT_SESSIOND
;
2762 return LTTNG_ERR_KERN_NA
;
2768 * Copy consumer output from the tracing session to the domain session. The
2769 * function also applies the right modification on a per domain basis for the
2770 * trace files destination directory.
2772 * Should *NOT* be called with RCU read-side lock held.
2774 static int copy_session_consumer(int domain
, struct ltt_session
*session
)
2777 const char *dir_name
;
2778 struct consumer_output
*consumer
;
2781 assert(session
->consumer
);
2784 case LTTNG_DOMAIN_KERNEL
:
2785 DBG3("Copying tracing session consumer output in kernel session");
2787 * XXX: We should audit the session creation and what this function
2788 * does "extra" in order to avoid a destroy since this function is used
2789 * in the domain session creation (kernel and ust) only. Same for UST
2792 if (session
->kernel_session
->consumer
) {
2793 consumer_output_put(session
->kernel_session
->consumer
);
2795 session
->kernel_session
->consumer
=
2796 consumer_copy_output(session
->consumer
);
2797 /* Ease our life a bit for the next part */
2798 consumer
= session
->kernel_session
->consumer
;
2799 dir_name
= DEFAULT_KERNEL_TRACE_DIR
;
2801 case LTTNG_DOMAIN_JUL
:
2802 case LTTNG_DOMAIN_LOG4J
:
2803 case LTTNG_DOMAIN_PYTHON
:
2804 case LTTNG_DOMAIN_UST
:
2805 DBG3("Copying tracing session consumer output in UST session");
2806 if (session
->ust_session
->consumer
) {
2807 consumer_output_put(session
->ust_session
->consumer
);
2809 session
->ust_session
->consumer
=
2810 consumer_copy_output(session
->consumer
);
2811 /* Ease our life a bit for the next part */
2812 consumer
= session
->ust_session
->consumer
;
2813 dir_name
= DEFAULT_UST_TRACE_DIR
;
2816 ret
= LTTNG_ERR_UNKNOWN_DOMAIN
;
2820 /* Append correct directory to subdir */
2821 strncat(consumer
->subdir
, dir_name
,
2822 sizeof(consumer
->subdir
) - strlen(consumer
->subdir
) - 1);
2823 DBG3("Copy session consumer subdir %s", consumer
->subdir
);
2832 * Create an UST session and add it to the session ust list.
2834 * Should *NOT* be called with RCU read-side lock held.
2836 static int create_ust_session(struct ltt_session
*session
,
2837 struct lttng_domain
*domain
)
2840 struct ltt_ust_session
*lus
= NULL
;
2844 assert(session
->consumer
);
2846 switch (domain
->type
) {
2847 case LTTNG_DOMAIN_JUL
:
2848 case LTTNG_DOMAIN_LOG4J
:
2849 case LTTNG_DOMAIN_PYTHON
:
2850 case LTTNG_DOMAIN_UST
:
2853 ERR("Unknown UST domain on create session %d", domain
->type
);
2854 ret
= LTTNG_ERR_UNKNOWN_DOMAIN
;
2858 DBG("Creating UST session");
2860 lus
= trace_ust_create_session(session
->id
);
2862 ret
= LTTNG_ERR_UST_SESS_FAIL
;
2866 lus
->uid
= session
->uid
;
2867 lus
->gid
= session
->gid
;
2868 lus
->output_traces
= session
->output_traces
;
2869 lus
->snapshot_mode
= session
->snapshot_mode
;
2870 lus
->live_timer_interval
= session
->live_timer
;
2871 session
->ust_session
= lus
;
2872 if (session
->shm_path
[0]) {
2873 strncpy(lus
->root_shm_path
, session
->shm_path
,
2874 sizeof(lus
->root_shm_path
));
2875 lus
->root_shm_path
[sizeof(lus
->root_shm_path
) - 1] = '\0';
2876 strncpy(lus
->shm_path
, session
->shm_path
,
2877 sizeof(lus
->shm_path
));
2878 lus
->shm_path
[sizeof(lus
->shm_path
) - 1] = '\0';
2879 strncat(lus
->shm_path
, "/ust",
2880 sizeof(lus
->shm_path
) - strlen(lus
->shm_path
) - 1);
2882 /* Copy session output to the newly created UST session */
2883 ret
= copy_session_consumer(domain
->type
, session
);
2884 if (ret
!= LTTNG_OK
) {
2892 session
->ust_session
= NULL
;
2897 * Create a kernel tracer session then create the default channel.
2899 static int create_kernel_session(struct ltt_session
*session
)
2903 DBG("Creating kernel session");
2905 ret
= kernel_create_session(session
, kernel_tracer_fd
);
2907 ret
= LTTNG_ERR_KERN_SESS_FAIL
;
2911 /* Code flow safety */
2912 assert(session
->kernel_session
);
2914 /* Copy session output to the newly created Kernel session */
2915 ret
= copy_session_consumer(LTTNG_DOMAIN_KERNEL
, session
);
2916 if (ret
!= LTTNG_OK
) {
2920 /* Create directory(ies) on local filesystem. */
2921 if (session
->kernel_session
->consumer
->type
== CONSUMER_DST_LOCAL
&&
2922 strlen(session
->kernel_session
->consumer
->dst
.trace_path
) > 0) {
2923 ret
= run_as_mkdir_recursive(
2924 session
->kernel_session
->consumer
->dst
.trace_path
,
2925 S_IRWXU
| S_IRWXG
, session
->uid
, session
->gid
);
2927 if (errno
!= EEXIST
) {
2928 ERR("Trace directory creation error");
2934 session
->kernel_session
->uid
= session
->uid
;
2935 session
->kernel_session
->gid
= session
->gid
;
2936 session
->kernel_session
->output_traces
= session
->output_traces
;
2937 session
->kernel_session
->snapshot_mode
= session
->snapshot_mode
;
2942 trace_kernel_destroy_session(session
->kernel_session
);
2943 session
->kernel_session
= NULL
;
2948 * Count number of session permitted by uid/gid.
2950 static unsigned int lttng_sessions_count(uid_t uid
, gid_t gid
)
2953 struct ltt_session
*session
;
2955 DBG("Counting number of available session for UID %d GID %d",
2957 cds_list_for_each_entry(session
, &session_list_ptr
->head
, list
) {
2959 * Only list the sessions the user can control.
2961 if (!session_access_ok(session
, uid
, gid
)) {
2970 * Process the command requested by the lttng client within the command
2971 * context structure. This function make sure that the return structure (llm)
2972 * is set and ready for transmission before returning.
2974 * Return any error encountered or 0 for success.
2976 * "sock" is only used for special-case var. len data.
2978 * Should *NOT* be called with RCU read-side lock held.
2980 static int process_client_msg(struct command_ctx
*cmd_ctx
, int sock
,
2984 int need_tracing_session
= 1;
2987 DBG("Processing client command %d", cmd_ctx
->lsm
->cmd_type
);
2989 assert(!rcu_read_ongoing());
2993 switch (cmd_ctx
->lsm
->cmd_type
) {
2994 case LTTNG_CREATE_SESSION
:
2995 case LTTNG_CREATE_SESSION_SNAPSHOT
:
2996 case LTTNG_CREATE_SESSION_LIVE
:
2997 case LTTNG_DESTROY_SESSION
:
2998 case LTTNG_LIST_SESSIONS
:
2999 case LTTNG_LIST_DOMAINS
:
3000 case LTTNG_START_TRACE
:
3001 case LTTNG_STOP_TRACE
:
3002 case LTTNG_DATA_PENDING
:
3003 case LTTNG_SNAPSHOT_ADD_OUTPUT
:
3004 case LTTNG_SNAPSHOT_DEL_OUTPUT
:
3005 case LTTNG_SNAPSHOT_LIST_OUTPUT
:
3006 case LTTNG_SNAPSHOT_RECORD
:
3007 case LTTNG_SAVE_SESSION
:
3008 case LTTNG_SET_SESSION_SHM_PATH
:
3009 case LTTNG_REGENERATE_METADATA
:
3010 case LTTNG_REGENERATE_STATEDUMP
:
3017 if (opt_no_kernel
&& need_domain
3018 && cmd_ctx
->lsm
->domain
.type
== LTTNG_DOMAIN_KERNEL
) {
3020 ret
= LTTNG_ERR_NEED_ROOT_SESSIOND
;
3022 ret
= LTTNG_ERR_KERN_NA
;
3027 /* Deny register consumer if we already have a spawned consumer. */
3028 if (cmd_ctx
->lsm
->cmd_type
== LTTNG_REGISTER_CONSUMER
) {
3029 pthread_mutex_lock(&kconsumer_data
.pid_mutex
);
3030 if (kconsumer_data
.pid
> 0) {
3031 ret
= LTTNG_ERR_KERN_CONSUMER_FAIL
;
3032 pthread_mutex_unlock(&kconsumer_data
.pid_mutex
);
3035 pthread_mutex_unlock(&kconsumer_data
.pid_mutex
);
3039 * Check for command that don't needs to allocate a returned payload. We do
3040 * this here so we don't have to make the call for no payload at each
3043 switch(cmd_ctx
->lsm
->cmd_type
) {
3044 case LTTNG_LIST_SESSIONS
:
3045 case LTTNG_LIST_TRACEPOINTS
:
3046 case LTTNG_LIST_TRACEPOINT_FIELDS
:
3047 case LTTNG_LIST_DOMAINS
:
3048 case LTTNG_LIST_CHANNELS
:
3049 case LTTNG_LIST_EVENTS
:
3050 case LTTNG_LIST_SYSCALLS
:
3051 case LTTNG_LIST_TRACKER_IDS
:
3052 case LTTNG_DATA_PENDING
:
3055 /* Setup lttng message with no payload */
3056 ret
= setup_lttng_msg_no_cmd_header(cmd_ctx
, NULL
, 0);
3058 /* This label does not try to unlock the session */
3059 goto init_setup_error
;
3063 /* Commands that DO NOT need a session. */
3064 switch (cmd_ctx
->lsm
->cmd_type
) {
3065 case LTTNG_CREATE_SESSION
:
3066 case LTTNG_CREATE_SESSION_SNAPSHOT
:
3067 case LTTNG_CREATE_SESSION_LIVE
:
3068 case LTTNG_LIST_SESSIONS
:
3069 case LTTNG_LIST_TRACEPOINTS
:
3070 case LTTNG_LIST_SYSCALLS
:
3071 case LTTNG_LIST_TRACEPOINT_FIELDS
:
3072 case LTTNG_SAVE_SESSION
:
3073 need_tracing_session
= 0;
3076 DBG("Getting session %s by name", cmd_ctx
->lsm
->session
.name
);
3078 * We keep the session list lock across _all_ commands
3079 * for now, because the per-session lock does not
3080 * handle teardown properly.
3082 session_lock_list();
3083 cmd_ctx
->session
= session_find_by_name(cmd_ctx
->lsm
->session
.name
);
3084 if (cmd_ctx
->session
== NULL
) {
3085 ret
= LTTNG_ERR_SESS_NOT_FOUND
;
3088 /* Acquire lock for the session */
3089 session_lock(cmd_ctx
->session
);
3095 * Commands that need a valid session but should NOT create one if none
3096 * exists. Instead of creating one and destroying it when the command is
3097 * handled, process that right before so we save some round trip in useless
3100 switch (cmd_ctx
->lsm
->cmd_type
) {
3101 case LTTNG_DISABLE_CHANNEL
:
3102 case LTTNG_DISABLE_EVENT
:
3103 switch (cmd_ctx
->lsm
->domain
.type
) {
3104 case LTTNG_DOMAIN_KERNEL
:
3105 if (!cmd_ctx
->session
->kernel_session
) {
3106 ret
= LTTNG_ERR_NO_CHANNEL
;
3110 case LTTNG_DOMAIN_JUL
:
3111 case LTTNG_DOMAIN_LOG4J
:
3112 case LTTNG_DOMAIN_PYTHON
:
3113 case LTTNG_DOMAIN_UST
:
3114 if (!cmd_ctx
->session
->ust_session
) {
3115 ret
= LTTNG_ERR_NO_CHANNEL
;
3120 ret
= LTTNG_ERR_UNKNOWN_DOMAIN
;
3132 * Check domain type for specific "pre-action".
3134 switch (cmd_ctx
->lsm
->domain
.type
) {
3135 case LTTNG_DOMAIN_KERNEL
:
3137 ret
= LTTNG_ERR_NEED_ROOT_SESSIOND
;
3141 /* Kernel tracer check */
3142 if (kernel_tracer_fd
== -1) {
3143 /* Basically, load kernel tracer modules */
3144 ret
= init_kernel_tracer();
3150 /* Consumer is in an ERROR state. Report back to client */
3151 if (uatomic_read(&kernel_consumerd_state
) == CONSUMER_ERROR
) {
3152 ret
= LTTNG_ERR_NO_KERNCONSUMERD
;
3156 /* Need a session for kernel command */
3157 if (need_tracing_session
) {
3158 if (cmd_ctx
->session
->kernel_session
== NULL
) {
3159 ret
= create_kernel_session(cmd_ctx
->session
);
3161 ret
= LTTNG_ERR_KERN_SESS_FAIL
;
3166 /* Start the kernel consumer daemon */
3167 pthread_mutex_lock(&kconsumer_data
.pid_mutex
);
3168 if (kconsumer_data
.pid
== 0 &&
3169 cmd_ctx
->lsm
->cmd_type
!= LTTNG_REGISTER_CONSUMER
) {
3170 pthread_mutex_unlock(&kconsumer_data
.pid_mutex
);
3171 ret
= start_consumerd(&kconsumer_data
);
3173 ret
= LTTNG_ERR_KERN_CONSUMER_FAIL
;
3176 uatomic_set(&kernel_consumerd_state
, CONSUMER_STARTED
);
3178 pthread_mutex_unlock(&kconsumer_data
.pid_mutex
);
3182 * The consumer was just spawned so we need to add the socket to
3183 * the consumer output of the session if exist.
3185 ret
= consumer_create_socket(&kconsumer_data
,
3186 cmd_ctx
->session
->kernel_session
->consumer
);
3193 case LTTNG_DOMAIN_JUL
:
3194 case LTTNG_DOMAIN_LOG4J
:
3195 case LTTNG_DOMAIN_PYTHON
:
3196 case LTTNG_DOMAIN_UST
:
3198 if (!ust_app_supported()) {
3199 ret
= LTTNG_ERR_NO_UST
;
3202 /* Consumer is in an ERROR state. Report back to client */
3203 if (uatomic_read(&ust_consumerd_state
) == CONSUMER_ERROR
) {
3204 ret
= LTTNG_ERR_NO_USTCONSUMERD
;
3208 if (need_tracing_session
) {
3209 /* Create UST session if none exist. */
3210 if (cmd_ctx
->session
->ust_session
== NULL
) {
3211 ret
= create_ust_session(cmd_ctx
->session
,
3212 &cmd_ctx
->lsm
->domain
);
3213 if (ret
!= LTTNG_OK
) {
3218 /* Start the UST consumer daemons */
3220 pthread_mutex_lock(&ustconsumer64_data
.pid_mutex
);
3221 if (consumerd64_bin
[0] != '\0' &&
3222 ustconsumer64_data
.pid
== 0 &&
3223 cmd_ctx
->lsm
->cmd_type
!= LTTNG_REGISTER_CONSUMER
) {
3224 pthread_mutex_unlock(&ustconsumer64_data
.pid_mutex
);
3225 ret
= start_consumerd(&ustconsumer64_data
);
3227 ret
= LTTNG_ERR_UST_CONSUMER64_FAIL
;
3228 uatomic_set(&ust_consumerd64_fd
, -EINVAL
);
3232 uatomic_set(&ust_consumerd64_fd
, ustconsumer64_data
.cmd_sock
);
3233 uatomic_set(&ust_consumerd_state
, CONSUMER_STARTED
);
3235 pthread_mutex_unlock(&ustconsumer64_data
.pid_mutex
);
3239 * Setup socket for consumer 64 bit. No need for atomic access
3240 * since it was set above and can ONLY be set in this thread.
3242 ret
= consumer_create_socket(&ustconsumer64_data
,
3243 cmd_ctx
->session
->ust_session
->consumer
);
3249 pthread_mutex_lock(&ustconsumer32_data
.pid_mutex
);
3250 if (consumerd32_bin
[0] != '\0' &&
3251 ustconsumer32_data
.pid
== 0 &&
3252 cmd_ctx
->lsm
->cmd_type
!= LTTNG_REGISTER_CONSUMER
) {
3253 pthread_mutex_unlock(&ustconsumer32_data
.pid_mutex
);
3254 ret
= start_consumerd(&ustconsumer32_data
);
3256 ret
= LTTNG_ERR_UST_CONSUMER32_FAIL
;
3257 uatomic_set(&ust_consumerd32_fd
, -EINVAL
);
3261 uatomic_set(&ust_consumerd32_fd
, ustconsumer32_data
.cmd_sock
);
3262 uatomic_set(&ust_consumerd_state
, CONSUMER_STARTED
);
3264 pthread_mutex_unlock(&ustconsumer32_data
.pid_mutex
);
3268 * Setup socket for consumer 64 bit. No need for atomic access
3269 * since it was set above and can ONLY be set in this thread.
3271 ret
= consumer_create_socket(&ustconsumer32_data
,
3272 cmd_ctx
->session
->ust_session
->consumer
);
3284 /* Validate consumer daemon state when start/stop trace command */
3285 if (cmd_ctx
->lsm
->cmd_type
== LTTNG_START_TRACE
||
3286 cmd_ctx
->lsm
->cmd_type
== LTTNG_STOP_TRACE
) {
3287 switch (cmd_ctx
->lsm
->domain
.type
) {
3288 case LTTNG_DOMAIN_NONE
:
3290 case LTTNG_DOMAIN_JUL
:
3291 case LTTNG_DOMAIN_LOG4J
:
3292 case LTTNG_DOMAIN_PYTHON
:
3293 case LTTNG_DOMAIN_UST
:
3294 if (uatomic_read(&ust_consumerd_state
) != CONSUMER_STARTED
) {
3295 ret
= LTTNG_ERR_NO_USTCONSUMERD
;
3299 case LTTNG_DOMAIN_KERNEL
:
3300 if (uatomic_read(&kernel_consumerd_state
) != CONSUMER_STARTED
) {
3301 ret
= LTTNG_ERR_NO_KERNCONSUMERD
;
3306 ret
= LTTNG_ERR_UNKNOWN_DOMAIN
;
3312 * Check that the UID or GID match that of the tracing session.
3313 * The root user can interact with all sessions.
3315 if (need_tracing_session
) {
3316 if (!session_access_ok(cmd_ctx
->session
,
3317 LTTNG_SOCK_GET_UID_CRED(&cmd_ctx
->creds
),
3318 LTTNG_SOCK_GET_GID_CRED(&cmd_ctx
->creds
))) {
3319 ret
= LTTNG_ERR_EPERM
;
3325 * Send relayd information to consumer as soon as we have a domain and a
3328 if (cmd_ctx
->session
&& need_domain
) {
3330 * Setup relayd if not done yet. If the relayd information was already
3331 * sent to the consumer, this call will gracefully return.
3333 ret
= cmd_setup_relayd(cmd_ctx
->session
);
3334 if (ret
!= LTTNG_OK
) {
3339 /* Process by command type */
3340 switch (cmd_ctx
->lsm
->cmd_type
) {
3341 case LTTNG_ADD_CONTEXT
:
3344 * An LTTNG_ADD_CONTEXT command might have a supplementary
3345 * payload if the context being added is an application context.
3347 if (cmd_ctx
->lsm
->u
.context
.ctx
.ctx
==
3348 LTTNG_EVENT_CONTEXT_APP_CONTEXT
) {
3349 char *provider_name
= NULL
, *context_name
= NULL
;
3350 size_t provider_name_len
=
3351 cmd_ctx
->lsm
->u
.context
.provider_name_len
;
3352 size_t context_name_len
=
3353 cmd_ctx
->lsm
->u
.context
.context_name_len
;
3355 if (provider_name_len
== 0 || context_name_len
== 0) {
3357 * Application provider and context names MUST
3360 ret
= -LTTNG_ERR_INVALID
;
3364 provider_name
= zmalloc(provider_name_len
+ 1);
3365 if (!provider_name
) {
3366 ret
= -LTTNG_ERR_NOMEM
;
3369 cmd_ctx
->lsm
->u
.context
.ctx
.u
.app_ctx
.provider_name
=
3372 context_name
= zmalloc(context_name_len
+ 1);
3373 if (!context_name
) {
3374 ret
= -LTTNG_ERR_NOMEM
;
3375 goto error_add_context
;
3377 cmd_ctx
->lsm
->u
.context
.ctx
.u
.app_ctx
.ctx_name
=
3380 ret
= lttcomm_recv_unix_sock(sock
, provider_name
,
3383 goto error_add_context
;
3386 ret
= lttcomm_recv_unix_sock(sock
, context_name
,
3389 goto error_add_context
;
3394 * cmd_add_context assumes ownership of the provider and context
3397 ret
= cmd_add_context(cmd_ctx
->session
,
3398 cmd_ctx
->lsm
->domain
.type
,
3399 cmd_ctx
->lsm
->u
.context
.channel_name
,
3400 &cmd_ctx
->lsm
->u
.context
.ctx
,
3401 kernel_poll_pipe
[1]);
3403 cmd_ctx
->lsm
->u
.context
.ctx
.u
.app_ctx
.provider_name
= NULL
;
3404 cmd_ctx
->lsm
->u
.context
.ctx
.u
.app_ctx
.ctx_name
= NULL
;
3406 free(cmd_ctx
->lsm
->u
.context
.ctx
.u
.app_ctx
.provider_name
);
3407 free(cmd_ctx
->lsm
->u
.context
.ctx
.u
.app_ctx
.ctx_name
);
3413 case LTTNG_DISABLE_CHANNEL
:
3415 ret
= cmd_disable_channel(cmd_ctx
->session
, cmd_ctx
->lsm
->domain
.type
,
3416 cmd_ctx
->lsm
->u
.disable
.channel_name
);
3419 case LTTNG_DISABLE_EVENT
:
3423 * FIXME: handle filter; for now we just receive the filter's
3424 * bytecode along with the filter expression which are sent by
3425 * liblttng-ctl and discard them.
3427 * This fixes an issue where the client may block while sending
3428 * the filter payload and encounter an error because the session
3429 * daemon closes the socket without ever handling this data.
3431 size_t count
= cmd_ctx
->lsm
->u
.disable
.expression_len
+
3432 cmd_ctx
->lsm
->u
.disable
.bytecode_len
;
3435 char data
[LTTNG_FILTER_MAX_LEN
];
3437 DBG("Discarding disable event command payload of size %zu", count
);
3439 ret
= lttcomm_recv_unix_sock(sock
, data
,
3440 count
> sizeof(data
) ? sizeof(data
) : count
);
3445 count
-= (size_t) ret
;
3448 /* FIXME: passing packed structure to non-packed pointer */
3449 ret
= cmd_disable_event(cmd_ctx
->session
, cmd_ctx
->lsm
->domain
.type
,
3450 cmd_ctx
->lsm
->u
.disable
.channel_name
,
3451 &cmd_ctx
->lsm
->u
.disable
.event
);
3454 case LTTNG_ENABLE_CHANNEL
:
3456 ret
= cmd_enable_channel(cmd_ctx
->session
, &cmd_ctx
->lsm
->domain
,
3457 &cmd_ctx
->lsm
->u
.channel
.chan
, kernel_poll_pipe
[1]);
3460 case LTTNG_TRACK_ID
:
3462 struct lttng_tracker_id id
;
3464 memset(&id
, 0, sizeof(id
));
3465 id
.type
= cmd_ctx
->lsm
->u
.id_tracker
.id_type
;
3469 case LTTNG_ID_VALUE
:
3470 id
.value
= cmd_ctx
->lsm
->u
.id_tracker
.u
.value
;
3472 case LTTNG_ID_STRING
:
3474 size_t var_len
= cmd_ctx
->lsm
->u
.id_tracker
.u
.var_len
;
3476 id
.string
= zmalloc(var_len
);
3478 ret
= LTTNG_ERR_NOMEM
;
3481 DBG("Receiving var len tracker id string from client.");
3482 ret
= lttcomm_recv_unix_sock(sock
, id
.string
, var_len
);
3484 DBG("Nothing received.");
3487 ret
= LTTNG_ERR_INVALID
;
3490 if (strnlen(id
.string
, var_len
) != var_len
- 1) {
3491 DBG("Corrupted string.");
3493 ret
= LTTNG_ERR_INVALID
;
3499 ret
= LTTNG_ERR_INVALID
;
3502 ret
= cmd_track_id(cmd_ctx
->session
,
3503 cmd_ctx
->lsm
->u
.id_tracker
.tracker_type
,
3504 cmd_ctx
->lsm
->domain
.type
,
3509 case LTTNG_UNTRACK_ID
:
3511 struct lttng_tracker_id id
;
3513 memset(&id
, 0, sizeof(id
));
3514 id
.type
= cmd_ctx
->lsm
->u
.id_tracker
.id_type
;
3518 case LTTNG_ID_VALUE
:
3519 id
.value
= cmd_ctx
->lsm
->u
.id_tracker
.u
.value
;
3521 case LTTNG_ID_STRING
:
3523 size_t var_len
= cmd_ctx
->lsm
->u
.id_tracker
.u
.var_len
;
3525 id
.string
= zmalloc(var_len
);
3527 ret
= LTTNG_ERR_NOMEM
;
3530 DBG("Receiving var len tracker id string from client.");
3531 ret
= lttcomm_recv_unix_sock(sock
, id
.string
, var_len
);
3533 DBG("Nothing received.");
3536 ret
= LTTNG_ERR_INVALID
;
3539 if (strnlen(id
.string
, var_len
) != var_len
- 1) {
3540 DBG("Corrupted string.");
3542 ret
= LTTNG_ERR_INVALID
;
3548 ret
= LTTNG_ERR_INVALID
;
3551 ret
= cmd_untrack_id(cmd_ctx
->session
,
3552 cmd_ctx
->lsm
->u
.id_tracker
.tracker_type
,
3553 cmd_ctx
->lsm
->domain
.type
,
3558 case LTTNG_ENABLE_EVENT
:
3560 struct lttng_event_exclusion
*exclusion
= NULL
;
3561 struct lttng_filter_bytecode
*bytecode
= NULL
;
3562 char *filter_expression
= NULL
;
3564 /* Handle exclusion events and receive it from the client. */
3565 if (cmd_ctx
->lsm
->u
.enable
.exclusion_count
> 0) {
3566 size_t count
= cmd_ctx
->lsm
->u
.enable
.exclusion_count
;
3568 exclusion
= zmalloc(sizeof(struct lttng_event_exclusion
) +
3569 (count
* LTTNG_SYMBOL_NAME_LEN
));
3571 ret
= LTTNG_ERR_EXCLUSION_NOMEM
;
3575 DBG("Receiving var len exclusion event list from client ...");
3576 exclusion
->count
= count
;
3577 ret
= lttcomm_recv_unix_sock(sock
, exclusion
->names
,
3578 count
* LTTNG_SYMBOL_NAME_LEN
);
3580 DBG("Nothing recv() from client var len data... continuing");
3583 ret
= LTTNG_ERR_EXCLUSION_INVAL
;
3588 /* Get filter expression from client. */
3589 if (cmd_ctx
->lsm
->u
.enable
.expression_len
> 0) {
3590 size_t expression_len
=
3591 cmd_ctx
->lsm
->u
.enable
.expression_len
;
3593 if (expression_len
> LTTNG_FILTER_MAX_LEN
) {
3594 ret
= LTTNG_ERR_FILTER_INVAL
;
3599 filter_expression
= zmalloc(expression_len
);
3600 if (!filter_expression
) {
3602 ret
= LTTNG_ERR_FILTER_NOMEM
;
3606 /* Receive var. len. data */
3607 DBG("Receiving var len filter's expression from client ...");
3608 ret
= lttcomm_recv_unix_sock(sock
, filter_expression
,
3611 DBG("Nothing recv() from client car len data... continuing");
3613 free(filter_expression
);
3615 ret
= LTTNG_ERR_FILTER_INVAL
;
3620 /* Handle filter and get bytecode from client. */
3621 if (cmd_ctx
->lsm
->u
.enable
.bytecode_len
> 0) {
3622 size_t bytecode_len
= cmd_ctx
->lsm
->u
.enable
.bytecode_len
;
3624 if (bytecode_len
> LTTNG_FILTER_MAX_LEN
) {
3625 ret
= LTTNG_ERR_FILTER_INVAL
;
3626 free(filter_expression
);
3631 bytecode
= zmalloc(bytecode_len
);
3633 free(filter_expression
);
3635 ret
= LTTNG_ERR_FILTER_NOMEM
;
3639 /* Receive var. len. data */
3640 DBG("Receiving var len filter's bytecode from client ...");
3641 ret
= lttcomm_recv_unix_sock(sock
, bytecode
, bytecode_len
);
3643 DBG("Nothing recv() from client car len data... continuing");
3645 free(filter_expression
);
3648 ret
= LTTNG_ERR_FILTER_INVAL
;
3652 if ((bytecode
->len
+ sizeof(*bytecode
)) != bytecode_len
) {
3653 free(filter_expression
);
3656 ret
= LTTNG_ERR_FILTER_INVAL
;
3661 ret
= cmd_enable_event(cmd_ctx
->session
, &cmd_ctx
->lsm
->domain
,
3662 cmd_ctx
->lsm
->u
.enable
.channel_name
,
3663 &cmd_ctx
->lsm
->u
.enable
.event
,
3664 filter_expression
, bytecode
, exclusion
,
3665 kernel_poll_pipe
[1]);
3668 case LTTNG_LIST_TRACEPOINTS
:
3670 struct lttng_event
*events
;
3673 session_lock_list();
3674 nb_events
= cmd_list_tracepoints(cmd_ctx
->lsm
->domain
.type
, &events
);
3675 session_unlock_list();
3676 if (nb_events
< 0) {
3677 /* Return value is a negative lttng_error_code. */
3683 * Setup lttng message with payload size set to the event list size in
3684 * bytes and then copy list into the llm payload.
3686 ret
= setup_lttng_msg_no_cmd_header(cmd_ctx
, events
,
3687 sizeof(struct lttng_event
) * nb_events
);
3697 case LTTNG_LIST_TRACEPOINT_FIELDS
:
3699 struct lttng_event_field
*fields
;
3702 session_lock_list();
3703 nb_fields
= cmd_list_tracepoint_fields(cmd_ctx
->lsm
->domain
.type
,
3705 session_unlock_list();
3706 if (nb_fields
< 0) {
3707 /* Return value is a negative lttng_error_code. */
3713 * Setup lttng message with payload size set to the event list size in
3714 * bytes and then copy list into the llm payload.
3716 ret
= setup_lttng_msg_no_cmd_header(cmd_ctx
, fields
,
3717 sizeof(struct lttng_event_field
) * nb_fields
);
3727 case LTTNG_LIST_SYSCALLS
:
3729 struct lttng_event
*events
;
3732 nb_events
= cmd_list_syscalls(&events
);
3733 if (nb_events
< 0) {
3734 /* Return value is a negative lttng_error_code. */
3740 * Setup lttng message with payload size set to the event list size in
3741 * bytes and then copy list into the llm payload.
3743 ret
= setup_lttng_msg_no_cmd_header(cmd_ctx
, events
,
3744 sizeof(struct lttng_event
) * nb_events
);
3754 case LTTNG_LIST_TRACKER_IDS
:
3756 struct lttcomm_tracker_command_header cmd_header
;
3757 struct lttng_tracker_id
*ids
= NULL
;
3759 struct lttng_dynamic_buffer buf
;
3761 nr_ids
= cmd_list_tracker_ids(cmd_ctx
->lsm
->u
.id_tracker
.tracker_type
,
3763 cmd_ctx
->lsm
->domain
.type
, &ids
);
3765 /* Return value is a negative lttng_error_code. */
3770 lttng_dynamic_buffer_init(&buf
);
3771 for (i
= 0; i
< nr_ids
; i
++) {
3772 struct lttng_tracker_id
*id
= &ids
[i
];
3773 struct lttcomm_tracker_id_header id_hdr
;
3774 size_t var_data_len
= 0;
3776 memset(&id_hdr
, 0, sizeof(id_hdr
));
3777 id_hdr
.type
= id
->type
;
3781 case LTTNG_ID_VALUE
:
3782 id_hdr
.u
.value
= id
->value
;
3784 case LTTNG_ID_STRING
:
3785 id_hdr
.u
.var_data_len
= var_data_len
= strlen(id
->string
) + 1;
3788 ret
= LTTNG_ERR_INVALID
;
3791 ret
= lttng_dynamic_buffer_append(&buf
, &id_hdr
, sizeof(id_hdr
));
3793 ret
= LTTNG_ERR_NOMEM
;
3796 ret
= lttng_dynamic_buffer_append(&buf
, id
->string
, var_data_len
);
3798 ret
= LTTNG_ERR_NOMEM
;
3804 cmd_header
.nb_tracker_id
= nr_ids
;
3805 ret
= setup_lttng_msg(cmd_ctx
, buf
.data
, buf
.size
, &cmd_header
,
3806 sizeof(cmd_header
));
3808 lttng_dynamic_buffer_reset(&buf
);
3816 case LTTNG_SET_CONSUMER_URI
:
3819 struct lttng_uri
*uris
;
3821 nb_uri
= cmd_ctx
->lsm
->u
.uri
.size
;
3822 len
= nb_uri
* sizeof(struct lttng_uri
);
3825 ret
= LTTNG_ERR_INVALID
;
3829 uris
= zmalloc(len
);
3831 ret
= LTTNG_ERR_FATAL
;
3835 /* Receive variable len data */
3836 DBG("Receiving %zu URI(s) from client ...", nb_uri
);
3837 ret
= lttcomm_recv_unix_sock(sock
, uris
, len
);
3839 DBG("No URIs received from client... continuing");
3841 ret
= LTTNG_ERR_SESSION_FAIL
;
3846 ret
= cmd_set_consumer_uri(cmd_ctx
->session
, nb_uri
, uris
);
3848 if (ret
!= LTTNG_OK
) {
3855 case LTTNG_START_TRACE
:
3857 ret
= cmd_start_trace(cmd_ctx
->session
);
3860 case LTTNG_STOP_TRACE
:
3862 ret
= cmd_stop_trace(cmd_ctx
->session
);
3865 case LTTNG_CREATE_SESSION
:
3868 struct lttng_uri
*uris
= NULL
;
3870 nb_uri
= cmd_ctx
->lsm
->u
.uri
.size
;
3871 len
= nb_uri
* sizeof(struct lttng_uri
);
3874 uris
= zmalloc(len
);
3876 ret
= LTTNG_ERR_FATAL
;
3880 /* Receive variable len data */
3881 DBG("Waiting for %zu URIs from client ...", nb_uri
);
3882 ret
= lttcomm_recv_unix_sock(sock
, uris
, len
);
3884 DBG("No URIs received from client... continuing");
3886 ret
= LTTNG_ERR_SESSION_FAIL
;
3891 if (nb_uri
== 1 && uris
[0].dtype
!= LTTNG_DST_PATH
) {
3892 DBG("Creating session with ONE network URI is a bad call");
3893 ret
= LTTNG_ERR_SESSION_FAIL
;
3899 ret
= cmd_create_session_uri(cmd_ctx
->lsm
->session
.name
, uris
, nb_uri
,
3900 &cmd_ctx
->creds
, 0);
3906 case LTTNG_DESTROY_SESSION
:
3908 ret
= cmd_destroy_session(cmd_ctx
->session
, kernel_poll_pipe
[1]);
3910 /* Set session to NULL so we do not unlock it after free. */
3911 cmd_ctx
->session
= NULL
;
3914 case LTTNG_LIST_DOMAINS
:
3917 struct lttng_domain
*domains
= NULL
;
3919 nb_dom
= cmd_list_domains(cmd_ctx
->session
, &domains
);
3921 /* Return value is a negative lttng_error_code. */
3926 ret
= setup_lttng_msg_no_cmd_header(cmd_ctx
, domains
,
3927 nb_dom
* sizeof(struct lttng_domain
));
3937 case LTTNG_LIST_CHANNELS
:
3939 ssize_t payload_size
;
3940 struct lttng_channel
*channels
= NULL
;
3942 payload_size
= cmd_list_channels(cmd_ctx
->lsm
->domain
.type
,
3943 cmd_ctx
->session
, &channels
);
3944 if (payload_size
< 0) {
3945 /* Return value is a negative lttng_error_code. */
3946 ret
= -payload_size
;
3950 ret
= setup_lttng_msg_no_cmd_header(cmd_ctx
, channels
,
3961 case LTTNG_LIST_EVENTS
:
3964 struct lttng_event
*events
= NULL
;
3965 struct lttcomm_event_command_header cmd_header
;
3968 memset(&cmd_header
, 0, sizeof(cmd_header
));
3969 /* Extended infos are included at the end of events */
3970 nb_event
= cmd_list_events(cmd_ctx
->lsm
->domain
.type
,
3971 cmd_ctx
->session
, cmd_ctx
->lsm
->u
.list
.channel_name
,
3972 &events
, &total_size
);
3975 /* Return value is a negative lttng_error_code. */
3980 cmd_header
.nb_events
= nb_event
;
3981 ret
= setup_lttng_msg(cmd_ctx
, events
, total_size
,
3982 &cmd_header
, sizeof(cmd_header
));
3992 case LTTNG_LIST_SESSIONS
:
3994 unsigned int nr_sessions
;
3995 void *sessions_payload
;
3998 session_lock_list();
3999 nr_sessions
= lttng_sessions_count(
4000 LTTNG_SOCK_GET_UID_CRED(&cmd_ctx
->creds
),
4001 LTTNG_SOCK_GET_GID_CRED(&cmd_ctx
->creds
));
4002 payload_len
= sizeof(struct lttng_session
) * nr_sessions
;
4003 sessions_payload
= zmalloc(payload_len
);
4005 if (!sessions_payload
) {
4006 session_unlock_list();
4011 cmd_list_lttng_sessions(sessions_payload
,
4012 LTTNG_SOCK_GET_UID_CRED(&cmd_ctx
->creds
),
4013 LTTNG_SOCK_GET_GID_CRED(&cmd_ctx
->creds
));
4014 session_unlock_list();
4016 ret
= setup_lttng_msg_no_cmd_header(cmd_ctx
, sessions_payload
,
4018 free(sessions_payload
);
4027 case LTTNG_REGISTER_CONSUMER
:
4029 struct consumer_data
*cdata
;
4031 switch (cmd_ctx
->lsm
->domain
.type
) {
4032 case LTTNG_DOMAIN_KERNEL
:
4033 cdata
= &kconsumer_data
;
4036 ret
= LTTNG_ERR_UND
;
4040 ret
= cmd_register_consumer(cmd_ctx
->session
, cmd_ctx
->lsm
->domain
.type
,
4041 cmd_ctx
->lsm
->u
.reg
.path
, cdata
);
4044 case LTTNG_DATA_PENDING
:
4047 uint8_t pending_ret_byte
;
4049 pending_ret
= cmd_data_pending(cmd_ctx
->session
);
4054 * This function may returns 0 or 1 to indicate whether or not
4055 * there is data pending. In case of error, it should return an
4056 * LTTNG_ERR code. However, some code paths may still return
4057 * a nondescript error code, which we handle by returning an
4060 if (pending_ret
== 0 || pending_ret
== 1) {
4062 * ret will be set to LTTNG_OK at the end of
4065 } else if (pending_ret
< 0) {
4066 ret
= LTTNG_ERR_UNK
;
4073 pending_ret_byte
= (uint8_t) pending_ret
;
4075 /* 1 byte to return whether or not data is pending */
4076 ret
= setup_lttng_msg_no_cmd_header(cmd_ctx
,
4077 &pending_ret_byte
, 1);
4086 case LTTNG_SNAPSHOT_ADD_OUTPUT
:
4088 struct lttcomm_lttng_output_id reply
;
4090 ret
= cmd_snapshot_add_output(cmd_ctx
->session
,
4091 &cmd_ctx
->lsm
->u
.snapshot_output
.output
, &reply
.id
);
4092 if (ret
!= LTTNG_OK
) {
4096 ret
= setup_lttng_msg_no_cmd_header(cmd_ctx
, &reply
,
4102 /* Copy output list into message payload */
4106 case LTTNG_SNAPSHOT_DEL_OUTPUT
:
4108 ret
= cmd_snapshot_del_output(cmd_ctx
->session
,
4109 &cmd_ctx
->lsm
->u
.snapshot_output
.output
);
4112 case LTTNG_SNAPSHOT_LIST_OUTPUT
:
4115 struct lttng_snapshot_output
*outputs
= NULL
;
4117 nb_output
= cmd_snapshot_list_outputs(cmd_ctx
->session
, &outputs
);
4118 if (nb_output
< 0) {
4123 assert((nb_output
> 0 && outputs
) || nb_output
== 0);
4124 ret
= setup_lttng_msg_no_cmd_header(cmd_ctx
, outputs
,
4125 nb_output
* sizeof(struct lttng_snapshot_output
));
4135 case LTTNG_SNAPSHOT_RECORD
:
4137 ret
= cmd_snapshot_record(cmd_ctx
->session
,
4138 &cmd_ctx
->lsm
->u
.snapshot_record
.output
,
4139 cmd_ctx
->lsm
->u
.snapshot_record
.wait
);
4142 case LTTNG_CREATE_SESSION_SNAPSHOT
:
4145 struct lttng_uri
*uris
= NULL
;
4147 nb_uri
= cmd_ctx
->lsm
->u
.uri
.size
;
4148 len
= nb_uri
* sizeof(struct lttng_uri
);
4151 uris
= zmalloc(len
);
4153 ret
= LTTNG_ERR_FATAL
;
4157 /* Receive variable len data */
4158 DBG("Waiting for %zu URIs from client ...", nb_uri
);
4159 ret
= lttcomm_recv_unix_sock(sock
, uris
, len
);
4161 DBG("No URIs received from client... continuing");
4163 ret
= LTTNG_ERR_SESSION_FAIL
;
4168 if (nb_uri
== 1 && uris
[0].dtype
!= LTTNG_DST_PATH
) {
4169 DBG("Creating session with ONE network URI is a bad call");
4170 ret
= LTTNG_ERR_SESSION_FAIL
;
4176 ret
= cmd_create_session_snapshot(cmd_ctx
->lsm
->session
.name
, uris
,
4177 nb_uri
, &cmd_ctx
->creds
);
4181 case LTTNG_CREATE_SESSION_LIVE
:
4184 struct lttng_uri
*uris
= NULL
;
4186 nb_uri
= cmd_ctx
->lsm
->u
.uri
.size
;
4187 len
= nb_uri
* sizeof(struct lttng_uri
);
4190 uris
= zmalloc(len
);
4192 ret
= LTTNG_ERR_FATAL
;
4196 /* Receive variable len data */
4197 DBG("Waiting for %zu URIs from client ...", nb_uri
);
4198 ret
= lttcomm_recv_unix_sock(sock
, uris
, len
);
4200 DBG("No URIs received from client... continuing");
4202 ret
= LTTNG_ERR_SESSION_FAIL
;
4207 if (nb_uri
== 1 && uris
[0].dtype
!= LTTNG_DST_PATH
) {
4208 DBG("Creating session with ONE network URI is a bad call");
4209 ret
= LTTNG_ERR_SESSION_FAIL
;
4215 ret
= cmd_create_session_uri(cmd_ctx
->lsm
->session
.name
, uris
,
4216 nb_uri
, &cmd_ctx
->creds
, cmd_ctx
->lsm
->u
.session_live
.timer_interval
);
4220 case LTTNG_SAVE_SESSION
:
4222 ret
= cmd_save_sessions(&cmd_ctx
->lsm
->u
.save_session
.attr
,
4226 case LTTNG_SET_SESSION_SHM_PATH
:
4228 ret
= cmd_set_session_shm_path(cmd_ctx
->session
,
4229 cmd_ctx
->lsm
->u
.set_shm_path
.shm_path
);
4232 case LTTNG_REGENERATE_METADATA
:
4234 ret
= cmd_regenerate_metadata(cmd_ctx
->session
);
4237 case LTTNG_REGENERATE_STATEDUMP
:
4239 ret
= cmd_regenerate_statedump(cmd_ctx
->session
);
4243 ret
= LTTNG_ERR_UND
;
4248 if (cmd_ctx
->llm
== NULL
) {
4249 DBG("Missing llm structure. Allocating one.");
4250 if (setup_lttng_msg_no_cmd_header(cmd_ctx
, NULL
, 0) < 0) {
4254 /* Set return code */
4255 cmd_ctx
->llm
->ret_code
= ret
;
4257 if (cmd_ctx
->session
) {
4258 session_unlock(cmd_ctx
->session
);
4260 if (need_tracing_session
) {
4261 session_unlock_list();
4264 assert(!rcu_read_ongoing());
4269 * Thread managing health check socket.
4271 static void *thread_manage_health(void *data
)
4273 int sock
= -1, new_sock
= -1, ret
, i
, pollfd
, err
= -1;
4274 uint32_t revents
, nb_fd
;
4275 struct lttng_poll_event events
;
4276 struct health_comm_msg msg
;
4277 struct health_comm_reply reply
;
4279 DBG("[thread] Manage health check started");
4281 rcu_register_thread();
4283 /* We might hit an error path before this is created. */
4284 lttng_poll_init(&events
);
4286 /* Create unix socket */
4287 sock
= lttcomm_create_unix_sock(health_unix_sock_path
);
4289 ERR("Unable to create health check Unix socket");
4294 /* lttng health client socket path permissions */
4295 ret
= chown(health_unix_sock_path
, 0,
4296 utils_get_group_id(tracing_group_name
));
4298 ERR("Unable to set group on %s", health_unix_sock_path
);
4303 ret
= chmod(health_unix_sock_path
,
4304 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
4306 ERR("Unable to set permissions on %s", health_unix_sock_path
);
4313 * Set the CLOEXEC flag. Return code is useless because either way, the
4316 (void) utils_set_fd_cloexec(sock
);
4318 ret
= lttcomm_listen_unix_sock(sock
);
4324 * Pass 2 as size here for the thread quit pipe and client_sock. Nothing
4325 * more will be added to this poll set.
4327 ret
= sessiond_set_thread_pollset(&events
, 2);
4332 /* Add the application registration socket */
4333 ret
= lttng_poll_add(&events
, sock
, LPOLLIN
| LPOLLPRI
);
4338 sessiond_notify_ready();
4341 DBG("Health check ready");
4343 /* Inifinite blocking call, waiting for transmission */
4345 ret
= lttng_poll_wait(&events
, -1);
4348 * Restart interrupted system call.
4350 if (errno
== EINTR
) {
4358 for (i
= 0; i
< nb_fd
; i
++) {
4359 /* Fetch once the poll data */
4360 revents
= LTTNG_POLL_GETEV(&events
, i
);
4361 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4364 /* No activity for this FD (poll implementation). */
4368 /* Thread quit pipe has been closed. Killing thread. */
4369 ret
= sessiond_check_thread_quit_pipe(pollfd
, revents
);
4375 /* Event on the registration socket */
4376 if (pollfd
== sock
) {
4377 if (revents
& LPOLLIN
) {
4379 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4380 ERR("Health socket poll error");
4383 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
4389 new_sock
= lttcomm_accept_unix_sock(sock
);
4395 * Set the CLOEXEC flag. Return code is useless because either way, the
4398 (void) utils_set_fd_cloexec(new_sock
);
4400 DBG("Receiving data from client for health...");
4401 ret
= lttcomm_recv_unix_sock(new_sock
, (void *)&msg
, sizeof(msg
));
4403 DBG("Nothing recv() from client... continuing");
4404 ret
= close(new_sock
);
4411 rcu_thread_online();
4413 memset(&reply
, 0, sizeof(reply
));
4414 for (i
= 0; i
< NR_HEALTH_SESSIOND_TYPES
; i
++) {
4416 * health_check_state returns 0 if health is
4419 if (!health_check_state(health_sessiond
, i
)) {
4420 reply
.ret_code
|= 1ULL << i
;
4424 DBG2("Health check return value %" PRIx64
, reply
.ret_code
);
4426 ret
= send_unix_sock(new_sock
, (void *) &reply
, sizeof(reply
));
4428 ERR("Failed to send health data back to client");
4431 /* End of transmission */
4432 ret
= close(new_sock
);
4441 ERR("Health error occurred in %s", __func__
);
4443 DBG("Health check thread dying");
4444 unlink(health_unix_sock_path
);
4452 lttng_poll_clean(&events
);
4454 rcu_unregister_thread();
4459 * This thread manage all clients request using the unix client socket for
4462 static void *thread_manage_clients(void *data
)
4464 int sock
= -1, ret
, i
, pollfd
, err
= -1;
4466 uint32_t revents
, nb_fd
;
4467 struct command_ctx
*cmd_ctx
= NULL
;
4468 struct lttng_poll_event events
;
4470 DBG("[thread] Manage client started");
4472 rcu_register_thread();
4474 health_register(health_sessiond
, HEALTH_SESSIOND_TYPE_CMD
);
4476 health_code_update();
4478 ret
= lttcomm_listen_unix_sock(client_sock
);
4484 * Pass 2 as size here for the thread quit pipe and client_sock. Nothing
4485 * more will be added to this poll set.
4487 ret
= sessiond_set_thread_pollset(&events
, 2);
4489 goto error_create_poll
;
4492 /* Add the application registration socket */
4493 ret
= lttng_poll_add(&events
, client_sock
, LPOLLIN
| LPOLLPRI
);
4498 sessiond_notify_ready();
4500 ret
= sem_post(&load_info
->message_thread_ready
);
4502 PERROR("sem_post message_thread_ready");
4507 * Wait until all support threads are initialized before accepting
4510 while (uatomic_read(<tng_sessiond_ready
) != 0) {
4512 struct timeval timeout
;
4515 FD_SET(thread_quit_pipe
[0], &read_fds
);
4516 memset(&timeout
, 0, sizeof(timeout
));
4517 timeout
.tv_usec
= 1000;
4520 * If a support thread failed to launch, it may signal that
4521 * we must exit and the sessiond would never be marked as
4524 * The timeout is set to 1ms, which serves as a way to
4525 * pace down this check.
4527 ret
= select(thread_quit_pipe
[0] + 1, &read_fds
, NULL
, NULL
,
4529 if (ret
> 0 || (ret
< 0 && errno
!= EINTR
)) {
4534 /* This testpoint is after we signal readiness to the parent. */
4535 if (testpoint(sessiond_thread_manage_clients
)) {
4539 if (testpoint(sessiond_thread_manage_clients_before_loop
)) {
4543 health_code_update();
4546 DBG("Accepting client command ...");
4548 /* Inifinite blocking call, waiting for transmission */
4550 health_poll_entry();
4551 ret
= lttng_poll_wait(&events
, -1);
4555 * Restart interrupted system call.
4557 if (errno
== EINTR
) {
4565 for (i
= 0; i
< nb_fd
; i
++) {
4566 /* Fetch once the poll data */
4567 revents
= LTTNG_POLL_GETEV(&events
, i
);
4568 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4570 health_code_update();
4573 /* No activity for this FD (poll implementation). */
4577 /* Thread quit pipe has been closed. Killing thread. */
4578 ret
= sessiond_check_thread_quit_pipe(pollfd
, revents
);
4584 /* Event on the registration socket */
4585 if (pollfd
== client_sock
) {
4586 if (revents
& LPOLLIN
) {
4588 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4589 ERR("Client socket poll error");
4592 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
4598 DBG("Wait for client response");
4600 health_code_update();
4602 sock
= lttcomm_accept_unix_sock(client_sock
);
4608 * Set the CLOEXEC flag. Return code is useless because either way, the
4611 (void) utils_set_fd_cloexec(sock
);
4613 /* Set socket option for credentials retrieval */
4614 ret
= lttcomm_setsockopt_creds_unix_sock(sock
);
4619 /* Allocate context command to process the client request */
4620 cmd_ctx
= zmalloc(sizeof(struct command_ctx
));
4621 if (cmd_ctx
== NULL
) {
4622 PERROR("zmalloc cmd_ctx");
4626 /* Allocate data buffer for reception */
4627 cmd_ctx
->lsm
= zmalloc(sizeof(struct lttcomm_session_msg
));
4628 if (cmd_ctx
->lsm
== NULL
) {
4629 PERROR("zmalloc cmd_ctx->lsm");
4633 cmd_ctx
->llm
= NULL
;
4634 cmd_ctx
->session
= NULL
;
4636 health_code_update();
4639 * Data is received from the lttng client. The struct
4640 * lttcomm_session_msg (lsm) contains the command and data request of
4643 DBG("Receiving data from client ...");
4644 ret
= lttcomm_recv_creds_unix_sock(sock
, cmd_ctx
->lsm
,
4645 sizeof(struct lttcomm_session_msg
), &cmd_ctx
->creds
);
4647 DBG("Nothing recv() from client... continuing");
4653 clean_command_ctx(&cmd_ctx
);
4657 health_code_update();
4659 // TODO: Validate cmd_ctx including sanity check for
4660 // security purpose.
4662 rcu_thread_online();
4664 * This function dispatch the work to the kernel or userspace tracer
4665 * libs and fill the lttcomm_lttng_msg data structure of all the needed
4666 * informations for the client. The command context struct contains
4667 * everything this function may needs.
4669 ret
= process_client_msg(cmd_ctx
, sock
, &sock_error
);
4670 rcu_thread_offline();
4678 * TODO: Inform client somehow of the fatal error. At
4679 * this point, ret < 0 means that a zmalloc failed
4680 * (ENOMEM). Error detected but still accept
4681 * command, unless a socket error has been
4684 clean_command_ctx(&cmd_ctx
);
4688 health_code_update();
4690 DBG("Sending response (size: %d, retcode: %s (%d))",
4691 cmd_ctx
->lttng_msg_size
,
4692 lttng_strerror(-cmd_ctx
->llm
->ret_code
),
4693 cmd_ctx
->llm
->ret_code
);
4694 ret
= send_unix_sock(sock
, cmd_ctx
->llm
, cmd_ctx
->lttng_msg_size
);
4696 ERR("Failed to send data back to client");
4699 /* End of transmission */
4706 clean_command_ctx(&cmd_ctx
);
4708 health_code_update();
4720 lttng_poll_clean(&events
);
4721 clean_command_ctx(&cmd_ctx
);
4725 unlink(client_unix_sock_path
);
4726 if (client_sock
>= 0) {
4727 ret
= close(client_sock
);
4735 ERR("Health error occurred in %s", __func__
);
4738 health_unregister(health_sessiond
);
4740 DBG("Client thread dying");
4742 rcu_unregister_thread();
4745 * Since we are creating the consumer threads, we own them, so we need
4746 * to join them before our thread exits.
4748 ret
= join_consumer_thread(&kconsumer_data
);
4751 PERROR("join_consumer");
4754 ret
= join_consumer_thread(&ustconsumer32_data
);
4757 PERROR("join_consumer ust32");
4760 ret
= join_consumer_thread(&ustconsumer64_data
);
4763 PERROR("join_consumer ust64");
4768 static int string_match(const char *str1
, const char *str2
)
4770 return (str1
&& str2
) && !strcmp(str1
, str2
);
4774 * Take an option from the getopt output and set it in the right variable to be
4777 * Return 0 on success else a negative value.
4779 static int set_option(int opt
, const char *arg
, const char *optname
)
4783 if (string_match(optname
, "client-sock") || opt
== 'c') {
4784 if (!arg
|| *arg
== '\0') {
4788 if (lttng_is_setuid_setgid()) {
4789 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4790 "-c, --client-sock");
4792 snprintf(client_unix_sock_path
, PATH_MAX
, "%s", arg
);
4794 } else if (string_match(optname
, "apps-sock") || opt
== 'a') {
4795 if (!arg
|| *arg
== '\0') {
4799 if (lttng_is_setuid_setgid()) {
4800 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4803 snprintf(apps_unix_sock_path
, PATH_MAX
, "%s", arg
);
4805 } else if (string_match(optname
, "daemonize") || opt
== 'd') {
4807 } else if (string_match(optname
, "background") || opt
== 'b') {
4809 } else if (string_match(optname
, "group") || opt
== 'g') {
4810 if (!arg
|| *arg
== '\0') {
4814 if (lttng_is_setuid_setgid()) {
4815 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4819 * If the override option is set, the pointer points to a
4820 * *non* const thus freeing it even though the variable type is
4823 if (tracing_group_name_override
) {
4824 free((void *) tracing_group_name
);
4826 tracing_group_name
= strdup(arg
);
4827 if (!tracing_group_name
) {
4831 tracing_group_name_override
= 1;
4833 } else if (string_match(optname
, "help") || opt
== 'h') {
4834 ret
= utils_show_man_page(8, "lttng-sessiond");
4836 ERR("Cannot view man page lttng-sessiond(8)");
4839 exit(ret
? EXIT_FAILURE
: EXIT_SUCCESS
);
4840 } else if (string_match(optname
, "version") || opt
== 'V') {
4841 opt_print_version
= 1;
4842 } else if (string_match(optname
, "sig-parent") || opt
== 'S') {
4844 } else if (string_match(optname
, "kconsumerd-err-sock")) {
4845 if (!arg
|| *arg
== '\0') {
4849 if (lttng_is_setuid_setgid()) {
4850 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4851 "--kconsumerd-err-sock");
4853 snprintf(kconsumer_data
.err_unix_sock_path
, PATH_MAX
, "%s", arg
);
4855 } else if (string_match(optname
, "kconsumerd-cmd-sock")) {
4856 if (!arg
|| *arg
== '\0') {
4860 if (lttng_is_setuid_setgid()) {
4861 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4862 "--kconsumerd-cmd-sock");
4864 snprintf(kconsumer_data
.cmd_unix_sock_path
, PATH_MAX
, "%s", arg
);
4866 } else if (string_match(optname
, "ustconsumerd64-err-sock")) {
4867 if (!arg
|| *arg
== '\0') {
4871 if (lttng_is_setuid_setgid()) {
4872 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4873 "--ustconsumerd64-err-sock");
4875 snprintf(ustconsumer64_data
.err_unix_sock_path
, PATH_MAX
, "%s", arg
);
4877 } else if (string_match(optname
, "ustconsumerd64-cmd-sock")) {
4878 if (!arg
|| *arg
== '\0') {
4882 if (lttng_is_setuid_setgid()) {
4883 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4884 "--ustconsumerd64-cmd-sock");
4886 snprintf(ustconsumer64_data
.cmd_unix_sock_path
, PATH_MAX
, "%s", arg
);
4888 } else if (string_match(optname
, "ustconsumerd32-err-sock")) {
4889 if (!arg
|| *arg
== '\0') {
4893 if (lttng_is_setuid_setgid()) {
4894 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4895 "--ustconsumerd32-err-sock");
4897 snprintf(ustconsumer32_data
.err_unix_sock_path
, PATH_MAX
, "%s", arg
);
4899 } else if (string_match(optname
, "ustconsumerd32-cmd-sock")) {
4900 if (!arg
|| *arg
== '\0') {
4904 if (lttng_is_setuid_setgid()) {
4905 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4906 "--ustconsumerd32-cmd-sock");
4908 snprintf(ustconsumer32_data
.cmd_unix_sock_path
, PATH_MAX
, "%s", arg
);
4910 } else if (string_match(optname
, "no-kernel")) {
4912 } else if (string_match(optname
, "quiet") || opt
== 'q') {
4913 lttng_opt_quiet
= 1;
4914 } else if (string_match(optname
, "verbose") || opt
== 'v') {
4915 /* Verbose level can increase using multiple -v */
4917 /* Value obtained from config file */
4918 lttng_opt_verbose
= config_parse_value(arg
);
4920 /* -v used on command line */
4921 lttng_opt_verbose
++;
4923 /* Clamp value to [0, 3] */
4924 lttng_opt_verbose
= lttng_opt_verbose
< 0 ? 0 :
4925 (lttng_opt_verbose
<= 3 ? lttng_opt_verbose
: 3);
4926 } else if (string_match(optname
, "verbose-consumer")) {
4928 opt_verbose_consumer
= config_parse_value(arg
);
4930 opt_verbose_consumer
++;
4932 } else if (string_match(optname
, "consumerd32-path")) {
4933 if (!arg
|| *arg
== '\0') {
4937 if (lttng_is_setuid_setgid()) {
4938 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4939 "--consumerd32-path");
4941 if (consumerd32_bin_override
) {
4942 free((void *) consumerd32_bin
);
4944 consumerd32_bin
= strdup(arg
);
4945 if (!consumerd32_bin
) {
4949 consumerd32_bin_override
= 1;
4951 } else if (string_match(optname
, "consumerd32-libdir")) {
4952 if (!arg
|| *arg
== '\0') {
4956 if (lttng_is_setuid_setgid()) {
4957 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4958 "--consumerd32-libdir");
4960 if (consumerd32_libdir_override
) {
4961 free((void *) consumerd32_libdir
);
4963 consumerd32_libdir
= strdup(arg
);
4964 if (!consumerd32_libdir
) {
4968 consumerd32_libdir_override
= 1;
4970 } else if (string_match(optname
, "consumerd64-path")) {
4971 if (!arg
|| *arg
== '\0') {
4975 if (lttng_is_setuid_setgid()) {
4976 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4977 "--consumerd64-path");
4979 if (consumerd64_bin_override
) {
4980 free((void *) consumerd64_bin
);
4982 consumerd64_bin
= strdup(arg
);
4983 if (!consumerd64_bin
) {
4987 consumerd64_bin_override
= 1;
4989 } else if (string_match(optname
, "consumerd64-libdir")) {
4990 if (!arg
|| *arg
== '\0') {
4994 if (lttng_is_setuid_setgid()) {
4995 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4996 "--consumerd64-libdir");
4998 if (consumerd64_libdir_override
) {
4999 free((void *) consumerd64_libdir
);
5001 consumerd64_libdir
= strdup(arg
);
5002 if (!consumerd64_libdir
) {
5006 consumerd64_libdir_override
= 1;
5008 } else if (string_match(optname
, "pidfile") || opt
== 'p') {
5009 if (!arg
|| *arg
== '\0') {
5013 if (lttng_is_setuid_setgid()) {
5014 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
5018 opt_pidfile
= strdup(arg
);
5024 } else if (string_match(optname
, "agent-tcp-port")) {
5025 if (!arg
|| *arg
== '\0') {
5029 if (lttng_is_setuid_setgid()) {
5030 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
5031 "--agent-tcp-port");
5036 v
= strtoul(arg
, NULL
, 0);
5037 if (errno
!= 0 || !isdigit(arg
[0])) {
5038 ERR("Wrong value in --agent-tcp-port parameter: %s", arg
);
5041 if (v
== 0 || v
>= 65535) {
5042 ERR("Port overflow in --agent-tcp-port parameter: %s", arg
);
5045 agent_tcp_port
= (uint32_t) v
;
5046 DBG3("Agent TCP port set to non default: %u", agent_tcp_port
);
5048 } else if (string_match(optname
, "load") || opt
== 'l') {
5049 if (!arg
|| *arg
== '\0') {
5053 if (lttng_is_setuid_setgid()) {
5054 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
5057 free(opt_load_session_path
);
5058 opt_load_session_path
= strdup(arg
);
5059 if (!opt_load_session_path
) {
5064 } else if (string_match(optname
, "kmod-probes")) {
5065 if (!arg
|| *arg
== '\0') {
5069 if (lttng_is_setuid_setgid()) {
5070 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
5073 free(kmod_probes_list
);
5074 kmod_probes_list
= strdup(arg
);
5075 if (!kmod_probes_list
) {
5080 } else if (string_match(optname
, "extra-kmod-probes")) {
5081 if (!arg
|| *arg
== '\0') {
5085 if (lttng_is_setuid_setgid()) {
5086 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
5087 "--extra-kmod-probes");
5089 free(kmod_extra_probes_list
);
5090 kmod_extra_probes_list
= strdup(arg
);
5091 if (!kmod_extra_probes_list
) {
5096 } else if (string_match(optname
, "config") || opt
== 'f') {
5097 /* This is handled in set_options() thus silent skip. */
5100 /* Unknown option or other error.
5101 * Error is printed by getopt, just return */
5106 if (ret
== -EINVAL
) {
5107 const char *opt_name
= "unknown";
5110 for (i
= 0; i
< sizeof(long_options
) / sizeof(struct option
);
5112 if (opt
== long_options
[i
].val
) {
5113 opt_name
= long_options
[i
].name
;
5118 WARN("Invalid argument provided for option \"%s\", using default value.",
5126 * config_entry_handler_cb used to handle options read from a config file.
5127 * See config_entry_handler_cb comment in common/config/session-config.h for the
5128 * return value conventions.
5130 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
5134 if (!entry
|| !entry
->name
|| !entry
->value
) {
5139 /* Check if the option is to be ignored */
5140 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
5141 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
5146 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1;
5149 /* Ignore if not fully matched. */
5150 if (strcmp(entry
->name
, long_options
[i
].name
)) {
5155 * If the option takes no argument on the command line, we have to
5156 * check if the value is "true". We support non-zero numeric values,
5159 if (!long_options
[i
].has_arg
) {
5160 ret
= config_parse_value(entry
->value
);
5163 WARN("Invalid configuration value \"%s\" for option %s",
5164 entry
->value
, entry
->name
);
5166 /* False, skip boolean config option. */
5171 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
5175 WARN("Unrecognized option \"%s\" in daemon configuration file.", entry
->name
);
5181 static void sessiond_config_log(void)
5183 DBG("LTTng-sessiond " VERSION
" - " VERSION_NAME
"%s%s",
5184 GIT_VERSION
[0] == '\0' ? "" : " - " GIT_VERSION
,
5185 EXTRA_VERSION_NAME
[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME
);
5186 if (EXTRA_VERSION_DESCRIPTION
[0] != '\0') {
5187 DBG("LTTng-sessiond extra version description:\n\t" EXTRA_VERSION_DESCRIPTION
"\n");
5189 if (EXTRA_VERSION_PATCHES
[0] != '\0') {
5190 DBG("LTTng-sessiond extra patches:\n\t" EXTRA_VERSION_PATCHES
"\n");
5194 static void print_version(void) {
5195 fprintf(stdout
, "%s\n", VERSION
);
5199 * daemon configuration loading and argument parsing
5201 static int set_options(int argc
, char **argv
)
5203 int ret
= 0, c
= 0, option_index
= 0;
5204 int orig_optopt
= optopt
, orig_optind
= optind
;
5206 const char *config_path
= NULL
;
5208 optstring
= utils_generate_optstring(long_options
,
5209 sizeof(long_options
) / sizeof(struct option
));
5215 /* Check for the --config option */
5216 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
5217 &option_index
)) != -1) {
5221 } else if (c
!= 'f') {
5222 /* if not equal to --config option. */
5226 if (lttng_is_setuid_setgid()) {
5227 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
5230 config_path
= utils_expand_path(optarg
);
5232 ERR("Failed to resolve path: %s", optarg
);
5237 ret
= config_get_section_entries(config_path
, config_section_name
,
5238 config_entry_handler
, NULL
);
5241 ERR("Invalid configuration option at line %i", ret
);
5247 /* Reset getopt's global state */
5248 optopt
= orig_optopt
;
5249 optind
= orig_optind
;
5253 * getopt_long() will not set option_index if it encounters a
5256 c
= getopt_long(argc
, argv
, optstring
, long_options
,
5263 * Pass NULL as the long option name if popt left the index
5266 ret
= set_option(c
, optarg
,
5267 option_index
< 0 ? NULL
:
5268 long_options
[option_index
].name
);
5280 * Creates the two needed socket by the daemon.
5281 * apps_sock - The communication socket for all UST apps.
5282 * client_sock - The communication of the cli tool (lttng).
5284 static int init_daemon_socket(void)
5289 old_umask
= umask(0);
5291 /* Create client tool unix socket */
5292 client_sock
= lttcomm_create_unix_sock(client_unix_sock_path
);
5293 if (client_sock
< 0) {
5294 ERR("Create unix sock failed: %s", client_unix_sock_path
);
5299 /* Set the cloexec flag */
5300 ret
= utils_set_fd_cloexec(client_sock
);
5302 ERR("Unable to set CLOEXEC flag to the client Unix socket (fd: %d). "
5303 "Continuing but note that the consumer daemon will have a "
5304 "reference to this socket on exec()", client_sock
);
5307 /* File permission MUST be 660 */
5308 ret
= chmod(client_unix_sock_path
, S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
5310 ERR("Set file permissions failed: %s", client_unix_sock_path
);
5315 /* Create the application unix socket */
5316 apps_sock
= lttcomm_create_unix_sock(apps_unix_sock_path
);
5317 if (apps_sock
< 0) {
5318 ERR("Create unix sock failed: %s", apps_unix_sock_path
);
5323 /* Set the cloexec flag */
5324 ret
= utils_set_fd_cloexec(apps_sock
);
5326 ERR("Unable to set CLOEXEC flag to the app Unix socket (fd: %d). "
5327 "Continuing but note that the consumer daemon will have a "
5328 "reference to this socket on exec()", apps_sock
);
5331 /* File permission MUST be 666 */
5332 ret
= chmod(apps_unix_sock_path
,
5333 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
| S_IROTH
| S_IWOTH
);
5335 ERR("Set file permissions failed: %s", apps_unix_sock_path
);
5340 DBG3("Session daemon client socket %d and application socket %d created",
5341 client_sock
, apps_sock
);
5349 * Check if the global socket is available, and if a daemon is answering at the
5350 * other side. If yes, error is returned.
5352 static int check_existing_daemon(void)
5354 /* Is there anybody out there ? */
5355 if (lttng_session_daemon_alive()) {
5363 * Set the tracing group gid onto the client socket.
5365 * Race window between mkdir and chown is OK because we are going from more
5366 * permissive (root.root) to less permissive (root.tracing).
5368 static int set_permissions(char *rundir
)
5373 gid
= utils_get_group_id(tracing_group_name
);
5375 /* Set lttng run dir */
5376 ret
= chown(rundir
, 0, gid
);
5378 ERR("Unable to set group on %s", rundir
);
5383 * Ensure all applications and tracing group can search the run
5384 * dir. Allow everyone to read the directory, since it does not
5385 * buy us anything to hide its content.
5387 ret
= chmod(rundir
, S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
5389 ERR("Unable to set permissions on %s", rundir
);
5393 /* lttng client socket path */
5394 ret
= chown(client_unix_sock_path
, 0, gid
);
5396 ERR("Unable to set group on %s", client_unix_sock_path
);
5400 /* kconsumer error socket path */
5401 ret
= chown(kconsumer_data
.err_unix_sock_path
, 0, 0);
5403 ERR("Unable to set group on %s", kconsumer_data
.err_unix_sock_path
);
5407 /* 64-bit ustconsumer error socket path */
5408 ret
= chown(ustconsumer64_data
.err_unix_sock_path
, 0, 0);
5410 ERR("Unable to set group on %s", ustconsumer64_data
.err_unix_sock_path
);
5414 /* 32-bit ustconsumer compat32 error socket path */
5415 ret
= chown(ustconsumer32_data
.err_unix_sock_path
, 0, 0);
5417 ERR("Unable to set group on %s", ustconsumer32_data
.err_unix_sock_path
);
5421 DBG("All permissions are set");
5427 * Create the lttng run directory needed for all global sockets and pipe.
5429 static int create_lttng_rundir(const char *rundir
)
5433 DBG3("Creating LTTng run directory: %s", rundir
);
5435 ret
= mkdir(rundir
, S_IRWXU
);
5437 if (errno
!= EEXIST
) {
5438 ERR("Unable to create %s", rundir
);
5450 * Setup sockets and directory needed by the kconsumerd communication with the
5453 static int set_consumer_sockets(struct consumer_data
*consumer_data
,
5457 char path
[PATH_MAX
];
5459 switch (consumer_data
->type
) {
5460 case LTTNG_CONSUMER_KERNEL
:
5461 snprintf(path
, PATH_MAX
, DEFAULT_KCONSUMERD_PATH
, rundir
);
5463 case LTTNG_CONSUMER64_UST
:
5464 snprintf(path
, PATH_MAX
, DEFAULT_USTCONSUMERD64_PATH
, rundir
);
5466 case LTTNG_CONSUMER32_UST
:
5467 snprintf(path
, PATH_MAX
, DEFAULT_USTCONSUMERD32_PATH
, rundir
);
5470 ERR("Consumer type unknown");
5475 DBG2("Creating consumer directory: %s", path
);
5477 ret
= mkdir(path
, S_IRWXU
| S_IRGRP
| S_IXGRP
);
5479 if (errno
!= EEXIST
) {
5481 ERR("Failed to create %s", path
);
5487 ret
= chown(path
, 0, utils_get_group_id(tracing_group_name
));
5489 ERR("Unable to set group on %s", path
);
5495 /* Create the kconsumerd error unix socket */
5496 consumer_data
->err_sock
=
5497 lttcomm_create_unix_sock(consumer_data
->err_unix_sock_path
);
5498 if (consumer_data
->err_sock
< 0) {
5499 ERR("Create unix sock failed: %s", consumer_data
->err_unix_sock_path
);
5505 * Set the CLOEXEC flag. Return code is useless because either way, the
5508 ret
= utils_set_fd_cloexec(consumer_data
->err_sock
);
5510 PERROR("utils_set_fd_cloexec");
5511 /* continue anyway */
5514 /* File permission MUST be 660 */
5515 ret
= chmod(consumer_data
->err_unix_sock_path
,
5516 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
5518 ERR("Set file permissions failed: %s", consumer_data
->err_unix_sock_path
);
5528 * Signal handler for the daemon
5530 * Simply stop all worker threads, leaving main() return gracefully after
5531 * joining all threads and calling cleanup().
5533 static void sighandler(int sig
)
5537 DBG("SIGINT caught");
5541 DBG("SIGTERM caught");
5545 CMM_STORE_SHARED(recv_child_signal
, 1);
5553 * Setup signal handler for :
5554 * SIGINT, SIGTERM, SIGPIPE
5556 static int set_signal_handler(void)
5559 struct sigaction sa
;
5562 if ((ret
= sigemptyset(&sigset
)) < 0) {
5563 PERROR("sigemptyset");
5567 sa
.sa_mask
= sigset
;
5570 sa
.sa_handler
= sighandler
;
5571 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
5572 PERROR("sigaction");
5576 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
5577 PERROR("sigaction");
5581 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
5582 PERROR("sigaction");
5586 sa
.sa_handler
= SIG_IGN
;
5587 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
5588 PERROR("sigaction");
5592 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
5598 * Set open files limit to unlimited. This daemon can open a large number of
5599 * file descriptors in order to consume multiple kernel traces.
5601 static void set_ulimit(void)
5606 /* The kernel does not allow an infinite limit for open files */
5607 lim
.rlim_cur
= 65535;
5608 lim
.rlim_max
= 65535;
5610 ret
= setrlimit(RLIMIT_NOFILE
, &lim
);
5612 PERROR("failed to set open files limit");
5617 * Write pidfile using the rundir and opt_pidfile.
5619 static int write_pidfile(void)
5622 char pidfile_path
[PATH_MAX
];
5627 if (lttng_strncpy(pidfile_path
, opt_pidfile
, sizeof(pidfile_path
))) {
5632 /* Build pidfile path from rundir and opt_pidfile. */
5633 ret
= snprintf(pidfile_path
, sizeof(pidfile_path
), "%s/"
5634 DEFAULT_LTTNG_SESSIOND_PIDFILE
, rundir
);
5636 PERROR("snprintf pidfile path");
5642 * Create pid file in rundir.
5644 ret
= utils_create_pid_file(getpid(), pidfile_path
);
5650 * Create lockfile using the rundir and return its fd.
5652 static int create_lockfile(void)
5655 char lockfile_path
[PATH_MAX
];
5657 ret
= generate_lock_file_path(lockfile_path
, sizeof(lockfile_path
));
5662 ret
= utils_create_lock_file(lockfile_path
);
5668 * Write agent TCP port using the rundir.
5670 static int write_agent_port(void)
5673 char path
[PATH_MAX
];
5677 ret
= snprintf(path
, sizeof(path
), "%s/"
5678 DEFAULT_LTTNG_SESSIOND_AGENTPORT_FILE
, rundir
);
5680 PERROR("snprintf agent port path");
5685 * Create TCP agent port file in rundir.
5687 ret
= utils_create_pid_file(agent_tcp_port
, path
);
5693 static int set_clock_plugin_env(void)
5696 const char *original_env_value
;
5697 char *full_path
= NULL
;
5698 char *new_env_value
= NULL
;
5700 original_env_value
= getenv("LTTNG_UST_CLOCK_PLUGIN");
5701 if (!original_env_value
) {
5705 full_path
= utils_expand_path(original_env_value
);
5707 ERR("Failed to expand LTTNG_UST_CLOCK_PLUGIN path \"%s\"",
5708 original_env_value
);
5712 ret
= asprintf(&new_env_value
, "LTTNG_UST_CLOCK_PLUGIN=%s",
5720 DBG("Updating environment: %s", new_env_value
);
5721 ret
= putenv(new_env_value
);
5723 free(new_env_value
);
5724 PERROR("putenv of LTTNG_UST_CLOCK_PLUGIN");
5734 int main(int argc
, char **argv
)
5736 int ret
= 0, retval
= 0;
5738 const char *home_path
, *env_app_timeout
;
5740 init_kernel_workarounds();
5742 rcu_register_thread();
5744 if (set_signal_handler()) {
5746 goto exit_set_signal_handler
;
5749 setup_consumerd_path();
5751 page_size
= sysconf(_SC_PAGESIZE
);
5752 if (page_size
< 0) {
5753 PERROR("sysconf _SC_PAGESIZE");
5754 page_size
= LONG_MAX
;
5755 WARN("Fallback page size to %ld", page_size
);
5759 * Parse arguments and load the daemon configuration file.
5761 * We have an exit_options exit path to free memory reserved by
5762 * set_options. This is needed because the rest of sessiond_cleanup()
5763 * depends on ht_cleanup_thread, which depends on lttng_daemonize, which
5764 * depends on set_options.
5767 if (set_options(argc
, argv
)) {
5772 sessiond_config_log();
5774 if (opt_print_version
) {
5780 ret
= set_clock_plugin_env();
5787 if (opt_daemon
|| opt_background
) {
5790 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
5798 * We are in the child. Make sure all other file descriptors are
5799 * closed, in case we are called with more opened file
5800 * descriptors than the standard ones.
5802 for (i
= 3; i
< sysconf(_SC_OPEN_MAX
); i
++) {
5807 if (run_as_create_worker(argv
[0]) < 0) {
5808 goto exit_create_run_as_worker_cleanup
;
5812 * Starting from here, we can create threads. This needs to be after
5813 * lttng_daemonize due to RCU.
5817 * Initialize the health check subsystem. This call should set the
5818 * appropriate time values.
5820 health_sessiond
= health_app_create(NR_HEALTH_SESSIOND_TYPES
);
5821 if (!health_sessiond
) {
5822 PERROR("health_app_create error");
5824 goto exit_health_sessiond_cleanup
;
5827 /* Create thread to clean up RCU hash tables */
5828 if (init_ht_cleanup_thread(&ht_cleanup_thread
)) {
5830 goto exit_ht_cleanup
;
5833 /* Create thread quit pipe */
5834 if (init_thread_quit_pipe()) {
5836 goto exit_init_data
;
5839 /* Check if daemon is UID = 0 */
5840 is_root
= !getuid();
5843 rundir
= strdup(DEFAULT_LTTNG_RUNDIR
);
5846 goto exit_init_data
;
5849 /* Create global run dir with root access */
5850 if (create_lttng_rundir(rundir
)) {
5852 goto exit_init_data
;
5855 if (strlen(apps_unix_sock_path
) == 0) {
5856 ret
= snprintf(apps_unix_sock_path
, PATH_MAX
,
5857 DEFAULT_GLOBAL_APPS_UNIX_SOCK
);
5860 goto exit_init_data
;
5864 if (strlen(client_unix_sock_path
) == 0) {
5865 ret
= snprintf(client_unix_sock_path
, PATH_MAX
,
5866 DEFAULT_GLOBAL_CLIENT_UNIX_SOCK
);
5869 goto exit_init_data
;
5873 /* Set global SHM for ust */
5874 if (strlen(wait_shm_path
) == 0) {
5875 ret
= snprintf(wait_shm_path
, PATH_MAX
,
5876 DEFAULT_GLOBAL_APPS_WAIT_SHM_PATH
);
5879 goto exit_init_data
;
5883 if (strlen(health_unix_sock_path
) == 0) {
5884 ret
= snprintf(health_unix_sock_path
,
5885 sizeof(health_unix_sock_path
),
5886 DEFAULT_GLOBAL_HEALTH_UNIX_SOCK
);
5889 goto exit_init_data
;
5893 /* Setup kernel consumerd path */
5894 ret
= snprintf(kconsumer_data
.err_unix_sock_path
, PATH_MAX
,
5895 DEFAULT_KCONSUMERD_ERR_SOCK_PATH
, rundir
);
5898 goto exit_init_data
;
5900 ret
= snprintf(kconsumer_data
.cmd_unix_sock_path
, PATH_MAX
,
5901 DEFAULT_KCONSUMERD_CMD_SOCK_PATH
, rundir
);
5904 goto exit_init_data
;
5907 DBG2("Kernel consumer err path: %s",
5908 kconsumer_data
.err_unix_sock_path
);
5909 DBG2("Kernel consumer cmd path: %s",
5910 kconsumer_data
.cmd_unix_sock_path
);
5912 home_path
= utils_get_home_dir();
5913 if (home_path
== NULL
) {
5914 /* TODO: Add --socket PATH option */
5915 ERR("Can't get HOME directory for sockets creation.");
5917 goto exit_init_data
;
5921 * Create rundir from home path. This will create something like
5924 ret
= asprintf(&rundir
, DEFAULT_LTTNG_HOME_RUNDIR
, home_path
);
5927 goto exit_init_data
;
5930 if (create_lttng_rundir(rundir
)) {
5932 goto exit_init_data
;
5935 if (strlen(apps_unix_sock_path
) == 0) {
5936 ret
= snprintf(apps_unix_sock_path
, PATH_MAX
,
5937 DEFAULT_HOME_APPS_UNIX_SOCK
,
5941 goto exit_init_data
;
5945 /* Set the cli tool unix socket path */
5946 if (strlen(client_unix_sock_path
) == 0) {
5947 ret
= snprintf(client_unix_sock_path
, PATH_MAX
,
5948 DEFAULT_HOME_CLIENT_UNIX_SOCK
,
5952 goto exit_init_data
;
5956 /* Set global SHM for ust */
5957 if (strlen(wait_shm_path
) == 0) {
5958 ret
= snprintf(wait_shm_path
, PATH_MAX
,
5959 DEFAULT_HOME_APPS_WAIT_SHM_PATH
,
5963 goto exit_init_data
;
5967 /* Set health check Unix path */
5968 if (strlen(health_unix_sock_path
) == 0) {
5969 ret
= snprintf(health_unix_sock_path
,
5970 sizeof(health_unix_sock_path
),
5971 DEFAULT_HOME_HEALTH_UNIX_SOCK
,
5975 goto exit_init_data
;
5980 lockfile_fd
= create_lockfile();
5981 if (lockfile_fd
< 0) {
5983 goto exit_init_data
;
5986 /* Set consumer initial state */
5987 kernel_consumerd_state
= CONSUMER_STOPPED
;
5988 ust_consumerd_state
= CONSUMER_STOPPED
;
5990 DBG("Client socket path %s", client_unix_sock_path
);
5991 DBG("Application socket path %s", apps_unix_sock_path
);
5992 DBG("Application wait path %s", wait_shm_path
);
5993 DBG("LTTng run directory path: %s", rundir
);
5995 /* 32 bits consumerd path setup */
5996 ret
= snprintf(ustconsumer32_data
.err_unix_sock_path
, PATH_MAX
,
5997 DEFAULT_USTCONSUMERD32_ERR_SOCK_PATH
, rundir
);
5999 PERROR("snprintf 32-bit consumer error socket path");
6001 goto exit_init_data
;
6003 ret
= snprintf(ustconsumer32_data
.cmd_unix_sock_path
, PATH_MAX
,
6004 DEFAULT_USTCONSUMERD32_CMD_SOCK_PATH
, rundir
);
6006 PERROR("snprintf 32-bit consumer command socket path");
6008 goto exit_init_data
;
6011 DBG2("UST consumer 32 bits err path: %s",
6012 ustconsumer32_data
.err_unix_sock_path
);
6013 DBG2("UST consumer 32 bits cmd path: %s",
6014 ustconsumer32_data
.cmd_unix_sock_path
);
6016 /* 64 bits consumerd path setup */
6017 ret
= snprintf(ustconsumer64_data
.err_unix_sock_path
, PATH_MAX
,
6018 DEFAULT_USTCONSUMERD64_ERR_SOCK_PATH
, rundir
);
6020 PERROR("snprintf 64-bit consumer error socket path");
6022 goto exit_init_data
;
6024 ret
= snprintf(ustconsumer64_data
.cmd_unix_sock_path
, PATH_MAX
,
6025 DEFAULT_USTCONSUMERD64_CMD_SOCK_PATH
, rundir
);
6027 PERROR("snprintf 64-bit consumer command socket path");
6029 goto exit_init_data
;
6032 DBG2("UST consumer 64 bits err path: %s",
6033 ustconsumer64_data
.err_unix_sock_path
);
6034 DBG2("UST consumer 64 bits cmd path: %s",
6035 ustconsumer64_data
.cmd_unix_sock_path
);
6038 * See if daemon already exist.
6040 if (check_existing_daemon()) {
6041 ERR("Already running daemon.\n");
6043 * We do not goto exit because we must not cleanup()
6044 * because a daemon is already running.
6047 goto exit_init_data
;
6051 * Init UST app hash table. Alloc hash table before this point since
6052 * cleanup() can get called after that point.
6054 if (ust_app_ht_alloc()) {
6055 ERR("Failed to allocate UST app hash table");
6057 goto exit_init_data
;
6061 * Initialize agent app hash table. We allocate the hash table here
6062 * since cleanup() can get called after this point.
6064 if (agent_app_ht_alloc()) {
6065 ERR("Failed to allocate Agent app hash table");
6067 goto exit_init_data
;
6071 * These actions must be executed as root. We do that *after* setting up
6072 * the sockets path because we MUST make the check for another daemon using
6073 * those paths *before* trying to set the kernel consumer sockets and init
6077 if (set_consumer_sockets(&kconsumer_data
, rundir
)) {
6079 goto exit_init_data
;
6082 /* Setup kernel tracer */
6083 if (!opt_no_kernel
) {
6084 init_kernel_tracer();
6085 if (kernel_tracer_fd
>= 0) {
6086 ret
= syscall_init_table();
6088 ERR("Unable to populate syscall table. "
6089 "Syscall tracing won't work "
6090 "for this session daemon.");
6095 /* Set ulimit for open files */
6098 /* init lttng_fd tracking must be done after set_ulimit. */
6101 if (set_consumer_sockets(&ustconsumer64_data
, rundir
)) {
6103 goto exit_init_data
;
6106 if (set_consumer_sockets(&ustconsumer32_data
, rundir
)) {
6108 goto exit_init_data
;
6111 /* Setup the needed unix socket */
6112 if (init_daemon_socket()) {
6114 goto exit_init_data
;
6117 /* Set credentials to socket */
6118 if (is_root
&& set_permissions(rundir
)) {
6120 goto exit_init_data
;
6123 /* Get parent pid if -S, --sig-parent is specified. */
6124 if (opt_sig_parent
) {
6128 /* Setup the kernel pipe for waking up the kernel thread */
6129 if (is_root
&& !opt_no_kernel
) {
6130 if (utils_create_pipe_cloexec(kernel_poll_pipe
)) {
6132 goto exit_init_data
;
6136 /* Setup the thread apps communication pipe. */
6137 if (utils_create_pipe_cloexec(apps_cmd_pipe
)) {
6139 goto exit_init_data
;
6142 /* Setup the thread apps notify communication pipe. */
6143 if (utils_create_pipe_cloexec(apps_cmd_notify_pipe
)) {
6145 goto exit_init_data
;
6148 /* Initialize global buffer per UID and PID registry. */
6149 buffer_reg_init_uid_registry();
6150 buffer_reg_init_pid_registry();
6152 /* Init UST command queue. */
6153 cds_wfcq_init(&ust_cmd_queue
.head
, &ust_cmd_queue
.tail
);
6156 * Get session list pointer. This pointer MUST NOT be free'd. This list
6157 * is statically declared in session.c
6159 session_list_ptr
= session_get_list();
6163 /* Check for the application socket timeout env variable. */
6164 env_app_timeout
= getenv(DEFAULT_APP_SOCKET_TIMEOUT_ENV
);
6165 if (env_app_timeout
) {
6166 app_socket_timeout
= atoi(env_app_timeout
);
6168 app_socket_timeout
= DEFAULT_APP_SOCKET_RW_TIMEOUT
;
6171 ret
= write_pidfile();
6173 ERR("Error in write_pidfile");
6175 goto exit_init_data
;
6177 ret
= write_agent_port();
6179 ERR("Error in write_agent_port");
6181 goto exit_init_data
;
6184 /* Initialize communication library */
6186 /* Initialize TCP timeout values */
6187 lttcomm_inet_init();
6189 if (load_session_init_data(&load_info
) < 0) {
6191 goto exit_init_data
;
6193 load_info
->path
= opt_load_session_path
;
6195 /* Create health-check thread */
6196 ret
= pthread_create(&health_thread
, default_pthread_attr(),
6197 thread_manage_health
, (void *) NULL
);
6200 PERROR("pthread_create health");
6205 /* Create thread to manage the client socket */
6206 ret
= pthread_create(&client_thread
, default_pthread_attr(),
6207 thread_manage_clients
, (void *) NULL
);
6210 PERROR("pthread_create clients");
6215 /* Create thread to dispatch registration */
6216 ret
= pthread_create(&dispatch_thread
, default_pthread_attr(),
6217 thread_dispatch_ust_registration
, (void *) NULL
);
6220 PERROR("pthread_create dispatch");
6225 /* Create thread to manage application registration. */
6226 ret
= pthread_create(®_apps_thread
, default_pthread_attr(),
6227 thread_registration_apps
, (void *) NULL
);
6230 PERROR("pthread_create registration");
6235 /* Create thread to manage application socket */
6236 ret
= pthread_create(&apps_thread
, default_pthread_attr(),
6237 thread_manage_apps
, (void *) NULL
);
6240 PERROR("pthread_create apps");
6245 /* Create thread to manage application notify socket */
6246 ret
= pthread_create(&apps_notify_thread
, default_pthread_attr(),
6247 ust_thread_manage_notify
, (void *) NULL
);
6250 PERROR("pthread_create notify");
6252 goto exit_apps_notify
;
6255 /* Create agent registration thread. */
6256 ret
= pthread_create(&agent_reg_thread
, default_pthread_attr(),
6257 agent_thread_manage_registration
, (void *) NULL
);
6260 PERROR("pthread_create agent");
6262 goto exit_agent_reg
;
6265 /* Don't start this thread if kernel tracing is not requested nor root */
6266 if (is_root
&& !opt_no_kernel
) {
6267 /* Create kernel thread to manage kernel event */
6268 ret
= pthread_create(&kernel_thread
, default_pthread_attr(),
6269 thread_manage_kernel
, (void *) NULL
);
6272 PERROR("pthread_create kernel");
6278 /* Create session loading thread. */
6279 ret
= pthread_create(&load_session_thread
, default_pthread_attr(),
6280 thread_load_session
, load_info
);
6283 PERROR("pthread_create load_session_thread");
6285 goto exit_load_session
;
6289 * This is where we start awaiting program completion (e.g. through
6290 * signal that asks threads to teardown).
6293 ret
= pthread_join(load_session_thread
, &status
);
6296 PERROR("pthread_join load_session_thread");
6301 if (is_root
&& !opt_no_kernel
) {
6302 ret
= pthread_join(kernel_thread
, &status
);
6305 PERROR("pthread_join");
6311 ret
= pthread_join(agent_reg_thread
, &status
);
6314 PERROR("pthread_join agent");
6319 ret
= pthread_join(apps_notify_thread
, &status
);
6322 PERROR("pthread_join apps notify");
6327 ret
= pthread_join(apps_thread
, &status
);
6330 PERROR("pthread_join apps");
6335 ret
= pthread_join(reg_apps_thread
, &status
);
6338 PERROR("pthread_join");
6344 * Join dispatch thread after joining reg_apps_thread to ensure
6345 * we don't leak applications in the queue.
6347 ret
= pthread_join(dispatch_thread
, &status
);
6350 PERROR("pthread_join");
6355 ret
= pthread_join(client_thread
, &status
);
6358 PERROR("pthread_join");
6363 ret
= pthread_join(health_thread
, &status
);
6366 PERROR("pthread_join health thread");
6373 * Wait for all pending call_rcu work to complete before tearing
6374 * down data structures. call_rcu worker may be trying to
6375 * perform lookups in those structures.
6379 * sessiond_cleanup() is called when no other thread is running, except
6380 * the ht_cleanup thread, which is needed to destroy the hash tables.
6382 rcu_thread_online();
6384 rcu_thread_offline();
6385 rcu_unregister_thread();
6388 * Ensure all prior call_rcu are done. call_rcu callbacks may push
6389 * hash tables to the ht_cleanup thread. Therefore, we ensure that
6390 * the queue is empty before shutting down the clean-up thread.
6394 ret
= fini_ht_cleanup_thread(&ht_cleanup_thread
);
6400 health_app_destroy(health_sessiond
);
6401 exit_health_sessiond_cleanup
:
6402 exit_create_run_as_worker_cleanup
:
6405 sessiond_cleanup_options();
6407 exit_set_signal_handler
: