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>
53 #include "lttng-sessiond.h"
54 #include "buffer-registry.h"
61 #include "kernel-consumer.h"
65 #include "ust-consumer.h"
68 #include "health-sessiond.h"
69 #include "testpoint.h"
70 #include "ust-thread.h"
71 #include "agent-thread.h"
73 #include "load-session-thread.h"
76 #include "ht-cleanup.h"
78 #define CONSUMERD_FILE "lttng-consumerd"
81 static const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
82 static int tracing_group_name_override
;
83 static char *opt_pidfile
;
84 static int opt_sig_parent
;
85 static int opt_verbose_consumer
;
86 static int opt_daemon
, opt_background
;
87 static int opt_no_kernel
;
88 static char *opt_load_session_path
;
89 static pid_t ppid
; /* Parent PID for --sig-parent option */
90 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
92 static int lockfile_fd
= -1;
93 static int opt_print_version
;
95 /* Set to 1 when a SIGUSR1 signal is received. */
96 static int recv_child_signal
;
99 * Consumer daemon specific control data. Every value not initialized here is
100 * set to 0 by the static definition.
102 static struct consumer_data kconsumer_data
= {
103 .type
= LTTNG_CONSUMER_KERNEL
,
104 .err_unix_sock_path
= DEFAULT_KCONSUMERD_ERR_SOCK_PATH
,
105 .cmd_unix_sock_path
= DEFAULT_KCONSUMERD_CMD_SOCK_PATH
,
108 .pid_mutex
= PTHREAD_MUTEX_INITIALIZER
,
109 .lock
= PTHREAD_MUTEX_INITIALIZER
,
110 .cond
= PTHREAD_COND_INITIALIZER
,
111 .cond_mutex
= PTHREAD_MUTEX_INITIALIZER
,
113 static struct consumer_data ustconsumer64_data
= {
114 .type
= LTTNG_CONSUMER64_UST
,
115 .err_unix_sock_path
= DEFAULT_USTCONSUMERD64_ERR_SOCK_PATH
,
116 .cmd_unix_sock_path
= DEFAULT_USTCONSUMERD64_CMD_SOCK_PATH
,
119 .pid_mutex
= PTHREAD_MUTEX_INITIALIZER
,
120 .lock
= PTHREAD_MUTEX_INITIALIZER
,
121 .cond
= PTHREAD_COND_INITIALIZER
,
122 .cond_mutex
= PTHREAD_MUTEX_INITIALIZER
,
124 static struct consumer_data ustconsumer32_data
= {
125 .type
= LTTNG_CONSUMER32_UST
,
126 .err_unix_sock_path
= DEFAULT_USTCONSUMERD32_ERR_SOCK_PATH
,
127 .cmd_unix_sock_path
= DEFAULT_USTCONSUMERD32_CMD_SOCK_PATH
,
130 .pid_mutex
= PTHREAD_MUTEX_INITIALIZER
,
131 .lock
= PTHREAD_MUTEX_INITIALIZER
,
132 .cond
= PTHREAD_COND_INITIALIZER
,
133 .cond_mutex
= PTHREAD_MUTEX_INITIALIZER
,
136 /* Command line options */
137 static const struct option long_options
[] = {
138 { "client-sock", required_argument
, 0, 'c' },
139 { "apps-sock", required_argument
, 0, 'a' },
140 { "kconsumerd-cmd-sock", required_argument
, 0, '\0' },
141 { "kconsumerd-err-sock", required_argument
, 0, '\0' },
142 { "ustconsumerd32-cmd-sock", required_argument
, 0, '\0' },
143 { "ustconsumerd32-err-sock", required_argument
, 0, '\0' },
144 { "ustconsumerd64-cmd-sock", required_argument
, 0, '\0' },
145 { "ustconsumerd64-err-sock", required_argument
, 0, '\0' },
146 { "consumerd32-path", required_argument
, 0, '\0' },
147 { "consumerd32-libdir", required_argument
, 0, '\0' },
148 { "consumerd64-path", required_argument
, 0, '\0' },
149 { "consumerd64-libdir", required_argument
, 0, '\0' },
150 { "daemonize", no_argument
, 0, 'd' },
151 { "background", no_argument
, 0, 'b' },
152 { "sig-parent", no_argument
, 0, 'S' },
153 { "help", no_argument
, 0, 'h' },
154 { "group", required_argument
, 0, 'g' },
155 { "version", no_argument
, 0, 'V' },
156 { "quiet", no_argument
, 0, 'q' },
157 { "verbose", no_argument
, 0, 'v' },
158 { "verbose-consumer", no_argument
, 0, '\0' },
159 { "no-kernel", no_argument
, 0, '\0' },
160 { "pidfile", required_argument
, 0, 'p' },
161 { "agent-tcp-port", required_argument
, 0, '\0' },
162 { "config", required_argument
, 0, 'f' },
163 { "load", required_argument
, 0, 'l' },
164 { "kmod-probes", required_argument
, 0, '\0' },
165 { "extra-kmod-probes", required_argument
, 0, '\0' },
169 /* Command line options to ignore from configuration file */
170 static const char *config_ignore_options
[] = { "help", "version", "config" };
172 /* Shared between threads */
173 static int dispatch_thread_exit
;
175 /* Global application Unix socket path */
176 static char apps_unix_sock_path
[PATH_MAX
];
177 /* Global client Unix socket path */
178 static char client_unix_sock_path
[PATH_MAX
];
179 /* global wait shm path for UST */
180 static char wait_shm_path
[PATH_MAX
];
181 /* Global health check unix path */
182 static char health_unix_sock_path
[PATH_MAX
];
184 /* Sockets and FDs */
185 static int client_sock
= -1;
186 static int apps_sock
= -1;
187 int kernel_tracer_fd
= -1;
188 static int kernel_poll_pipe
[2] = { -1, -1 };
191 * Quit pipe for all threads. This permits a single cancellation point
192 * for all threads when receiving an event on the pipe.
194 static int thread_quit_pipe
[2] = { -1, -1 };
197 * This pipe is used to inform the thread managing application communication
198 * that a command is queued and ready to be processed.
200 static int apps_cmd_pipe
[2] = { -1, -1 };
202 int apps_cmd_notify_pipe
[2] = { -1, -1 };
204 /* Pthread, Mutexes and Semaphores */
205 static pthread_t apps_thread
;
206 static pthread_t apps_notify_thread
;
207 static pthread_t reg_apps_thread
;
208 static pthread_t client_thread
;
209 static pthread_t kernel_thread
;
210 static pthread_t dispatch_thread
;
211 static pthread_t health_thread
;
212 static pthread_t ht_cleanup_thread
;
213 static pthread_t agent_reg_thread
;
214 static pthread_t load_session_thread
;
217 * UST registration command queue. This queue is tied with a futex and uses a N
218 * wakers / 1 waiter implemented and detailed in futex.c/.h
220 * The thread_registration_apps and thread_dispatch_ust_registration uses this
221 * queue along with the wait/wake scheme. The thread_manage_apps receives down
222 * the line new application socket and monitors it for any I/O error or clean
223 * close that triggers an unregistration of the application.
225 static struct ust_cmd_queue ust_cmd_queue
;
228 * Pointer initialized before thread creation.
230 * This points to the tracing session list containing the session count and a
231 * mutex lock. The lock MUST be taken if you iterate over the list. The lock
232 * MUST NOT be taken if you call a public function in session.c.
234 * The lock is nested inside the structure: session_list_ptr->lock. Please use
235 * session_lock_list and session_unlock_list for lock acquisition.
237 static struct ltt_session_list
*session_list_ptr
;
239 int ust_consumerd64_fd
= -1;
240 int ust_consumerd32_fd
= -1;
242 static const char *consumerd32_bin
= CONFIG_CONSUMERD32_BIN
;
243 static const char *consumerd64_bin
= CONFIG_CONSUMERD64_BIN
;
244 static const char *consumerd32_libdir
= CONFIG_CONSUMERD32_LIBDIR
;
245 static const char *consumerd64_libdir
= CONFIG_CONSUMERD64_LIBDIR
;
246 static int consumerd32_bin_override
;
247 static int consumerd64_bin_override
;
248 static int consumerd32_libdir_override
;
249 static int consumerd64_libdir_override
;
251 static const char *module_proc_lttng
= "/proc/lttng";
254 * Consumer daemon state which is changed when spawning it, killing it or in
255 * case of a fatal error.
257 enum consumerd_state
{
258 CONSUMER_STARTED
= 1,
259 CONSUMER_STOPPED
= 2,
264 * This consumer daemon state is used to validate if a client command will be
265 * able to reach the consumer. If not, the client is informed. For instance,
266 * doing a "lttng start" when the consumer state is set to ERROR will return an
267 * error to the client.
269 * The following example shows a possible race condition of this scheme:
271 * consumer thread error happens
273 * client cmd checks state -> still OK
274 * consumer thread exit, sets error
275 * client cmd try to talk to consumer
278 * However, since the consumer is a different daemon, we have no way of making
279 * sure the command will reach it safely even with this state flag. This is why
280 * we consider that up to the state validation during command processing, the
281 * command is safe. After that, we can not guarantee the correctness of the
282 * client request vis-a-vis the consumer.
284 static enum consumerd_state ust_consumerd_state
;
285 static enum consumerd_state kernel_consumerd_state
;
288 * Socket timeout for receiving and sending in seconds.
290 static int app_socket_timeout
;
292 /* Set in main() with the current page size. */
295 /* Application health monitoring */
296 struct health_app
*health_sessiond
;
298 /* Agent TCP port for registration. Used by the agent thread. */
299 unsigned int agent_tcp_port
= DEFAULT_AGENT_TCP_PORT
;
301 /* Am I root or not. */
302 int is_root
; /* Set to 1 if the daemon is running as root */
304 const char * const config_section_name
= "sessiond";
306 /* Load session thread information to operate. */
307 struct load_session_thread_data
*load_info
;
309 /* Global hash tables */
310 struct lttng_ht
*agent_apps_ht_by_sock
= NULL
;
313 * The initialization of the session daemon is done in multiple phases.
315 * While all threads are launched near-simultaneously, only some of them
316 * are needed to ensure the session daemon can start to respond to client
319 * There are two important guarantees that we wish to offer with respect
320 * to the initialisation of the session daemon:
321 * - When the daemonize/background launcher process exits, the sessiond
322 * is fully able to respond to client requests,
323 * - Auto-loaded sessions are visible to clients.
325 * In order to achieve this, a number of support threads have to be launched
326 * to allow the "client" thread to function properly. Moreover, since the
327 * "load session" thread needs the client thread, we must provide a way
328 * for the "load session" thread to know that the "client" thread is up
331 * Hence, the support threads decrement the lttng_sessiond_ready counter
332 * while the "client" threads waits for it to reach 0. Once the "client" thread
333 * unblocks, it posts the message_thread_ready semaphore which allows the
334 * "load session" thread to progress.
336 * This implies that the "load session" thread is the last to be initialized
337 * and will explicitly call sessiond_signal_parents(), which signals the parents
338 * that the session daemon is fully initialized.
340 * The two (2) support threads are:
344 int lttng_sessiond_ready
= 2;
346 int sessiond_check_thread_quit_pipe(int fd
, uint32_t events
)
348 return (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) ? 1 : 0;
351 /* Notify parents that we are ready for cmd and health check */
353 void sessiond_signal_parents(void)
356 * Notify parent pid that we are ready to accept command
357 * for client side. This ppid is the one from the
358 * external process that spawned us.
360 if (opt_sig_parent
) {
365 * Notify the parent of the fork() process that we are
368 if (opt_daemon
|| opt_background
) {
369 kill(child_ppid
, SIGUSR1
);
374 void sessiond_notify_ready(void)
377 * The _return variant is used since the implied memory barriers are
380 (void) uatomic_sub_return(<tng_sessiond_ready
, 1);
384 void setup_consumerd_path(void)
386 const char *bin
, *libdir
;
389 * Allow INSTALL_BIN_PATH to be used as a target path for the
390 * native architecture size consumer if CONFIG_CONSUMER*_PATH
391 * has not been defined.
393 #if (CAA_BITS_PER_LONG == 32)
394 if (!consumerd32_bin
[0]) {
395 consumerd32_bin
= INSTALL_BIN_PATH
"/" CONSUMERD_FILE
;
397 if (!consumerd32_libdir
[0]) {
398 consumerd32_libdir
= INSTALL_LIB_PATH
;
400 #elif (CAA_BITS_PER_LONG == 64)
401 if (!consumerd64_bin
[0]) {
402 consumerd64_bin
= INSTALL_BIN_PATH
"/" CONSUMERD_FILE
;
404 if (!consumerd64_libdir
[0]) {
405 consumerd64_libdir
= INSTALL_LIB_PATH
;
408 #error "Unknown bitness"
412 * runtime env. var. overrides the build default.
414 bin
= lttng_secure_getenv("LTTNG_CONSUMERD32_BIN");
416 consumerd32_bin
= bin
;
418 bin
= lttng_secure_getenv("LTTNG_CONSUMERD64_BIN");
420 consumerd64_bin
= bin
;
422 libdir
= lttng_secure_getenv("LTTNG_CONSUMERD32_LIBDIR");
424 consumerd32_libdir
= libdir
;
426 libdir
= lttng_secure_getenv("LTTNG_CONSUMERD64_LIBDIR");
428 consumerd64_libdir
= libdir
;
433 int __sessiond_set_thread_pollset(struct lttng_poll_event
*events
, size_t size
,
440 ret
= lttng_poll_create(events
, size
, LTTNG_CLOEXEC
);
446 ret
= lttng_poll_add(events
, a_pipe
[0], LPOLLIN
| LPOLLERR
);
458 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
460 int sessiond_set_thread_pollset(struct lttng_poll_event
*events
, size_t size
)
462 return __sessiond_set_thread_pollset(events
, size
, thread_quit_pipe
);
466 * Init thread quit pipe.
468 * Return -1 on error or 0 if all pipes are created.
470 static int __init_thread_quit_pipe(int *a_pipe
)
476 PERROR("thread quit pipe");
480 for (i
= 0; i
< 2; i
++) {
481 ret
= fcntl(a_pipe
[i
], F_SETFD
, FD_CLOEXEC
);
492 static int init_thread_quit_pipe(void)
494 return __init_thread_quit_pipe(thread_quit_pipe
);
498 * Stop all threads by closing the thread quit pipe.
500 static void stop_threads(void)
504 /* Stopping all threads */
505 DBG("Terminating all threads");
506 ret
= notify_thread_pipe(thread_quit_pipe
[1]);
508 ERR("write error on thread quit pipe");
511 /* Dispatch thread */
512 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
513 futex_nto1_wake(&ust_cmd_queue
.futex
);
517 * Close every consumer sockets.
519 static void close_consumer_sockets(void)
523 if (kconsumer_data
.err_sock
>= 0) {
524 ret
= close(kconsumer_data
.err_sock
);
526 PERROR("kernel consumer err_sock close");
529 if (ustconsumer32_data
.err_sock
>= 0) {
530 ret
= close(ustconsumer32_data
.err_sock
);
532 PERROR("UST consumerd32 err_sock close");
535 if (ustconsumer64_data
.err_sock
>= 0) {
536 ret
= close(ustconsumer64_data
.err_sock
);
538 PERROR("UST consumerd64 err_sock close");
541 if (kconsumer_data
.cmd_sock
>= 0) {
542 ret
= close(kconsumer_data
.cmd_sock
);
544 PERROR("kernel consumer cmd_sock close");
547 if (ustconsumer32_data
.cmd_sock
>= 0) {
548 ret
= close(ustconsumer32_data
.cmd_sock
);
550 PERROR("UST consumerd32 cmd_sock close");
553 if (ustconsumer64_data
.cmd_sock
>= 0) {
554 ret
= close(ustconsumer64_data
.cmd_sock
);
556 PERROR("UST consumerd64 cmd_sock close");
562 * Generate the full lock file path using the rundir.
564 * Return the snprintf() return value thus a negative value is an error.
566 static int generate_lock_file_path(char *path
, size_t len
)
573 /* Build lockfile path from rundir. */
574 ret
= snprintf(path
, len
, "%s/" DEFAULT_LTTNG_SESSIOND_LOCKFILE
, rundir
);
576 PERROR("snprintf lockfile path");
583 * Wait on consumer process termination.
585 * Need to be called with the consumer data lock held or from a context
586 * ensuring no concurrent access to data (e.g: cleanup).
588 static void wait_consumer(struct consumer_data
*consumer_data
)
593 if (consumer_data
->pid
<= 0) {
597 DBG("Waiting for complete teardown of consumerd (PID: %d)",
599 ret
= waitpid(consumer_data
->pid
, &status
, 0);
601 PERROR("consumerd waitpid pid: %d", consumer_data
->pid
)
602 } else if (!WIFEXITED(status
)) {
603 ERR("consumerd termination with error: %d",
606 consumer_data
->pid
= 0;
610 * Cleanup the session daemon's data structures.
612 static void sessiond_cleanup(void)
615 struct ltt_session
*sess
, *stmp
;
618 DBG("Cleanup sessiond");
621 * Close the thread quit pipe. It has already done its job,
622 * since we are now called.
624 utils_close_pipe(thread_quit_pipe
);
627 * If opt_pidfile is undefined, the default file will be wiped when
628 * removing the rundir.
631 ret
= remove(opt_pidfile
);
633 PERROR("remove pidfile %s", opt_pidfile
);
637 DBG("Removing sessiond and consumerd content of directory %s", rundir
);
640 snprintf(path
, PATH_MAX
,
642 rundir
, DEFAULT_LTTNG_SESSIOND_PIDFILE
);
643 DBG("Removing %s", path
);
646 snprintf(path
, PATH_MAX
, "%s/%s", rundir
,
647 DEFAULT_LTTNG_SESSIOND_AGENTPORT_FILE
);
648 DBG("Removing %s", path
);
652 snprintf(path
, PATH_MAX
,
653 DEFAULT_KCONSUMERD_ERR_SOCK_PATH
,
655 DBG("Removing %s", path
);
658 snprintf(path
, PATH_MAX
,
659 DEFAULT_KCONSUMERD_PATH
,
661 DBG("Removing directory %s", path
);
664 /* ust consumerd 32 */
665 snprintf(path
, PATH_MAX
,
666 DEFAULT_USTCONSUMERD32_ERR_SOCK_PATH
,
668 DBG("Removing %s", path
);
671 snprintf(path
, PATH_MAX
,
672 DEFAULT_USTCONSUMERD32_PATH
,
674 DBG("Removing directory %s", path
);
677 /* ust consumerd 64 */
678 snprintf(path
, PATH_MAX
,
679 DEFAULT_USTCONSUMERD64_ERR_SOCK_PATH
,
681 DBG("Removing %s", path
);
684 snprintf(path
, PATH_MAX
,
685 DEFAULT_USTCONSUMERD64_PATH
,
687 DBG("Removing directory %s", path
);
690 DBG("Cleaning up all sessions");
692 /* Destroy session list mutex */
693 if (session_list_ptr
!= NULL
) {
694 pthread_mutex_destroy(&session_list_ptr
->lock
);
696 /* Cleanup ALL session */
697 cds_list_for_each_entry_safe(sess
, stmp
,
698 &session_list_ptr
->head
, list
) {
699 cmd_destroy_session(sess
, kernel_poll_pipe
[1]);
703 wait_consumer(&kconsumer_data
);
704 wait_consumer(&ustconsumer64_data
);
705 wait_consumer(&ustconsumer32_data
);
707 DBG("Cleaning up all agent apps");
708 agent_app_ht_clean();
710 DBG("Closing all UST sockets");
711 ust_app_clean_list();
712 buffer_reg_destroy_registries();
714 if (is_root
&& !opt_no_kernel
) {
715 DBG2("Closing kernel fd");
716 if (kernel_tracer_fd
>= 0) {
717 ret
= close(kernel_tracer_fd
);
722 DBG("Unloading kernel modules");
723 modprobe_remove_lttng_all();
727 close_consumer_sockets();
730 load_session_destroy_data(load_info
);
735 * Cleanup lock file by deleting it and finaly closing it which will
736 * release the file system lock.
738 if (lockfile_fd
>= 0) {
739 char lockfile_path
[PATH_MAX
];
741 ret
= generate_lock_file_path(lockfile_path
,
742 sizeof(lockfile_path
));
744 ret
= remove(lockfile_path
);
746 PERROR("remove lock file");
748 ret
= close(lockfile_fd
);
750 PERROR("close lock file");
756 * We do NOT rmdir rundir because there are other processes
757 * using it, for instance lttng-relayd, which can start in
758 * parallel with this teardown.
765 * Cleanup the daemon's option data structures.
767 static void sessiond_cleanup_options(void)
769 DBG("Cleaning up options");
772 * If the override option is set, the pointer points to a *non* const
773 * thus freeing it even though the variable type is set to const.
775 if (tracing_group_name_override
) {
776 free((void *) tracing_group_name
);
778 if (consumerd32_bin_override
) {
779 free((void *) consumerd32_bin
);
781 if (consumerd64_bin_override
) {
782 free((void *) consumerd64_bin
);
784 if (consumerd32_libdir_override
) {
785 free((void *) consumerd32_libdir
);
787 if (consumerd64_libdir_override
) {
788 free((void *) consumerd64_libdir
);
792 free(opt_load_session_path
);
793 free(kmod_probes_list
);
794 free(kmod_extra_probes_list
);
796 run_as_destroy_worker();
800 * Send data on a unix socket using the liblttsessiondcomm API.
802 * Return lttcomm error code.
804 static int send_unix_sock(int sock
, void *buf
, size_t len
)
806 /* Check valid length */
811 return lttcomm_send_unix_sock(sock
, buf
, len
);
815 * Free memory of a command context structure.
817 static void clean_command_ctx(struct command_ctx
**cmd_ctx
)
819 DBG("Clean command context structure");
821 if ((*cmd_ctx
)->llm
) {
822 free((*cmd_ctx
)->llm
);
824 if ((*cmd_ctx
)->lsm
) {
825 free((*cmd_ctx
)->lsm
);
833 * Notify UST applications using the shm mmap futex.
835 static int notify_ust_apps(int active
)
839 DBG("Notifying applications of session daemon state: %d", active
);
841 /* See shm.c for this call implying mmap, shm and futex calls */
842 wait_shm_mmap
= shm_ust_get_mmap(wait_shm_path
, is_root
);
843 if (wait_shm_mmap
== NULL
) {
847 /* Wake waiting process */
848 futex_wait_update((int32_t *) wait_shm_mmap
, active
);
850 /* Apps notified successfully */
858 * Setup the outgoing data buffer for the response (llm) by allocating the
859 * right amount of memory and copying the original information from the lsm
862 * Return 0 on success, negative value on error.
864 static int setup_lttng_msg(struct command_ctx
*cmd_ctx
,
865 const void *payload_buf
, size_t payload_len
,
866 const void *cmd_header_buf
, size_t cmd_header_len
)
869 const size_t header_len
= sizeof(struct lttcomm_lttng_msg
);
870 const size_t cmd_header_offset
= header_len
;
871 const size_t payload_offset
= cmd_header_offset
+ cmd_header_len
;
872 const size_t total_msg_size
= header_len
+ cmd_header_len
+ payload_len
;
874 cmd_ctx
->llm
= zmalloc(total_msg_size
);
876 if (cmd_ctx
->llm
== NULL
) {
882 /* Copy common data */
883 cmd_ctx
->llm
->cmd_type
= cmd_ctx
->lsm
->cmd_type
;
884 cmd_ctx
->llm
->pid
= cmd_ctx
->lsm
->domain
.attr
.pid
;
885 cmd_ctx
->llm
->cmd_header_size
= cmd_header_len
;
886 cmd_ctx
->llm
->data_size
= payload_len
;
887 cmd_ctx
->lttng_msg_size
= total_msg_size
;
889 /* Copy command header */
890 if (cmd_header_len
) {
891 memcpy(((uint8_t *) cmd_ctx
->llm
) + cmd_header_offset
, cmd_header_buf
,
897 memcpy(((uint8_t *) cmd_ctx
->llm
) + payload_offset
, payload_buf
,
906 * Version of setup_lttng_msg() without command header.
908 static int setup_lttng_msg_no_cmd_header(struct command_ctx
*cmd_ctx
,
909 void *payload_buf
, size_t payload_len
)
911 return setup_lttng_msg(cmd_ctx
, payload_buf
, payload_len
, NULL
, 0);
914 * Update the kernel poll set of all channel fd available over all tracing
915 * session. Add the wakeup pipe at the end of the set.
917 static int update_kernel_poll(struct lttng_poll_event
*events
)
920 struct ltt_session
*session
;
921 struct ltt_kernel_channel
*channel
;
923 DBG("Updating kernel poll set");
926 cds_list_for_each_entry(session
, &session_list_ptr
->head
, list
) {
927 session_lock(session
);
928 if (session
->kernel_session
== NULL
) {
929 session_unlock(session
);
933 cds_list_for_each_entry(channel
,
934 &session
->kernel_session
->channel_list
.head
, list
) {
935 /* Add channel fd to the kernel poll set */
936 ret
= lttng_poll_add(events
, channel
->fd
, LPOLLIN
| LPOLLRDNORM
);
938 session_unlock(session
);
941 DBG("Channel fd %d added to kernel set", channel
->fd
);
943 session_unlock(session
);
945 session_unlock_list();
950 session_unlock_list();
955 * Find the channel fd from 'fd' over all tracing session. When found, check
956 * for new channel stream and send those stream fds to the kernel consumer.
958 * Useful for CPU hotplug feature.
960 static int update_kernel_stream(struct consumer_data
*consumer_data
, int fd
)
963 struct ltt_session
*session
;
964 struct ltt_kernel_session
*ksess
;
965 struct ltt_kernel_channel
*channel
;
967 DBG("Updating kernel streams for channel fd %d", fd
);
970 cds_list_for_each_entry(session
, &session_list_ptr
->head
, list
) {
971 session_lock(session
);
972 if (session
->kernel_session
== NULL
) {
973 session_unlock(session
);
976 ksess
= session
->kernel_session
;
978 cds_list_for_each_entry(channel
,
979 &ksess
->channel_list
.head
, list
) {
980 struct lttng_ht_iter iter
;
981 struct consumer_socket
*socket
;
983 if (channel
->fd
!= fd
) {
986 DBG("Channel found, updating kernel streams");
987 ret
= kernel_open_channel_stream(channel
);
991 /* Update the stream global counter */
992 ksess
->stream_count_global
+= ret
;
995 * Have we already sent fds to the consumer? If yes, it
996 * means that tracing is started so it is safe to send
997 * our updated stream fds.
999 if (ksess
->consumer_fds_sent
!= 1
1000 || ksess
->consumer
== NULL
) {
1006 cds_lfht_for_each_entry(ksess
->consumer
->socks
->ht
,
1007 &iter
.iter
, socket
, node
.node
) {
1008 pthread_mutex_lock(socket
->lock
);
1009 ret
= kernel_consumer_send_channel_stream(socket
,
1011 session
->output_traces
? 1 : 0);
1012 pthread_mutex_unlock(socket
->lock
);
1020 session_unlock(session
);
1022 session_unlock_list();
1026 session_unlock(session
);
1027 session_unlock_list();
1032 * For each tracing session, update newly registered apps. The session list
1033 * lock MUST be acquired before calling this.
1035 static void update_ust_app(int app_sock
)
1037 struct ltt_session
*sess
, *stmp
;
1039 /* Consumer is in an ERROR state. Stop any application update. */
1040 if (uatomic_read(&ust_consumerd_state
) == CONSUMER_ERROR
) {
1041 /* Stop the update process since the consumer is dead. */
1045 /* For all tracing session(s) */
1046 cds_list_for_each_entry_safe(sess
, stmp
, &session_list_ptr
->head
, list
) {
1047 struct ust_app
*app
;
1050 if (!sess
->ust_session
) {
1051 goto unlock_session
;
1055 assert(app_sock
>= 0);
1056 app
= ust_app_find_by_sock(app_sock
);
1059 * Application can be unregistered before so
1060 * this is possible hence simply stopping the
1063 DBG3("UST app update failed to find app sock %d",
1067 ust_app_global_update(sess
->ust_session
, app
);
1071 session_unlock(sess
);
1076 * This thread manage event coming from the kernel.
1078 * Features supported in this thread:
1081 static void *thread_manage_kernel(void *data
)
1083 int ret
, i
, pollfd
, update_poll_flag
= 1, err
= -1;
1084 uint32_t revents
, nb_fd
;
1086 struct lttng_poll_event events
;
1088 DBG("[thread] Thread manage kernel started");
1090 health_register(health_sessiond
, HEALTH_SESSIOND_TYPE_KERNEL
);
1093 * This first step of the while is to clean this structure which could free
1094 * non NULL pointers so initialize it before the loop.
1096 lttng_poll_init(&events
);
1098 if (testpoint(sessiond_thread_manage_kernel
)) {
1099 goto error_testpoint
;
1102 health_code_update();
1104 if (testpoint(sessiond_thread_manage_kernel_before_loop
)) {
1105 goto error_testpoint
;
1109 health_code_update();
1111 if (update_poll_flag
== 1) {
1112 /* Clean events object. We are about to populate it again. */
1113 lttng_poll_clean(&events
);
1115 ret
= sessiond_set_thread_pollset(&events
, 2);
1117 goto error_poll_create
;
1120 ret
= lttng_poll_add(&events
, kernel_poll_pipe
[0], LPOLLIN
);
1125 /* This will add the available kernel channel if any. */
1126 ret
= update_kernel_poll(&events
);
1130 update_poll_flag
= 0;
1133 DBG("Thread kernel polling");
1135 /* Poll infinite value of time */
1137 health_poll_entry();
1138 ret
= lttng_poll_wait(&events
, -1);
1139 DBG("Thread kernel return from poll on %d fds",
1140 LTTNG_POLL_GETNB(&events
));
1144 * Restart interrupted system call.
1146 if (errno
== EINTR
) {
1150 } else if (ret
== 0) {
1151 /* Should not happen since timeout is infinite */
1152 ERR("Return value of poll is 0 with an infinite timeout.\n"
1153 "This should not have happened! Continuing...");
1159 for (i
= 0; i
< nb_fd
; i
++) {
1160 /* Fetch once the poll data */
1161 revents
= LTTNG_POLL_GETEV(&events
, i
);
1162 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
1164 health_code_update();
1167 /* No activity for this FD (poll implementation). */
1171 /* Thread quit pipe has been closed. Killing thread. */
1172 ret
= sessiond_check_thread_quit_pipe(pollfd
, revents
);
1178 /* Check for data on kernel pipe */
1179 if (revents
& LPOLLIN
) {
1180 if (pollfd
== kernel_poll_pipe
[0]) {
1181 (void) lttng_read(kernel_poll_pipe
[0],
1184 * Ret value is useless here, if this pipe gets any actions an
1185 * update is required anyway.
1187 update_poll_flag
= 1;
1191 * New CPU detected by the kernel. Adding kernel stream to
1192 * kernel session and updating the kernel consumer
1194 ret
= update_kernel_stream(&kconsumer_data
, pollfd
);
1200 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1201 update_poll_flag
= 1;
1204 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1212 lttng_poll_clean(&events
);
1215 utils_close_pipe(kernel_poll_pipe
);
1216 kernel_poll_pipe
[0] = kernel_poll_pipe
[1] = -1;
1219 ERR("Health error occurred in %s", __func__
);
1220 WARN("Kernel thread died unexpectedly. "
1221 "Kernel tracing can continue but CPU hotplug is disabled.");
1223 health_unregister(health_sessiond
);
1224 DBG("Kernel thread dying");
1229 * Signal pthread condition of the consumer data that the thread.
1231 static void signal_consumer_condition(struct consumer_data
*data
, int state
)
1233 pthread_mutex_lock(&data
->cond_mutex
);
1236 * The state is set before signaling. It can be any value, it's the waiter
1237 * job to correctly interpret this condition variable associated to the
1238 * consumer pthread_cond.
1240 * A value of 0 means that the corresponding thread of the consumer data
1241 * was not started. 1 indicates that the thread has started and is ready
1242 * for action. A negative value means that there was an error during the
1245 data
->consumer_thread_is_ready
= state
;
1246 (void) pthread_cond_signal(&data
->cond
);
1248 pthread_mutex_unlock(&data
->cond_mutex
);
1252 * This thread manage the consumer error sent back to the session daemon.
1254 static void *thread_manage_consumer(void *data
)
1256 int sock
= -1, i
, ret
, pollfd
, err
= -1, should_quit
= 0;
1257 uint32_t revents
, nb_fd
;
1258 enum lttcomm_return_code code
;
1259 struct lttng_poll_event events
;
1260 struct consumer_data
*consumer_data
= data
;
1262 DBG("[thread] Manage consumer started");
1264 rcu_register_thread();
1265 rcu_thread_online();
1267 health_register(health_sessiond
, HEALTH_SESSIOND_TYPE_CONSUMER
);
1269 health_code_update();
1272 * Pass 3 as size here for the thread quit pipe, consumerd_err_sock and the
1273 * metadata_sock. Nothing more will be added to this poll set.
1275 ret
= sessiond_set_thread_pollset(&events
, 3);
1281 * The error socket here is already in a listening state which was done
1282 * just before spawning this thread to avoid a race between the consumer
1283 * daemon exec trying to connect and the listen() call.
1285 ret
= lttng_poll_add(&events
, consumer_data
->err_sock
, LPOLLIN
| LPOLLRDHUP
);
1290 health_code_update();
1292 /* Infinite blocking call, waiting for transmission */
1294 health_poll_entry();
1296 if (testpoint(sessiond_thread_manage_consumer
)) {
1300 ret
= lttng_poll_wait(&events
, -1);
1304 * Restart interrupted system call.
1306 if (errno
== EINTR
) {
1314 for (i
= 0; i
< nb_fd
; i
++) {
1315 /* Fetch once the poll data */
1316 revents
= LTTNG_POLL_GETEV(&events
, i
);
1317 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
1319 health_code_update();
1322 /* No activity for this FD (poll implementation). */
1326 /* Thread quit pipe has been closed. Killing thread. */
1327 ret
= sessiond_check_thread_quit_pipe(pollfd
, revents
);
1333 /* Event on the registration socket */
1334 if (pollfd
== consumer_data
->err_sock
) {
1335 if (revents
& LPOLLIN
) {
1337 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1338 ERR("consumer err socket poll error");
1341 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1347 sock
= lttcomm_accept_unix_sock(consumer_data
->err_sock
);
1353 * Set the CLOEXEC flag. Return code is useless because either way, the
1356 (void) utils_set_fd_cloexec(sock
);
1358 health_code_update();
1360 DBG2("Receiving code from consumer err_sock");
1362 /* Getting status code from kconsumerd */
1363 ret
= lttcomm_recv_unix_sock(sock
, &code
,
1364 sizeof(enum lttcomm_return_code
));
1369 health_code_update();
1370 if (code
== LTTCOMM_CONSUMERD_COMMAND_SOCK_READY
) {
1371 /* Connect both socket, command and metadata. */
1372 consumer_data
->cmd_sock
=
1373 lttcomm_connect_unix_sock(consumer_data
->cmd_unix_sock_path
);
1374 consumer_data
->metadata_fd
=
1375 lttcomm_connect_unix_sock(consumer_data
->cmd_unix_sock_path
);
1376 if (consumer_data
->cmd_sock
< 0
1377 || consumer_data
->metadata_fd
< 0) {
1378 PERROR("consumer connect cmd socket");
1379 /* On error, signal condition and quit. */
1380 signal_consumer_condition(consumer_data
, -1);
1383 consumer_data
->metadata_sock
.fd_ptr
= &consumer_data
->metadata_fd
;
1384 /* Create metadata socket lock. */
1385 consumer_data
->metadata_sock
.lock
= zmalloc(sizeof(pthread_mutex_t
));
1386 if (consumer_data
->metadata_sock
.lock
== NULL
) {
1387 PERROR("zmalloc pthread mutex");
1390 pthread_mutex_init(consumer_data
->metadata_sock
.lock
, NULL
);
1392 signal_consumer_condition(consumer_data
, 1);
1393 DBG("Consumer command socket ready (fd: %d", consumer_data
->cmd_sock
);
1394 DBG("Consumer metadata socket ready (fd: %d)",
1395 consumer_data
->metadata_fd
);
1397 ERR("consumer error when waiting for SOCK_READY : %s",
1398 lttcomm_get_readable_code(-code
));
1402 /* Remove the consumerd error sock since we've established a connexion */
1403 ret
= lttng_poll_del(&events
, consumer_data
->err_sock
);
1408 /* Add new accepted error socket. */
1409 ret
= lttng_poll_add(&events
, sock
, LPOLLIN
| LPOLLRDHUP
);
1414 /* Add metadata socket that is successfully connected. */
1415 ret
= lttng_poll_add(&events
, consumer_data
->metadata_fd
,
1416 LPOLLIN
| LPOLLRDHUP
);
1421 health_code_update();
1423 /* Infinite blocking call, waiting for transmission */
1426 health_code_update();
1428 /* Exit the thread because the thread quit pipe has been triggered. */
1430 /* Not a health error. */
1435 health_poll_entry();
1436 ret
= lttng_poll_wait(&events
, -1);
1440 * Restart interrupted system call.
1442 if (errno
== EINTR
) {
1450 for (i
= 0; i
< nb_fd
; i
++) {
1451 /* Fetch once the poll data */
1452 revents
= LTTNG_POLL_GETEV(&events
, i
);
1453 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
1455 health_code_update();
1458 /* No activity for this FD (poll implementation). */
1463 * Thread quit pipe has been triggered, flag that we should stop
1464 * but continue the current loop to handle potential data from
1467 should_quit
= sessiond_check_thread_quit_pipe(pollfd
, revents
);
1469 if (pollfd
== sock
) {
1470 /* Event on the consumerd socket */
1471 if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)
1472 && !(revents
& LPOLLIN
)) {
1473 ERR("consumer err socket second poll error");
1476 health_code_update();
1477 /* Wait for any kconsumerd error */
1478 ret
= lttcomm_recv_unix_sock(sock
, &code
,
1479 sizeof(enum lttcomm_return_code
));
1481 ERR("consumer closed the command socket");
1485 ERR("consumer return code : %s",
1486 lttcomm_get_readable_code(-code
));
1489 } else if (pollfd
== consumer_data
->metadata_fd
) {
1490 if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)
1491 && !(revents
& LPOLLIN
)) {
1492 ERR("consumer err metadata socket second poll error");
1495 /* UST metadata requests */
1496 ret
= ust_consumer_metadata_request(
1497 &consumer_data
->metadata_sock
);
1499 ERR("Handling metadata request");
1503 /* No need for an else branch all FDs are tested prior. */
1505 health_code_update();
1511 * We lock here because we are about to close the sockets and some other
1512 * thread might be using them so get exclusive access which will abort all
1513 * other consumer command by other threads.
1515 pthread_mutex_lock(&consumer_data
->lock
);
1517 /* Immediately set the consumerd state to stopped */
1518 if (consumer_data
->type
== LTTNG_CONSUMER_KERNEL
) {
1519 uatomic_set(&kernel_consumerd_state
, CONSUMER_ERROR
);
1520 } else if (consumer_data
->type
== LTTNG_CONSUMER64_UST
||
1521 consumer_data
->type
== LTTNG_CONSUMER32_UST
) {
1522 uatomic_set(&ust_consumerd_state
, CONSUMER_ERROR
);
1524 /* Code flow error... */
1528 if (consumer_data
->err_sock
>= 0) {
1529 ret
= close(consumer_data
->err_sock
);
1533 consumer_data
->err_sock
= -1;
1535 if (consumer_data
->cmd_sock
>= 0) {
1536 ret
= close(consumer_data
->cmd_sock
);
1540 consumer_data
->cmd_sock
= -1;
1542 if (consumer_data
->metadata_sock
.fd_ptr
&&
1543 *consumer_data
->metadata_sock
.fd_ptr
>= 0) {
1544 ret
= close(*consumer_data
->metadata_sock
.fd_ptr
);
1556 unlink(consumer_data
->err_unix_sock_path
);
1557 unlink(consumer_data
->cmd_unix_sock_path
);
1558 pthread_mutex_unlock(&consumer_data
->lock
);
1560 /* Cleanup metadata socket mutex. */
1561 if (consumer_data
->metadata_sock
.lock
) {
1562 pthread_mutex_destroy(consumer_data
->metadata_sock
.lock
);
1563 free(consumer_data
->metadata_sock
.lock
);
1565 lttng_poll_clean(&events
);
1569 ERR("Health error occurred in %s", __func__
);
1571 health_unregister(health_sessiond
);
1572 DBG("consumer thread cleanup completed");
1574 rcu_thread_offline();
1575 rcu_unregister_thread();
1581 * This thread manage application communication.
1583 static void *thread_manage_apps(void *data
)
1585 int i
, ret
, pollfd
, err
= -1;
1587 uint32_t revents
, nb_fd
;
1588 struct lttng_poll_event events
;
1590 DBG("[thread] Manage application started");
1592 rcu_register_thread();
1593 rcu_thread_online();
1595 health_register(health_sessiond
, HEALTH_SESSIOND_TYPE_APP_MANAGE
);
1597 if (testpoint(sessiond_thread_manage_apps
)) {
1598 goto error_testpoint
;
1601 health_code_update();
1603 ret
= sessiond_set_thread_pollset(&events
, 2);
1605 goto error_poll_create
;
1608 ret
= lttng_poll_add(&events
, apps_cmd_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
1613 if (testpoint(sessiond_thread_manage_apps_before_loop
)) {
1617 health_code_update();
1620 DBG("Apps thread polling");
1622 /* Inifinite blocking call, waiting for transmission */
1624 health_poll_entry();
1625 ret
= lttng_poll_wait(&events
, -1);
1626 DBG("Apps thread return from poll on %d fds",
1627 LTTNG_POLL_GETNB(&events
));
1631 * Restart interrupted system call.
1633 if (errno
== EINTR
) {
1641 for (i
= 0; i
< nb_fd
; i
++) {
1642 /* Fetch once the poll data */
1643 revents
= LTTNG_POLL_GETEV(&events
, i
);
1644 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
1646 health_code_update();
1649 /* No activity for this FD (poll implementation). */
1653 /* Thread quit pipe has been closed. Killing thread. */
1654 ret
= sessiond_check_thread_quit_pipe(pollfd
, revents
);
1660 /* Inspect the apps cmd pipe */
1661 if (pollfd
== apps_cmd_pipe
[0]) {
1662 if (revents
& LPOLLIN
) {
1666 size_ret
= lttng_read(apps_cmd_pipe
[0], &sock
, sizeof(sock
));
1667 if (size_ret
< sizeof(sock
)) {
1668 PERROR("read apps cmd pipe");
1672 health_code_update();
1675 * Since this is a command socket (write then read),
1676 * we only monitor the error events of the socket.
1678 ret
= lttng_poll_add(&events
, sock
,
1679 LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
);
1684 DBG("Apps with sock %d added to poll set", sock
);
1685 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1686 ERR("Apps command pipe error");
1689 ERR("Unknown poll events %u for sock %d", revents
, pollfd
);
1694 * At this point, we know that a registered application made
1695 * the event at poll_wait.
1697 if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1698 /* Removing from the poll set */
1699 ret
= lttng_poll_del(&events
, pollfd
);
1704 /* Socket closed on remote end. */
1705 ust_app_unregister(pollfd
);
1707 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1712 health_code_update();
1718 lttng_poll_clean(&events
);
1721 utils_close_pipe(apps_cmd_pipe
);
1722 apps_cmd_pipe
[0] = apps_cmd_pipe
[1] = -1;
1725 * We don't clean the UST app hash table here since already registered
1726 * applications can still be controlled so let them be until the session
1727 * daemon dies or the applications stop.
1732 ERR("Health error occurred in %s", __func__
);
1734 health_unregister(health_sessiond
);
1735 DBG("Application communication apps thread cleanup complete");
1736 rcu_thread_offline();
1737 rcu_unregister_thread();
1742 * Send a socket to a thread This is called from the dispatch UST registration
1743 * thread once all sockets are set for the application.
1745 * The sock value can be invalid, we don't really care, the thread will handle
1746 * it and make the necessary cleanup if so.
1748 * On success, return 0 else a negative value being the errno message of the
1751 static int send_socket_to_thread(int fd
, int sock
)
1756 * It's possible that the FD is set as invalid with -1 concurrently just
1757 * before calling this function being a shutdown state of the thread.
1764 ret
= lttng_write(fd
, &sock
, sizeof(sock
));
1765 if (ret
< sizeof(sock
)) {
1766 PERROR("write apps pipe %d", fd
);
1773 /* All good. Don't send back the write positive ret value. */
1780 * Sanitize the wait queue of the dispatch registration thread meaning removing
1781 * invalid nodes from it. This is to avoid memory leaks for the case the UST
1782 * notify socket is never received.
1784 static void sanitize_wait_queue(struct ust_reg_wait_queue
*wait_queue
)
1786 int ret
, nb_fd
= 0, i
;
1787 unsigned int fd_added
= 0;
1788 struct lttng_poll_event events
;
1789 struct ust_reg_wait_node
*wait_node
= NULL
, *tmp_wait_node
;
1793 lttng_poll_init(&events
);
1795 /* Just skip everything for an empty queue. */
1796 if (!wait_queue
->count
) {
1800 ret
= lttng_poll_create(&events
, wait_queue
->count
, LTTNG_CLOEXEC
);
1805 cds_list_for_each_entry_safe(wait_node
, tmp_wait_node
,
1806 &wait_queue
->head
, head
) {
1807 assert(wait_node
->app
);
1808 ret
= lttng_poll_add(&events
, wait_node
->app
->sock
,
1809 LPOLLHUP
| LPOLLERR
);
1822 * Poll but don't block so we can quickly identify the faulty events and
1823 * clean them afterwards from the wait queue.
1825 ret
= lttng_poll_wait(&events
, 0);
1831 for (i
= 0; i
< nb_fd
; i
++) {
1832 /* Get faulty FD. */
1833 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
1834 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
1837 /* No activity for this FD (poll implementation). */
1841 cds_list_for_each_entry_safe(wait_node
, tmp_wait_node
,
1842 &wait_queue
->head
, head
) {
1843 if (pollfd
== wait_node
->app
->sock
&&
1844 (revents
& (LPOLLHUP
| LPOLLERR
))) {
1845 cds_list_del(&wait_node
->head
);
1846 wait_queue
->count
--;
1847 ust_app_destroy(wait_node
->app
);
1850 * Silence warning of use-after-free in
1851 * cds_list_for_each_entry_safe which uses
1852 * __typeof__(*wait_node).
1857 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1864 DBG("Wait queue sanitized, %d node were cleaned up", nb_fd
);
1868 lttng_poll_clean(&events
);
1872 lttng_poll_clean(&events
);
1874 ERR("Unable to sanitize wait queue");
1879 * Dispatch request from the registration threads to the application
1880 * communication thread.
1882 static void *thread_dispatch_ust_registration(void *data
)
1885 struct cds_wfcq_node
*node
;
1886 struct ust_command
*ust_cmd
= NULL
;
1887 struct ust_reg_wait_node
*wait_node
= NULL
, *tmp_wait_node
;
1888 struct ust_reg_wait_queue wait_queue
= {
1892 rcu_register_thread();
1894 health_register(health_sessiond
, HEALTH_SESSIOND_TYPE_APP_REG_DISPATCH
);
1896 if (testpoint(sessiond_thread_app_reg_dispatch
)) {
1897 goto error_testpoint
;
1900 health_code_update();
1902 CDS_INIT_LIST_HEAD(&wait_queue
.head
);
1904 DBG("[thread] Dispatch UST command started");
1907 health_code_update();
1909 /* Atomically prepare the queue futex */
1910 futex_nto1_prepare(&ust_cmd_queue
.futex
);
1912 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1917 struct ust_app
*app
= NULL
;
1921 * Make sure we don't have node(s) that have hung up before receiving
1922 * the notify socket. This is to clean the list in order to avoid
1923 * memory leaks from notify socket that are never seen.
1925 sanitize_wait_queue(&wait_queue
);
1927 health_code_update();
1928 /* Dequeue command for registration */
1929 node
= cds_wfcq_dequeue_blocking(&ust_cmd_queue
.head
, &ust_cmd_queue
.tail
);
1931 DBG("Woken up but nothing in the UST command queue");
1932 /* Continue thread execution */
1936 ust_cmd
= caa_container_of(node
, struct ust_command
, node
);
1938 DBG("Dispatching UST registration pid:%d ppid:%d uid:%d"
1939 " gid:%d sock:%d name:%s (version %d.%d)",
1940 ust_cmd
->reg_msg
.pid
, ust_cmd
->reg_msg
.ppid
,
1941 ust_cmd
->reg_msg
.uid
, ust_cmd
->reg_msg
.gid
,
1942 ust_cmd
->sock
, ust_cmd
->reg_msg
.name
,
1943 ust_cmd
->reg_msg
.major
, ust_cmd
->reg_msg
.minor
);
1945 if (ust_cmd
->reg_msg
.type
== USTCTL_SOCKET_CMD
) {
1946 wait_node
= zmalloc(sizeof(*wait_node
));
1948 PERROR("zmalloc wait_node dispatch");
1949 ret
= close(ust_cmd
->sock
);
1951 PERROR("close ust sock dispatch %d", ust_cmd
->sock
);
1953 lttng_fd_put(LTTNG_FD_APPS
, 1);
1957 CDS_INIT_LIST_HEAD(&wait_node
->head
);
1959 /* Create application object if socket is CMD. */
1960 wait_node
->app
= ust_app_create(&ust_cmd
->reg_msg
,
1962 if (!wait_node
->app
) {
1963 ret
= close(ust_cmd
->sock
);
1965 PERROR("close ust sock dispatch %d", ust_cmd
->sock
);
1967 lttng_fd_put(LTTNG_FD_APPS
, 1);
1973 * Add application to the wait queue so we can set the notify
1974 * socket before putting this object in the global ht.
1976 cds_list_add(&wait_node
->head
, &wait_queue
.head
);
1981 * We have to continue here since we don't have the notify
1982 * socket and the application MUST be added to the hash table
1983 * only at that moment.
1988 * Look for the application in the local wait queue and set the
1989 * notify socket if found.
1991 cds_list_for_each_entry_safe(wait_node
, tmp_wait_node
,
1992 &wait_queue
.head
, head
) {
1993 health_code_update();
1994 if (wait_node
->app
->pid
== ust_cmd
->reg_msg
.pid
) {
1995 wait_node
->app
->notify_sock
= ust_cmd
->sock
;
1996 cds_list_del(&wait_node
->head
);
1998 app
= wait_node
->app
;
2000 DBG3("UST app notify socket %d is set", ust_cmd
->sock
);
2006 * With no application at this stage the received socket is
2007 * basically useless so close it before we free the cmd data
2008 * structure for good.
2011 ret
= close(ust_cmd
->sock
);
2013 PERROR("close ust sock dispatch %d", ust_cmd
->sock
);
2015 lttng_fd_put(LTTNG_FD_APPS
, 1);
2022 * @session_lock_list
2024 * Lock the global session list so from the register up to the
2025 * registration done message, no thread can see the application
2026 * and change its state.
2028 session_lock_list();
2032 * Add application to the global hash table. This needs to be
2033 * done before the update to the UST registry can locate the
2038 /* Set app version. This call will print an error if needed. */
2039 (void) ust_app_version(app
);
2041 /* Send notify socket through the notify pipe. */
2042 ret
= send_socket_to_thread(apps_cmd_notify_pipe
[1],
2046 session_unlock_list();
2048 * No notify thread, stop the UST tracing. However, this is
2049 * not an internal error of the this thread thus setting
2050 * the health error code to a normal exit.
2057 * Update newly registered application with the tracing
2058 * registry info already enabled information.
2060 update_ust_app(app
->sock
);
2063 * Don't care about return value. Let the manage apps threads
2064 * handle app unregistration upon socket close.
2066 (void) ust_app_register_done(app
);
2069 * Even if the application socket has been closed, send the app
2070 * to the thread and unregistration will take place at that
2073 ret
= send_socket_to_thread(apps_cmd_pipe
[1], app
->sock
);
2076 session_unlock_list();
2078 * No apps. thread, stop the UST tracing. However, this is
2079 * not an internal error of the this thread thus setting
2080 * the health error code to a normal exit.
2087 session_unlock_list();
2089 } while (node
!= NULL
);
2091 health_poll_entry();
2092 /* Futex wait on queue. Blocking call on futex() */
2093 futex_nto1_wait(&ust_cmd_queue
.futex
);
2096 /* Normal exit, no error */
2100 /* Clean up wait queue. */
2101 cds_list_for_each_entry_safe(wait_node
, tmp_wait_node
,
2102 &wait_queue
.head
, head
) {
2103 cds_list_del(&wait_node
->head
);
2108 /* Empty command queue. */
2110 /* Dequeue command for registration */
2111 node
= cds_wfcq_dequeue_blocking(&ust_cmd_queue
.head
, &ust_cmd_queue
.tail
);
2115 ust_cmd
= caa_container_of(node
, struct ust_command
, node
);
2116 ret
= close(ust_cmd
->sock
);
2118 PERROR("close ust sock exit dispatch %d", ust_cmd
->sock
);
2120 lttng_fd_put(LTTNG_FD_APPS
, 1);
2125 DBG("Dispatch thread dying");
2128 ERR("Health error occurred in %s", __func__
);
2130 health_unregister(health_sessiond
);
2131 rcu_unregister_thread();
2136 * This thread manage application registration.
2138 static void *thread_registration_apps(void *data
)
2140 int sock
= -1, i
, ret
, pollfd
, err
= -1;
2141 uint32_t revents
, nb_fd
;
2142 struct lttng_poll_event events
;
2144 * Get allocated in this thread, enqueued to a global queue, dequeued and
2145 * freed in the manage apps thread.
2147 struct ust_command
*ust_cmd
= NULL
;
2149 DBG("[thread] Manage application registration started");
2151 health_register(health_sessiond
, HEALTH_SESSIOND_TYPE_APP_REG
);
2153 if (testpoint(sessiond_thread_registration_apps
)) {
2154 goto error_testpoint
;
2157 ret
= lttcomm_listen_unix_sock(apps_sock
);
2163 * Pass 2 as size here for the thread quit pipe and apps socket. Nothing
2164 * more will be added to this poll set.
2166 ret
= sessiond_set_thread_pollset(&events
, 2);
2168 goto error_create_poll
;
2171 /* Add the application registration socket */
2172 ret
= lttng_poll_add(&events
, apps_sock
, LPOLLIN
| LPOLLRDHUP
);
2174 goto error_poll_add
;
2177 /* Notify all applications to register */
2178 ret
= notify_ust_apps(1);
2180 ERR("Failed to notify applications or create the wait shared memory.\n"
2181 "Execution continues but there might be problem for already\n"
2182 "running applications that wishes to register.");
2186 DBG("Accepting application registration");
2188 /* Inifinite blocking call, waiting for transmission */
2190 health_poll_entry();
2191 ret
= lttng_poll_wait(&events
, -1);
2195 * Restart interrupted system call.
2197 if (errno
== EINTR
) {
2205 for (i
= 0; i
< nb_fd
; i
++) {
2206 health_code_update();
2208 /* Fetch once the poll data */
2209 revents
= LTTNG_POLL_GETEV(&events
, i
);
2210 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2213 /* No activity for this FD (poll implementation). */
2217 /* Thread quit pipe has been closed. Killing thread. */
2218 ret
= sessiond_check_thread_quit_pipe(pollfd
, revents
);
2224 /* Event on the registration socket */
2225 if (pollfd
== apps_sock
) {
2226 if (revents
& LPOLLIN
) {
2227 sock
= lttcomm_accept_unix_sock(apps_sock
);
2233 * Set socket timeout for both receiving and ending.
2234 * app_socket_timeout is in seconds, whereas
2235 * lttcomm_setsockopt_rcv_timeout and
2236 * lttcomm_setsockopt_snd_timeout expect msec as
2239 if (app_socket_timeout
>= 0) {
2240 (void) lttcomm_setsockopt_rcv_timeout(sock
,
2241 app_socket_timeout
* 1000);
2242 (void) lttcomm_setsockopt_snd_timeout(sock
,
2243 app_socket_timeout
* 1000);
2247 * Set the CLOEXEC flag. Return code is useless because
2248 * either way, the show must go on.
2250 (void) utils_set_fd_cloexec(sock
);
2252 /* Create UST registration command for enqueuing */
2253 ust_cmd
= zmalloc(sizeof(struct ust_command
));
2254 if (ust_cmd
== NULL
) {
2255 PERROR("ust command zmalloc");
2264 * Using message-based transmissions to ensure we don't
2265 * have to deal with partially received messages.
2267 ret
= lttng_fd_get(LTTNG_FD_APPS
, 1);
2269 ERR("Exhausted file descriptors allowed for applications.");
2279 health_code_update();
2280 ret
= ust_app_recv_registration(sock
, &ust_cmd
->reg_msg
);
2283 /* Close socket of the application. */
2288 lttng_fd_put(LTTNG_FD_APPS
, 1);
2292 health_code_update();
2294 ust_cmd
->sock
= sock
;
2297 DBG("UST registration received with pid:%d ppid:%d uid:%d"
2298 " gid:%d sock:%d name:%s (version %d.%d)",
2299 ust_cmd
->reg_msg
.pid
, ust_cmd
->reg_msg
.ppid
,
2300 ust_cmd
->reg_msg
.uid
, ust_cmd
->reg_msg
.gid
,
2301 ust_cmd
->sock
, ust_cmd
->reg_msg
.name
,
2302 ust_cmd
->reg_msg
.major
, ust_cmd
->reg_msg
.minor
);
2305 * Lock free enqueue the registration request. The red pill
2306 * has been taken! This apps will be part of the *system*.
2308 cds_wfcq_enqueue(&ust_cmd_queue
.head
, &ust_cmd_queue
.tail
, &ust_cmd
->node
);
2311 * Wake the registration queue futex. Implicit memory
2312 * barrier with the exchange in cds_wfcq_enqueue.
2314 futex_nto1_wake(&ust_cmd_queue
.futex
);
2315 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2316 ERR("Register apps socket poll error");
2319 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
2328 /* Notify that the registration thread is gone */
2331 if (apps_sock
>= 0) {
2332 ret
= close(apps_sock
);
2342 lttng_fd_put(LTTNG_FD_APPS
, 1);
2344 unlink(apps_unix_sock_path
);
2347 lttng_poll_clean(&events
);
2351 DBG("UST Registration thread cleanup complete");
2354 ERR("Health error occurred in %s", __func__
);
2356 health_unregister(health_sessiond
);
2362 * Start the thread_manage_consumer. This must be done after a lttng-consumerd
2363 * exec or it will fails.
2365 static int spawn_consumer_thread(struct consumer_data
*consumer_data
)
2368 struct timespec timeout
;
2371 * Make sure we set the readiness flag to 0 because we are NOT ready.
2372 * This access to consumer_thread_is_ready does not need to be
2373 * protected by consumer_data.cond_mutex (yet) since the consumer
2374 * management thread has not been started at this point.
2376 consumer_data
->consumer_thread_is_ready
= 0;
2378 /* Setup pthread condition */
2379 ret
= pthread_condattr_init(&consumer_data
->condattr
);
2382 PERROR("pthread_condattr_init consumer data");
2387 * Set the monotonic clock in order to make sure we DO NOT jump in time
2388 * between the clock_gettime() call and the timedwait call. See bug #324
2389 * for a more details and how we noticed it.
2391 ret
= pthread_condattr_setclock(&consumer_data
->condattr
, CLOCK_MONOTONIC
);
2394 PERROR("pthread_condattr_setclock consumer data");
2398 ret
= pthread_cond_init(&consumer_data
->cond
, &consumer_data
->condattr
);
2401 PERROR("pthread_cond_init consumer data");
2405 ret
= pthread_create(&consumer_data
->thread
, default_pthread_attr(),
2406 thread_manage_consumer
, consumer_data
);
2409 PERROR("pthread_create consumer");
2414 /* We are about to wait on a pthread condition */
2415 pthread_mutex_lock(&consumer_data
->cond_mutex
);
2417 /* Get time for sem_timedwait absolute timeout */
2418 clock_ret
= lttng_clock_gettime(CLOCK_MONOTONIC
, &timeout
);
2420 * Set the timeout for the condition timed wait even if the clock gettime
2421 * call fails since we might loop on that call and we want to avoid to
2422 * increment the timeout too many times.
2424 timeout
.tv_sec
+= DEFAULT_SEM_WAIT_TIMEOUT
;
2427 * The following loop COULD be skipped in some conditions so this is why we
2428 * set ret to 0 in order to make sure at least one round of the loop is
2434 * Loop until the condition is reached or when a timeout is reached. Note
2435 * that the pthread_cond_timedwait(P) man page specifies that EINTR can NOT
2436 * be returned but the pthread_cond(3), from the glibc-doc, says that it is
2437 * possible. This loop does not take any chances and works with both of
2440 while (!consumer_data
->consumer_thread_is_ready
&& ret
!= ETIMEDOUT
) {
2441 if (clock_ret
< 0) {
2442 PERROR("clock_gettime spawn consumer");
2443 /* Infinite wait for the consumerd thread to be ready */
2444 ret
= pthread_cond_wait(&consumer_data
->cond
,
2445 &consumer_data
->cond_mutex
);
2447 ret
= pthread_cond_timedwait(&consumer_data
->cond
,
2448 &consumer_data
->cond_mutex
, &timeout
);
2452 /* Release the pthread condition */
2453 pthread_mutex_unlock(&consumer_data
->cond_mutex
);
2457 if (ret
== ETIMEDOUT
) {
2461 * Call has timed out so we kill the kconsumerd_thread and return
2464 ERR("Condition timed out. The consumer thread was never ready."
2466 pth_ret
= pthread_cancel(consumer_data
->thread
);
2468 PERROR("pthread_cancel consumer thread");
2471 PERROR("pthread_cond_wait failed consumer thread");
2473 /* Caller is expecting a negative value on failure. */
2478 pthread_mutex_lock(&consumer_data
->pid_mutex
);
2479 if (consumer_data
->pid
== 0) {
2480 ERR("Consumerd did not start");
2481 pthread_mutex_unlock(&consumer_data
->pid_mutex
);
2484 pthread_mutex_unlock(&consumer_data
->pid_mutex
);
2493 * Join consumer thread
2495 static int join_consumer_thread(struct consumer_data
*consumer_data
)
2499 /* Consumer pid must be a real one. */
2500 if (consumer_data
->pid
> 0) {
2502 ret
= kill(consumer_data
->pid
, SIGTERM
);
2504 PERROR("Error killing consumer daemon");
2507 return pthread_join(consumer_data
->thread
, &status
);
2514 * Fork and exec a consumer daemon (consumerd).
2516 * Return pid if successful else -1.
2518 static pid_t
spawn_consumerd(struct consumer_data
*consumer_data
)
2522 const char *consumer_to_use
;
2523 const char *verbosity
;
2526 DBG("Spawning consumerd");
2533 if (opt_verbose_consumer
) {
2534 verbosity
= "--verbose";
2535 } else if (lttng_opt_quiet
) {
2536 verbosity
= "--quiet";
2541 switch (consumer_data
->type
) {
2542 case LTTNG_CONSUMER_KERNEL
:
2544 * Find out which consumerd to execute. We will first try the
2545 * 64-bit path, then the sessiond's installation directory, and
2546 * fallback on the 32-bit one,
2548 DBG3("Looking for a kernel consumer at these locations:");
2549 DBG3(" 1) %s", consumerd64_bin
);
2550 DBG3(" 2) %s/%s", INSTALL_BIN_PATH
, CONSUMERD_FILE
);
2551 DBG3(" 3) %s", consumerd32_bin
);
2552 if (stat(consumerd64_bin
, &st
) == 0) {
2553 DBG3("Found location #1");
2554 consumer_to_use
= consumerd64_bin
;
2555 } else if (stat(INSTALL_BIN_PATH
"/" CONSUMERD_FILE
, &st
) == 0) {
2556 DBG3("Found location #2");
2557 consumer_to_use
= INSTALL_BIN_PATH
"/" CONSUMERD_FILE
;
2558 } else if (stat(consumerd32_bin
, &st
) == 0) {
2559 DBG3("Found location #3");
2560 consumer_to_use
= consumerd32_bin
;
2562 DBG("Could not find any valid consumerd executable");
2566 DBG("Using kernel consumer at: %s", consumer_to_use
);
2567 ret
= execl(consumer_to_use
,
2568 "lttng-consumerd", verbosity
, "-k",
2569 "--consumerd-cmd-sock", consumer_data
->cmd_unix_sock_path
,
2570 "--consumerd-err-sock", consumer_data
->err_unix_sock_path
,
2571 "--group", tracing_group_name
,
2574 case LTTNG_CONSUMER64_UST
:
2576 char *tmpnew
= NULL
;
2578 if (consumerd64_libdir
[0] != '\0') {
2582 tmp
= lttng_secure_getenv("LD_LIBRARY_PATH");
2586 tmplen
= strlen("LD_LIBRARY_PATH=")
2587 + strlen(consumerd64_libdir
) + 1 /* : */ + strlen(tmp
);
2588 tmpnew
= zmalloc(tmplen
+ 1 /* \0 */);
2593 strcpy(tmpnew
, "LD_LIBRARY_PATH=");
2594 strcat(tmpnew
, consumerd64_libdir
);
2595 if (tmp
[0] != '\0') {
2596 strcat(tmpnew
, ":");
2597 strcat(tmpnew
, tmp
);
2599 ret
= putenv(tmpnew
);
2606 DBG("Using 64-bit UST consumer at: %s", consumerd64_bin
);
2607 ret
= execl(consumerd64_bin
, "lttng-consumerd", verbosity
, "-u",
2608 "--consumerd-cmd-sock", consumer_data
->cmd_unix_sock_path
,
2609 "--consumerd-err-sock", consumer_data
->err_unix_sock_path
,
2610 "--group", tracing_group_name
,
2612 if (consumerd64_libdir
[0] != '\0') {
2617 case LTTNG_CONSUMER32_UST
:
2619 char *tmpnew
= NULL
;
2621 if (consumerd32_libdir
[0] != '\0') {
2625 tmp
= lttng_secure_getenv("LD_LIBRARY_PATH");
2629 tmplen
= strlen("LD_LIBRARY_PATH=")
2630 + strlen(consumerd32_libdir
) + 1 /* : */ + strlen(tmp
);
2631 tmpnew
= zmalloc(tmplen
+ 1 /* \0 */);
2636 strcpy(tmpnew
, "LD_LIBRARY_PATH=");
2637 strcat(tmpnew
, consumerd32_libdir
);
2638 if (tmp
[0] != '\0') {
2639 strcat(tmpnew
, ":");
2640 strcat(tmpnew
, tmp
);
2642 ret
= putenv(tmpnew
);
2649 DBG("Using 32-bit UST consumer at: %s", consumerd32_bin
);
2650 ret
= execl(consumerd32_bin
, "lttng-consumerd", verbosity
, "-u",
2651 "--consumerd-cmd-sock", consumer_data
->cmd_unix_sock_path
,
2652 "--consumerd-err-sock", consumer_data
->err_unix_sock_path
,
2653 "--group", tracing_group_name
,
2655 if (consumerd32_libdir
[0] != '\0') {
2661 ERR("unknown consumer type");
2665 PERROR("Consumer execl()");
2667 /* Reaching this point, we got a failure on our execl(). */
2669 } else if (pid
> 0) {
2672 PERROR("start consumer fork");
2680 * Spawn the consumerd daemon and session daemon thread.
2682 static int start_consumerd(struct consumer_data
*consumer_data
)
2687 * Set the listen() state on the socket since there is a possible race
2688 * between the exec() of the consumer daemon and this call if place in the
2689 * consumer thread. See bug #366 for more details.
2691 ret
= lttcomm_listen_unix_sock(consumer_data
->err_sock
);
2696 pthread_mutex_lock(&consumer_data
->pid_mutex
);
2697 if (consumer_data
->pid
!= 0) {
2698 pthread_mutex_unlock(&consumer_data
->pid_mutex
);
2702 ret
= spawn_consumerd(consumer_data
);
2704 ERR("Spawning consumerd failed");
2705 pthread_mutex_unlock(&consumer_data
->pid_mutex
);
2709 /* Setting up the consumer_data pid */
2710 consumer_data
->pid
= ret
;
2711 DBG2("Consumer pid %d", consumer_data
->pid
);
2712 pthread_mutex_unlock(&consumer_data
->pid_mutex
);
2714 DBG2("Spawning consumer control thread");
2715 ret
= spawn_consumer_thread(consumer_data
);
2717 ERR("Fatal error spawning consumer control thread");
2725 /* Cleanup already created sockets on error. */
2726 if (consumer_data
->err_sock
>= 0) {
2729 err
= close(consumer_data
->err_sock
);
2731 PERROR("close consumer data error socket");
2738 * Setup necessary data for kernel tracer action.
2740 static int init_kernel_tracer(void)
2744 /* Modprobe lttng kernel modules */
2745 ret
= modprobe_lttng_control();
2750 /* Open debugfs lttng */
2751 kernel_tracer_fd
= open(module_proc_lttng
, O_RDWR
);
2752 if (kernel_tracer_fd
< 0) {
2753 DBG("Failed to open %s", module_proc_lttng
);
2757 /* Validate kernel version */
2758 ret
= kernel_validate_version(kernel_tracer_fd
);
2763 ret
= modprobe_lttng_data();
2768 DBG("Kernel tracer fd %d", kernel_tracer_fd
);
2772 modprobe_remove_lttng_control();
2773 ret
= close(kernel_tracer_fd
);
2777 kernel_tracer_fd
= -1;
2778 return LTTNG_ERR_KERN_VERSION
;
2781 ret
= close(kernel_tracer_fd
);
2787 modprobe_remove_lttng_control();
2790 WARN("No kernel tracer available");
2791 kernel_tracer_fd
= -1;
2793 return LTTNG_ERR_NEED_ROOT_SESSIOND
;
2795 return LTTNG_ERR_KERN_NA
;
2801 * Copy consumer output from the tracing session to the domain session. The
2802 * function also applies the right modification on a per domain basis for the
2803 * trace files destination directory.
2805 * Should *NOT* be called with RCU read-side lock held.
2807 static int copy_session_consumer(int domain
, struct ltt_session
*session
)
2810 const char *dir_name
;
2811 struct consumer_output
*consumer
;
2814 assert(session
->consumer
);
2817 case LTTNG_DOMAIN_KERNEL
:
2818 DBG3("Copying tracing session consumer output in kernel session");
2820 * XXX: We should audit the session creation and what this function
2821 * does "extra" in order to avoid a destroy since this function is used
2822 * in the domain session creation (kernel and ust) only. Same for UST
2825 if (session
->kernel_session
->consumer
) {
2826 consumer_output_put(session
->kernel_session
->consumer
);
2828 session
->kernel_session
->consumer
=
2829 consumer_copy_output(session
->consumer
);
2830 /* Ease our life a bit for the next part */
2831 consumer
= session
->kernel_session
->consumer
;
2832 dir_name
= DEFAULT_KERNEL_TRACE_DIR
;
2834 case LTTNG_DOMAIN_JUL
:
2835 case LTTNG_DOMAIN_LOG4J
:
2836 case LTTNG_DOMAIN_PYTHON
:
2837 case LTTNG_DOMAIN_UST
:
2838 DBG3("Copying tracing session consumer output in UST session");
2839 if (session
->ust_session
->consumer
) {
2840 consumer_output_put(session
->ust_session
->consumer
);
2842 session
->ust_session
->consumer
=
2843 consumer_copy_output(session
->consumer
);
2844 /* Ease our life a bit for the next part */
2845 consumer
= session
->ust_session
->consumer
;
2846 dir_name
= DEFAULT_UST_TRACE_DIR
;
2849 ret
= LTTNG_ERR_UNKNOWN_DOMAIN
;
2853 /* Append correct directory to subdir */
2854 strncat(consumer
->subdir
, dir_name
,
2855 sizeof(consumer
->subdir
) - strlen(consumer
->subdir
) - 1);
2856 DBG3("Copy session consumer subdir %s", consumer
->subdir
);
2865 * Create an UST session and add it to the session ust list.
2867 * Should *NOT* be called with RCU read-side lock held.
2869 static int create_ust_session(struct ltt_session
*session
,
2870 struct lttng_domain
*domain
)
2873 struct ltt_ust_session
*lus
= NULL
;
2877 assert(session
->consumer
);
2879 switch (domain
->type
) {
2880 case LTTNG_DOMAIN_JUL
:
2881 case LTTNG_DOMAIN_LOG4J
:
2882 case LTTNG_DOMAIN_PYTHON
:
2883 case LTTNG_DOMAIN_UST
:
2886 ERR("Unknown UST domain on create session %d", domain
->type
);
2887 ret
= LTTNG_ERR_UNKNOWN_DOMAIN
;
2891 DBG("Creating UST session");
2893 lus
= trace_ust_create_session(session
->id
);
2895 ret
= LTTNG_ERR_UST_SESS_FAIL
;
2899 lus
->uid
= session
->uid
;
2900 lus
->gid
= session
->gid
;
2901 lus
->output_traces
= session
->output_traces
;
2902 lus
->snapshot_mode
= session
->snapshot_mode
;
2903 lus
->live_timer_interval
= session
->live_timer
;
2904 session
->ust_session
= lus
;
2905 if (session
->shm_path
[0]) {
2906 strncpy(lus
->root_shm_path
, session
->shm_path
,
2907 sizeof(lus
->root_shm_path
));
2908 lus
->root_shm_path
[sizeof(lus
->root_shm_path
) - 1] = '\0';
2909 strncpy(lus
->shm_path
, session
->shm_path
,
2910 sizeof(lus
->shm_path
));
2911 lus
->shm_path
[sizeof(lus
->shm_path
) - 1] = '\0';
2912 strncat(lus
->shm_path
, "/ust",
2913 sizeof(lus
->shm_path
) - strlen(lus
->shm_path
) - 1);
2915 /* Copy session output to the newly created UST session */
2916 ret
= copy_session_consumer(domain
->type
, session
);
2917 if (ret
!= LTTNG_OK
) {
2925 session
->ust_session
= NULL
;
2930 * Create a kernel tracer session then create the default channel.
2932 static int create_kernel_session(struct ltt_session
*session
)
2936 DBG("Creating kernel session");
2938 ret
= kernel_create_session(session
, kernel_tracer_fd
);
2940 ret
= LTTNG_ERR_KERN_SESS_FAIL
;
2944 /* Code flow safety */
2945 assert(session
->kernel_session
);
2947 /* Copy session output to the newly created Kernel session */
2948 ret
= copy_session_consumer(LTTNG_DOMAIN_KERNEL
, session
);
2949 if (ret
!= LTTNG_OK
) {
2953 /* Create directory(ies) on local filesystem. */
2954 if (session
->kernel_session
->consumer
->type
== CONSUMER_DST_LOCAL
&&
2955 strlen(session
->kernel_session
->consumer
->dst
.trace_path
) > 0) {
2956 ret
= run_as_mkdir_recursive(
2957 session
->kernel_session
->consumer
->dst
.trace_path
,
2958 S_IRWXU
| S_IRWXG
, session
->uid
, session
->gid
);
2960 if (errno
!= EEXIST
) {
2961 ERR("Trace directory creation error");
2967 session
->kernel_session
->uid
= session
->uid
;
2968 session
->kernel_session
->gid
= session
->gid
;
2969 session
->kernel_session
->output_traces
= session
->output_traces
;
2970 session
->kernel_session
->snapshot_mode
= session
->snapshot_mode
;
2975 trace_kernel_destroy_session(session
->kernel_session
);
2976 session
->kernel_session
= NULL
;
2981 * Count number of session permitted by uid/gid.
2983 static unsigned int lttng_sessions_count(uid_t uid
, gid_t gid
)
2986 struct ltt_session
*session
;
2988 DBG("Counting number of available session for UID %d GID %d",
2990 cds_list_for_each_entry(session
, &session_list_ptr
->head
, list
) {
2992 * Only list the sessions the user can control.
2994 if (!session_access_ok(session
, uid
, gid
)) {
3003 * Process the command requested by the lttng client within the command
3004 * context structure. This function make sure that the return structure (llm)
3005 * is set and ready for transmission before returning.
3007 * Return any error encountered or 0 for success.
3009 * "sock" is only used for special-case var. len data.
3011 * Should *NOT* be called with RCU read-side lock held.
3013 static int process_client_msg(struct command_ctx
*cmd_ctx
, int sock
,
3017 int need_tracing_session
= 1;
3020 DBG("Processing client command %d", cmd_ctx
->lsm
->cmd_type
);
3022 assert(!rcu_read_ongoing());
3026 switch (cmd_ctx
->lsm
->cmd_type
) {
3027 case LTTNG_CREATE_SESSION
:
3028 case LTTNG_CREATE_SESSION_SNAPSHOT
:
3029 case LTTNG_CREATE_SESSION_LIVE
:
3030 case LTTNG_DESTROY_SESSION
:
3031 case LTTNG_LIST_SESSIONS
:
3032 case LTTNG_LIST_DOMAINS
:
3033 case LTTNG_START_TRACE
:
3034 case LTTNG_STOP_TRACE
:
3035 case LTTNG_DATA_PENDING
:
3036 case LTTNG_SNAPSHOT_ADD_OUTPUT
:
3037 case LTTNG_SNAPSHOT_DEL_OUTPUT
:
3038 case LTTNG_SNAPSHOT_LIST_OUTPUT
:
3039 case LTTNG_SNAPSHOT_RECORD
:
3040 case LTTNG_SAVE_SESSION
:
3041 case LTTNG_SET_SESSION_SHM_PATH
:
3042 case LTTNG_REGENERATE_METADATA
:
3043 case LTTNG_REGENERATE_STATEDUMP
:
3050 if (opt_no_kernel
&& need_domain
3051 && cmd_ctx
->lsm
->domain
.type
== LTTNG_DOMAIN_KERNEL
) {
3053 ret
= LTTNG_ERR_NEED_ROOT_SESSIOND
;
3055 ret
= LTTNG_ERR_KERN_NA
;
3060 /* Deny register consumer if we already have a spawned consumer. */
3061 if (cmd_ctx
->lsm
->cmd_type
== LTTNG_REGISTER_CONSUMER
) {
3062 pthread_mutex_lock(&kconsumer_data
.pid_mutex
);
3063 if (kconsumer_data
.pid
> 0) {
3064 ret
= LTTNG_ERR_KERN_CONSUMER_FAIL
;
3065 pthread_mutex_unlock(&kconsumer_data
.pid_mutex
);
3068 pthread_mutex_unlock(&kconsumer_data
.pid_mutex
);
3072 * Check for command that don't needs to allocate a returned payload. We do
3073 * this here so we don't have to make the call for no payload at each
3076 switch(cmd_ctx
->lsm
->cmd_type
) {
3077 case LTTNG_LIST_SESSIONS
:
3078 case LTTNG_LIST_TRACEPOINTS
:
3079 case LTTNG_LIST_TRACEPOINT_FIELDS
:
3080 case LTTNG_LIST_DOMAINS
:
3081 case LTTNG_LIST_CHANNELS
:
3082 case LTTNG_LIST_EVENTS
:
3083 case LTTNG_LIST_SYSCALLS
:
3084 case LTTNG_LIST_TRACKER_PIDS
:
3085 case LTTNG_DATA_PENDING
:
3088 /* Setup lttng message with no payload */
3089 ret
= setup_lttng_msg_no_cmd_header(cmd_ctx
, NULL
, 0);
3091 /* This label does not try to unlock the session */
3092 goto init_setup_error
;
3096 /* Commands that DO NOT need a session. */
3097 switch (cmd_ctx
->lsm
->cmd_type
) {
3098 case LTTNG_CREATE_SESSION
:
3099 case LTTNG_CREATE_SESSION_SNAPSHOT
:
3100 case LTTNG_CREATE_SESSION_LIVE
:
3101 case LTTNG_LIST_SESSIONS
:
3102 case LTTNG_LIST_TRACEPOINTS
:
3103 case LTTNG_LIST_SYSCALLS
:
3104 case LTTNG_LIST_TRACEPOINT_FIELDS
:
3105 case LTTNG_SAVE_SESSION
:
3106 need_tracing_session
= 0;
3109 DBG("Getting session %s by name", cmd_ctx
->lsm
->session
.name
);
3111 * We keep the session list lock across _all_ commands
3112 * for now, because the per-session lock does not
3113 * handle teardown properly.
3115 session_lock_list();
3116 cmd_ctx
->session
= session_find_by_name(cmd_ctx
->lsm
->session
.name
);
3117 if (cmd_ctx
->session
== NULL
) {
3118 ret
= LTTNG_ERR_SESS_NOT_FOUND
;
3121 /* Acquire lock for the session */
3122 session_lock(cmd_ctx
->session
);
3128 * Commands that need a valid session but should NOT create one if none
3129 * exists. Instead of creating one and destroying it when the command is
3130 * handled, process that right before so we save some round trip in useless
3133 switch (cmd_ctx
->lsm
->cmd_type
) {
3134 case LTTNG_DISABLE_CHANNEL
:
3135 case LTTNG_DISABLE_EVENT
:
3136 switch (cmd_ctx
->lsm
->domain
.type
) {
3137 case LTTNG_DOMAIN_KERNEL
:
3138 if (!cmd_ctx
->session
->kernel_session
) {
3139 ret
= LTTNG_ERR_NO_CHANNEL
;
3143 case LTTNG_DOMAIN_JUL
:
3144 case LTTNG_DOMAIN_LOG4J
:
3145 case LTTNG_DOMAIN_PYTHON
:
3146 case LTTNG_DOMAIN_UST
:
3147 if (!cmd_ctx
->session
->ust_session
) {
3148 ret
= LTTNG_ERR_NO_CHANNEL
;
3153 ret
= LTTNG_ERR_UNKNOWN_DOMAIN
;
3165 * Check domain type for specific "pre-action".
3167 switch (cmd_ctx
->lsm
->domain
.type
) {
3168 case LTTNG_DOMAIN_KERNEL
:
3170 ret
= LTTNG_ERR_NEED_ROOT_SESSIOND
;
3174 /* Kernel tracer check */
3175 if (kernel_tracer_fd
== -1) {
3176 /* Basically, load kernel tracer modules */
3177 ret
= init_kernel_tracer();
3183 /* Consumer is in an ERROR state. Report back to client */
3184 if (uatomic_read(&kernel_consumerd_state
) == CONSUMER_ERROR
) {
3185 ret
= LTTNG_ERR_NO_KERNCONSUMERD
;
3189 /* Need a session for kernel command */
3190 if (need_tracing_session
) {
3191 if (cmd_ctx
->session
->kernel_session
== NULL
) {
3192 ret
= create_kernel_session(cmd_ctx
->session
);
3194 ret
= LTTNG_ERR_KERN_SESS_FAIL
;
3199 /* Start the kernel consumer daemon */
3200 pthread_mutex_lock(&kconsumer_data
.pid_mutex
);
3201 if (kconsumer_data
.pid
== 0 &&
3202 cmd_ctx
->lsm
->cmd_type
!= LTTNG_REGISTER_CONSUMER
) {
3203 pthread_mutex_unlock(&kconsumer_data
.pid_mutex
);
3204 ret
= start_consumerd(&kconsumer_data
);
3206 ret
= LTTNG_ERR_KERN_CONSUMER_FAIL
;
3209 uatomic_set(&kernel_consumerd_state
, CONSUMER_STARTED
);
3211 pthread_mutex_unlock(&kconsumer_data
.pid_mutex
);
3215 * The consumer was just spawned so we need to add the socket to
3216 * the consumer output of the session if exist.
3218 ret
= consumer_create_socket(&kconsumer_data
,
3219 cmd_ctx
->session
->kernel_session
->consumer
);
3226 case LTTNG_DOMAIN_JUL
:
3227 case LTTNG_DOMAIN_LOG4J
:
3228 case LTTNG_DOMAIN_PYTHON
:
3229 case LTTNG_DOMAIN_UST
:
3231 if (!ust_app_supported()) {
3232 ret
= LTTNG_ERR_NO_UST
;
3235 /* Consumer is in an ERROR state. Report back to client */
3236 if (uatomic_read(&ust_consumerd_state
) == CONSUMER_ERROR
) {
3237 ret
= LTTNG_ERR_NO_USTCONSUMERD
;
3241 if (need_tracing_session
) {
3242 /* Create UST session if none exist. */
3243 if (cmd_ctx
->session
->ust_session
== NULL
) {
3244 ret
= create_ust_session(cmd_ctx
->session
,
3245 &cmd_ctx
->lsm
->domain
);
3246 if (ret
!= LTTNG_OK
) {
3251 /* Start the UST consumer daemons */
3253 pthread_mutex_lock(&ustconsumer64_data
.pid_mutex
);
3254 if (consumerd64_bin
[0] != '\0' &&
3255 ustconsumer64_data
.pid
== 0 &&
3256 cmd_ctx
->lsm
->cmd_type
!= LTTNG_REGISTER_CONSUMER
) {
3257 pthread_mutex_unlock(&ustconsumer64_data
.pid_mutex
);
3258 ret
= start_consumerd(&ustconsumer64_data
);
3260 ret
= LTTNG_ERR_UST_CONSUMER64_FAIL
;
3261 uatomic_set(&ust_consumerd64_fd
, -EINVAL
);
3265 uatomic_set(&ust_consumerd64_fd
, ustconsumer64_data
.cmd_sock
);
3266 uatomic_set(&ust_consumerd_state
, CONSUMER_STARTED
);
3268 pthread_mutex_unlock(&ustconsumer64_data
.pid_mutex
);
3272 * Setup socket for consumer 64 bit. No need for atomic access
3273 * since it was set above and can ONLY be set in this thread.
3275 ret
= consumer_create_socket(&ustconsumer64_data
,
3276 cmd_ctx
->session
->ust_session
->consumer
);
3282 pthread_mutex_lock(&ustconsumer32_data
.pid_mutex
);
3283 if (consumerd32_bin
[0] != '\0' &&
3284 ustconsumer32_data
.pid
== 0 &&
3285 cmd_ctx
->lsm
->cmd_type
!= LTTNG_REGISTER_CONSUMER
) {
3286 pthread_mutex_unlock(&ustconsumer32_data
.pid_mutex
);
3287 ret
= start_consumerd(&ustconsumer32_data
);
3289 ret
= LTTNG_ERR_UST_CONSUMER32_FAIL
;
3290 uatomic_set(&ust_consumerd32_fd
, -EINVAL
);
3294 uatomic_set(&ust_consumerd32_fd
, ustconsumer32_data
.cmd_sock
);
3295 uatomic_set(&ust_consumerd_state
, CONSUMER_STARTED
);
3297 pthread_mutex_unlock(&ustconsumer32_data
.pid_mutex
);
3301 * Setup socket for consumer 64 bit. No need for atomic access
3302 * since it was set above and can ONLY be set in this thread.
3304 ret
= consumer_create_socket(&ustconsumer32_data
,
3305 cmd_ctx
->session
->ust_session
->consumer
);
3317 /* Validate consumer daemon state when start/stop trace command */
3318 if (cmd_ctx
->lsm
->cmd_type
== LTTNG_START_TRACE
||
3319 cmd_ctx
->lsm
->cmd_type
== LTTNG_STOP_TRACE
) {
3320 switch (cmd_ctx
->lsm
->domain
.type
) {
3321 case LTTNG_DOMAIN_NONE
:
3323 case LTTNG_DOMAIN_JUL
:
3324 case LTTNG_DOMAIN_LOG4J
:
3325 case LTTNG_DOMAIN_PYTHON
:
3326 case LTTNG_DOMAIN_UST
:
3327 if (uatomic_read(&ust_consumerd_state
) != CONSUMER_STARTED
) {
3328 ret
= LTTNG_ERR_NO_USTCONSUMERD
;
3332 case LTTNG_DOMAIN_KERNEL
:
3333 if (uatomic_read(&kernel_consumerd_state
) != CONSUMER_STARTED
) {
3334 ret
= LTTNG_ERR_NO_KERNCONSUMERD
;
3339 ret
= LTTNG_ERR_UNKNOWN_DOMAIN
;
3345 * Check that the UID or GID match that of the tracing session.
3346 * The root user can interact with all sessions.
3348 if (need_tracing_session
) {
3349 if (!session_access_ok(cmd_ctx
->session
,
3350 LTTNG_SOCK_GET_UID_CRED(&cmd_ctx
->creds
),
3351 LTTNG_SOCK_GET_GID_CRED(&cmd_ctx
->creds
))) {
3352 ret
= LTTNG_ERR_EPERM
;
3358 * Send relayd information to consumer as soon as we have a domain and a
3361 if (cmd_ctx
->session
&& need_domain
) {
3363 * Setup relayd if not done yet. If the relayd information was already
3364 * sent to the consumer, this call will gracefully return.
3366 ret
= cmd_setup_relayd(cmd_ctx
->session
);
3367 if (ret
!= LTTNG_OK
) {
3372 /* Process by command type */
3373 switch (cmd_ctx
->lsm
->cmd_type
) {
3374 case LTTNG_ADD_CONTEXT
:
3377 * An LTTNG_ADD_CONTEXT command might have a supplementary
3378 * payload if the context being added is an application context.
3380 if (cmd_ctx
->lsm
->u
.context
.ctx
.ctx
==
3381 LTTNG_EVENT_CONTEXT_APP_CONTEXT
) {
3382 char *provider_name
= NULL
, *context_name
= NULL
;
3383 size_t provider_name_len
=
3384 cmd_ctx
->lsm
->u
.context
.provider_name_len
;
3385 size_t context_name_len
=
3386 cmd_ctx
->lsm
->u
.context
.context_name_len
;
3388 if (provider_name_len
== 0 || context_name_len
== 0) {
3390 * Application provider and context names MUST
3393 ret
= -LTTNG_ERR_INVALID
;
3397 provider_name
= zmalloc(provider_name_len
+ 1);
3398 if (!provider_name
) {
3399 ret
= -LTTNG_ERR_NOMEM
;
3402 cmd_ctx
->lsm
->u
.context
.ctx
.u
.app_ctx
.provider_name
=
3405 context_name
= zmalloc(context_name_len
+ 1);
3406 if (!context_name
) {
3407 ret
= -LTTNG_ERR_NOMEM
;
3408 goto error_add_context
;
3410 cmd_ctx
->lsm
->u
.context
.ctx
.u
.app_ctx
.ctx_name
=
3413 ret
= lttcomm_recv_unix_sock(sock
, provider_name
,
3416 goto error_add_context
;
3419 ret
= lttcomm_recv_unix_sock(sock
, context_name
,
3422 goto error_add_context
;
3427 * cmd_add_context assumes ownership of the provider and context
3430 ret
= cmd_add_context(cmd_ctx
->session
,
3431 cmd_ctx
->lsm
->domain
.type
,
3432 cmd_ctx
->lsm
->u
.context
.channel_name
,
3433 &cmd_ctx
->lsm
->u
.context
.ctx
,
3434 kernel_poll_pipe
[1]);
3436 cmd_ctx
->lsm
->u
.context
.ctx
.u
.app_ctx
.provider_name
= NULL
;
3437 cmd_ctx
->lsm
->u
.context
.ctx
.u
.app_ctx
.ctx_name
= NULL
;
3439 free(cmd_ctx
->lsm
->u
.context
.ctx
.u
.app_ctx
.provider_name
);
3440 free(cmd_ctx
->lsm
->u
.context
.ctx
.u
.app_ctx
.ctx_name
);
3446 case LTTNG_DISABLE_CHANNEL
:
3448 ret
= cmd_disable_channel(cmd_ctx
->session
, cmd_ctx
->lsm
->domain
.type
,
3449 cmd_ctx
->lsm
->u
.disable
.channel_name
);
3452 case LTTNG_DISABLE_EVENT
:
3456 * FIXME: handle filter; for now we just receive the filter's
3457 * bytecode along with the filter expression which are sent by
3458 * liblttng-ctl and discard them.
3460 * This fixes an issue where the client may block while sending
3461 * the filter payload and encounter an error because the session
3462 * daemon closes the socket without ever handling this data.
3464 size_t count
= cmd_ctx
->lsm
->u
.disable
.expression_len
+
3465 cmd_ctx
->lsm
->u
.disable
.bytecode_len
;
3468 char data
[LTTNG_FILTER_MAX_LEN
];
3470 DBG("Discarding disable event command payload of size %zu", count
);
3472 ret
= lttcomm_recv_unix_sock(sock
, data
,
3473 count
> sizeof(data
) ? sizeof(data
) : count
);
3478 count
-= (size_t) ret
;
3481 /* FIXME: passing packed structure to non-packed pointer */
3482 ret
= cmd_disable_event(cmd_ctx
->session
, cmd_ctx
->lsm
->domain
.type
,
3483 cmd_ctx
->lsm
->u
.disable
.channel_name
,
3484 &cmd_ctx
->lsm
->u
.disable
.event
);
3487 case LTTNG_ENABLE_CHANNEL
:
3489 ret
= cmd_enable_channel(cmd_ctx
->session
, &cmd_ctx
->lsm
->domain
,
3490 &cmd_ctx
->lsm
->u
.channel
.chan
, kernel_poll_pipe
[1]);
3493 case LTTNG_TRACK_PID
:
3495 ret
= cmd_track_pid(cmd_ctx
->session
,
3496 cmd_ctx
->lsm
->domain
.type
,
3497 cmd_ctx
->lsm
->u
.pid_tracker
.pid
);
3500 case LTTNG_UNTRACK_PID
:
3502 ret
= cmd_untrack_pid(cmd_ctx
->session
,
3503 cmd_ctx
->lsm
->domain
.type
,
3504 cmd_ctx
->lsm
->u
.pid_tracker
.pid
);
3507 case LTTNG_ENABLE_EVENT
:
3509 struct lttng_event_exclusion
*exclusion
= NULL
;
3510 struct lttng_filter_bytecode
*bytecode
= NULL
;
3511 char *filter_expression
= NULL
;
3513 /* Handle exclusion events and receive it from the client. */
3514 if (cmd_ctx
->lsm
->u
.enable
.exclusion_count
> 0) {
3515 size_t count
= cmd_ctx
->lsm
->u
.enable
.exclusion_count
;
3517 exclusion
= zmalloc(sizeof(struct lttng_event_exclusion
) +
3518 (count
* LTTNG_SYMBOL_NAME_LEN
));
3520 ret
= LTTNG_ERR_EXCLUSION_NOMEM
;
3524 DBG("Receiving var len exclusion event list from client ...");
3525 exclusion
->count
= count
;
3526 ret
= lttcomm_recv_unix_sock(sock
, exclusion
->names
,
3527 count
* LTTNG_SYMBOL_NAME_LEN
);
3529 DBG("Nothing recv() from client var len data... continuing");
3532 ret
= LTTNG_ERR_EXCLUSION_INVAL
;
3537 /* Get filter expression from client. */
3538 if (cmd_ctx
->lsm
->u
.enable
.expression_len
> 0) {
3539 size_t expression_len
=
3540 cmd_ctx
->lsm
->u
.enable
.expression_len
;
3542 if (expression_len
> LTTNG_FILTER_MAX_LEN
) {
3543 ret
= LTTNG_ERR_FILTER_INVAL
;
3548 filter_expression
= zmalloc(expression_len
);
3549 if (!filter_expression
) {
3551 ret
= LTTNG_ERR_FILTER_NOMEM
;
3555 /* Receive var. len. data */
3556 DBG("Receiving var len filter's expression from client ...");
3557 ret
= lttcomm_recv_unix_sock(sock
, filter_expression
,
3560 DBG("Nothing recv() from client car len data... continuing");
3562 free(filter_expression
);
3564 ret
= LTTNG_ERR_FILTER_INVAL
;
3569 /* Handle filter and get bytecode from client. */
3570 if (cmd_ctx
->lsm
->u
.enable
.bytecode_len
> 0) {
3571 size_t bytecode_len
= cmd_ctx
->lsm
->u
.enable
.bytecode_len
;
3573 if (bytecode_len
> LTTNG_FILTER_MAX_LEN
) {
3574 ret
= LTTNG_ERR_FILTER_INVAL
;
3575 free(filter_expression
);
3580 bytecode
= zmalloc(bytecode_len
);
3582 free(filter_expression
);
3584 ret
= LTTNG_ERR_FILTER_NOMEM
;
3588 /* Receive var. len. data */
3589 DBG("Receiving var len filter's bytecode from client ...");
3590 ret
= lttcomm_recv_unix_sock(sock
, bytecode
, bytecode_len
);
3592 DBG("Nothing recv() from client car len data... continuing");
3594 free(filter_expression
);
3597 ret
= LTTNG_ERR_FILTER_INVAL
;
3601 if ((bytecode
->len
+ sizeof(*bytecode
)) != bytecode_len
) {
3602 free(filter_expression
);
3605 ret
= LTTNG_ERR_FILTER_INVAL
;
3610 ret
= cmd_enable_event(cmd_ctx
->session
, &cmd_ctx
->lsm
->domain
,
3611 cmd_ctx
->lsm
->u
.enable
.channel_name
,
3612 &cmd_ctx
->lsm
->u
.enable
.event
,
3613 filter_expression
, bytecode
, exclusion
,
3614 kernel_poll_pipe
[1]);
3617 case LTTNG_LIST_TRACEPOINTS
:
3619 struct lttng_event
*events
;
3622 session_lock_list();
3623 nb_events
= cmd_list_tracepoints(cmd_ctx
->lsm
->domain
.type
, &events
);
3624 session_unlock_list();
3625 if (nb_events
< 0) {
3626 /* Return value is a negative lttng_error_code. */
3632 * Setup lttng message with payload size set to the event list size in
3633 * bytes and then copy list into the llm payload.
3635 ret
= setup_lttng_msg_no_cmd_header(cmd_ctx
, events
,
3636 sizeof(struct lttng_event
) * nb_events
);
3646 case LTTNG_LIST_TRACEPOINT_FIELDS
:
3648 struct lttng_event_field
*fields
;
3651 session_lock_list();
3652 nb_fields
= cmd_list_tracepoint_fields(cmd_ctx
->lsm
->domain
.type
,
3654 session_unlock_list();
3655 if (nb_fields
< 0) {
3656 /* Return value is a negative lttng_error_code. */
3662 * Setup lttng message with payload size set to the event list size in
3663 * bytes and then copy list into the llm payload.
3665 ret
= setup_lttng_msg_no_cmd_header(cmd_ctx
, fields
,
3666 sizeof(struct lttng_event_field
) * nb_fields
);
3676 case LTTNG_LIST_SYSCALLS
:
3678 struct lttng_event
*events
;
3681 nb_events
= cmd_list_syscalls(&events
);
3682 if (nb_events
< 0) {
3683 /* Return value is a negative lttng_error_code. */
3689 * Setup lttng message with payload size set to the event list size in
3690 * bytes and then copy list into the llm payload.
3692 ret
= setup_lttng_msg_no_cmd_header(cmd_ctx
, events
,
3693 sizeof(struct lttng_event
) * nb_events
);
3703 case LTTNG_LIST_TRACKER_PIDS
:
3705 int32_t *pids
= NULL
;
3708 nr_pids
= cmd_list_tracker_pids(cmd_ctx
->session
,
3709 cmd_ctx
->lsm
->domain
.type
, &pids
);
3711 /* Return value is a negative lttng_error_code. */
3717 * Setup lttng message with payload size set to the event list size in
3718 * bytes and then copy list into the llm payload.
3720 ret
= setup_lttng_msg_no_cmd_header(cmd_ctx
, pids
,
3721 sizeof(int32_t) * nr_pids
);
3731 case LTTNG_SET_CONSUMER_URI
:
3734 struct lttng_uri
*uris
;
3736 nb_uri
= cmd_ctx
->lsm
->u
.uri
.size
;
3737 len
= nb_uri
* sizeof(struct lttng_uri
);
3740 ret
= LTTNG_ERR_INVALID
;
3744 uris
= zmalloc(len
);
3746 ret
= LTTNG_ERR_FATAL
;
3750 /* Receive variable len data */
3751 DBG("Receiving %zu URI(s) from client ...", nb_uri
);
3752 ret
= lttcomm_recv_unix_sock(sock
, uris
, len
);
3754 DBG("No URIs received from client... continuing");
3756 ret
= LTTNG_ERR_SESSION_FAIL
;
3761 ret
= cmd_set_consumer_uri(cmd_ctx
->session
, nb_uri
, uris
);
3763 if (ret
!= LTTNG_OK
) {
3770 case LTTNG_START_TRACE
:
3772 ret
= cmd_start_trace(cmd_ctx
->session
);
3775 case LTTNG_STOP_TRACE
:
3777 ret
= cmd_stop_trace(cmd_ctx
->session
);
3780 case LTTNG_CREATE_SESSION
:
3783 struct lttng_uri
*uris
= NULL
;
3785 nb_uri
= cmd_ctx
->lsm
->u
.uri
.size
;
3786 len
= nb_uri
* sizeof(struct lttng_uri
);
3789 uris
= zmalloc(len
);
3791 ret
= LTTNG_ERR_FATAL
;
3795 /* Receive variable len data */
3796 DBG("Waiting for %zu URIs from client ...", nb_uri
);
3797 ret
= lttcomm_recv_unix_sock(sock
, uris
, len
);
3799 DBG("No URIs received from client... continuing");
3801 ret
= LTTNG_ERR_SESSION_FAIL
;
3806 if (nb_uri
== 1 && uris
[0].dtype
!= LTTNG_DST_PATH
) {
3807 DBG("Creating session with ONE network URI is a bad call");
3808 ret
= LTTNG_ERR_SESSION_FAIL
;
3814 ret
= cmd_create_session_uri(cmd_ctx
->lsm
->session
.name
, uris
, nb_uri
,
3815 &cmd_ctx
->creds
, 0);
3821 case LTTNG_DESTROY_SESSION
:
3823 ret
= cmd_destroy_session(cmd_ctx
->session
, kernel_poll_pipe
[1]);
3825 /* Set session to NULL so we do not unlock it after free. */
3826 cmd_ctx
->session
= NULL
;
3829 case LTTNG_LIST_DOMAINS
:
3832 struct lttng_domain
*domains
= NULL
;
3834 nb_dom
= cmd_list_domains(cmd_ctx
->session
, &domains
);
3836 /* Return value is a negative lttng_error_code. */
3841 ret
= setup_lttng_msg_no_cmd_header(cmd_ctx
, domains
,
3842 nb_dom
* sizeof(struct lttng_domain
));
3852 case LTTNG_LIST_CHANNELS
:
3854 ssize_t payload_size
;
3855 struct lttng_channel
*channels
= NULL
;
3857 payload_size
= cmd_list_channels(cmd_ctx
->lsm
->domain
.type
,
3858 cmd_ctx
->session
, &channels
);
3859 if (payload_size
< 0) {
3860 /* Return value is a negative lttng_error_code. */
3861 ret
= -payload_size
;
3865 ret
= setup_lttng_msg_no_cmd_header(cmd_ctx
, channels
,
3876 case LTTNG_LIST_EVENTS
:
3879 struct lttng_event
*events
= NULL
;
3880 struct lttcomm_event_command_header cmd_header
;
3883 memset(&cmd_header
, 0, sizeof(cmd_header
));
3884 /* Extended infos are included at the end of events */
3885 nb_event
= cmd_list_events(cmd_ctx
->lsm
->domain
.type
,
3886 cmd_ctx
->session
, cmd_ctx
->lsm
->u
.list
.channel_name
,
3887 &events
, &total_size
);
3890 /* Return value is a negative lttng_error_code. */
3895 cmd_header
.nb_events
= nb_event
;
3896 ret
= setup_lttng_msg(cmd_ctx
, events
, total_size
,
3897 &cmd_header
, sizeof(cmd_header
));
3907 case LTTNG_LIST_SESSIONS
:
3909 unsigned int nr_sessions
;
3910 void *sessions_payload
;
3913 session_lock_list();
3914 nr_sessions
= lttng_sessions_count(
3915 LTTNG_SOCK_GET_UID_CRED(&cmd_ctx
->creds
),
3916 LTTNG_SOCK_GET_GID_CRED(&cmd_ctx
->creds
));
3917 payload_len
= sizeof(struct lttng_session
) * nr_sessions
;
3918 sessions_payload
= zmalloc(payload_len
);
3920 if (!sessions_payload
) {
3921 session_unlock_list();
3926 cmd_list_lttng_sessions(sessions_payload
,
3927 LTTNG_SOCK_GET_UID_CRED(&cmd_ctx
->creds
),
3928 LTTNG_SOCK_GET_GID_CRED(&cmd_ctx
->creds
));
3929 session_unlock_list();
3931 ret
= setup_lttng_msg_no_cmd_header(cmd_ctx
, sessions_payload
,
3933 free(sessions_payload
);
3942 case LTTNG_REGISTER_CONSUMER
:
3944 struct consumer_data
*cdata
;
3946 switch (cmd_ctx
->lsm
->domain
.type
) {
3947 case LTTNG_DOMAIN_KERNEL
:
3948 cdata
= &kconsumer_data
;
3951 ret
= LTTNG_ERR_UND
;
3955 ret
= cmd_register_consumer(cmd_ctx
->session
, cmd_ctx
->lsm
->domain
.type
,
3956 cmd_ctx
->lsm
->u
.reg
.path
, cdata
);
3959 case LTTNG_DATA_PENDING
:
3962 uint8_t pending_ret_byte
;
3964 pending_ret
= cmd_data_pending(cmd_ctx
->session
);
3969 * This function may returns 0 or 1 to indicate whether or not
3970 * there is data pending. In case of error, it should return an
3971 * LTTNG_ERR code. However, some code paths may still return
3972 * a nondescript error code, which we handle by returning an
3975 if (pending_ret
== 0 || pending_ret
== 1) {
3977 * ret will be set to LTTNG_OK at the end of
3980 } else if (pending_ret
< 0) {
3981 ret
= LTTNG_ERR_UNK
;
3988 pending_ret_byte
= (uint8_t) pending_ret
;
3990 /* 1 byte to return whether or not data is pending */
3991 ret
= setup_lttng_msg_no_cmd_header(cmd_ctx
,
3992 &pending_ret_byte
, 1);
4001 case LTTNG_SNAPSHOT_ADD_OUTPUT
:
4003 struct lttcomm_lttng_output_id reply
;
4005 ret
= cmd_snapshot_add_output(cmd_ctx
->session
,
4006 &cmd_ctx
->lsm
->u
.snapshot_output
.output
, &reply
.id
);
4007 if (ret
!= LTTNG_OK
) {
4011 ret
= setup_lttng_msg_no_cmd_header(cmd_ctx
, &reply
,
4017 /* Copy output list into message payload */
4021 case LTTNG_SNAPSHOT_DEL_OUTPUT
:
4023 ret
= cmd_snapshot_del_output(cmd_ctx
->session
,
4024 &cmd_ctx
->lsm
->u
.snapshot_output
.output
);
4027 case LTTNG_SNAPSHOT_LIST_OUTPUT
:
4030 struct lttng_snapshot_output
*outputs
= NULL
;
4032 nb_output
= cmd_snapshot_list_outputs(cmd_ctx
->session
, &outputs
);
4033 if (nb_output
< 0) {
4038 assert((nb_output
> 0 && outputs
) || nb_output
== 0);
4039 ret
= setup_lttng_msg_no_cmd_header(cmd_ctx
, outputs
,
4040 nb_output
* sizeof(struct lttng_snapshot_output
));
4050 case LTTNG_SNAPSHOT_RECORD
:
4052 ret
= cmd_snapshot_record(cmd_ctx
->session
,
4053 &cmd_ctx
->lsm
->u
.snapshot_record
.output
,
4054 cmd_ctx
->lsm
->u
.snapshot_record
.wait
);
4057 case LTTNG_CREATE_SESSION_SNAPSHOT
:
4060 struct lttng_uri
*uris
= NULL
;
4062 nb_uri
= cmd_ctx
->lsm
->u
.uri
.size
;
4063 len
= nb_uri
* sizeof(struct lttng_uri
);
4066 uris
= zmalloc(len
);
4068 ret
= LTTNG_ERR_FATAL
;
4072 /* Receive variable len data */
4073 DBG("Waiting for %zu URIs from client ...", nb_uri
);
4074 ret
= lttcomm_recv_unix_sock(sock
, uris
, len
);
4076 DBG("No URIs received from client... continuing");
4078 ret
= LTTNG_ERR_SESSION_FAIL
;
4083 if (nb_uri
== 1 && uris
[0].dtype
!= LTTNG_DST_PATH
) {
4084 DBG("Creating session with ONE network URI is a bad call");
4085 ret
= LTTNG_ERR_SESSION_FAIL
;
4091 ret
= cmd_create_session_snapshot(cmd_ctx
->lsm
->session
.name
, uris
,
4092 nb_uri
, &cmd_ctx
->creds
);
4096 case LTTNG_CREATE_SESSION_LIVE
:
4099 struct lttng_uri
*uris
= NULL
;
4101 nb_uri
= cmd_ctx
->lsm
->u
.uri
.size
;
4102 len
= nb_uri
* sizeof(struct lttng_uri
);
4105 uris
= zmalloc(len
);
4107 ret
= LTTNG_ERR_FATAL
;
4111 /* Receive variable len data */
4112 DBG("Waiting for %zu URIs from client ...", nb_uri
);
4113 ret
= lttcomm_recv_unix_sock(sock
, uris
, len
);
4115 DBG("No URIs received from client... continuing");
4117 ret
= LTTNG_ERR_SESSION_FAIL
;
4122 if (nb_uri
== 1 && uris
[0].dtype
!= LTTNG_DST_PATH
) {
4123 DBG("Creating session with ONE network URI is a bad call");
4124 ret
= LTTNG_ERR_SESSION_FAIL
;
4130 ret
= cmd_create_session_uri(cmd_ctx
->lsm
->session
.name
, uris
,
4131 nb_uri
, &cmd_ctx
->creds
, cmd_ctx
->lsm
->u
.session_live
.timer_interval
);
4135 case LTTNG_SAVE_SESSION
:
4137 ret
= cmd_save_sessions(&cmd_ctx
->lsm
->u
.save_session
.attr
,
4141 case LTTNG_SET_SESSION_SHM_PATH
:
4143 ret
= cmd_set_session_shm_path(cmd_ctx
->session
,
4144 cmd_ctx
->lsm
->u
.set_shm_path
.shm_path
);
4147 case LTTNG_REGENERATE_METADATA
:
4149 ret
= cmd_regenerate_metadata(cmd_ctx
->session
);
4152 case LTTNG_REGENERATE_STATEDUMP
:
4154 ret
= cmd_regenerate_statedump(cmd_ctx
->session
);
4158 ret
= LTTNG_ERR_UND
;
4163 if (cmd_ctx
->llm
== NULL
) {
4164 DBG("Missing llm structure. Allocating one.");
4165 if (setup_lttng_msg_no_cmd_header(cmd_ctx
, NULL
, 0) < 0) {
4169 /* Set return code */
4170 cmd_ctx
->llm
->ret_code
= ret
;
4172 if (cmd_ctx
->session
) {
4173 session_unlock(cmd_ctx
->session
);
4175 if (need_tracing_session
) {
4176 session_unlock_list();
4179 assert(!rcu_read_ongoing());
4184 * Thread managing health check socket.
4186 static void *thread_manage_health(void *data
)
4188 int sock
= -1, new_sock
= -1, ret
, i
, pollfd
, err
= -1;
4189 uint32_t revents
, nb_fd
;
4190 struct lttng_poll_event events
;
4191 struct health_comm_msg msg
;
4192 struct health_comm_reply reply
;
4194 DBG("[thread] Manage health check started");
4196 rcu_register_thread();
4198 /* We might hit an error path before this is created. */
4199 lttng_poll_init(&events
);
4201 /* Create unix socket */
4202 sock
= lttcomm_create_unix_sock(health_unix_sock_path
);
4204 ERR("Unable to create health check Unix socket");
4209 /* lttng health client socket path permissions */
4210 ret
= chown(health_unix_sock_path
, 0,
4211 utils_get_group_id(tracing_group_name
));
4213 ERR("Unable to set group on %s", health_unix_sock_path
);
4218 ret
= chmod(health_unix_sock_path
,
4219 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
4221 ERR("Unable to set permissions on %s", health_unix_sock_path
);
4228 * Set the CLOEXEC flag. Return code is useless because either way, the
4231 (void) utils_set_fd_cloexec(sock
);
4233 ret
= lttcomm_listen_unix_sock(sock
);
4239 * Pass 2 as size here for the thread quit pipe and client_sock. Nothing
4240 * more will be added to this poll set.
4242 ret
= sessiond_set_thread_pollset(&events
, 2);
4247 /* Add the application registration socket */
4248 ret
= lttng_poll_add(&events
, sock
, LPOLLIN
| LPOLLPRI
);
4253 sessiond_notify_ready();
4256 DBG("Health check ready");
4258 /* Inifinite blocking call, waiting for transmission */
4260 ret
= lttng_poll_wait(&events
, -1);
4263 * Restart interrupted system call.
4265 if (errno
== EINTR
) {
4273 for (i
= 0; i
< nb_fd
; i
++) {
4274 /* Fetch once the poll data */
4275 revents
= LTTNG_POLL_GETEV(&events
, i
);
4276 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4279 /* No activity for this FD (poll implementation). */
4283 /* Thread quit pipe has been closed. Killing thread. */
4284 ret
= sessiond_check_thread_quit_pipe(pollfd
, revents
);
4290 /* Event on the registration socket */
4291 if (pollfd
== sock
) {
4292 if (revents
& LPOLLIN
) {
4294 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4295 ERR("Health socket poll error");
4298 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
4304 new_sock
= lttcomm_accept_unix_sock(sock
);
4310 * Set the CLOEXEC flag. Return code is useless because either way, the
4313 (void) utils_set_fd_cloexec(new_sock
);
4315 DBG("Receiving data from client for health...");
4316 ret
= lttcomm_recv_unix_sock(new_sock
, (void *)&msg
, sizeof(msg
));
4318 DBG("Nothing recv() from client... continuing");
4319 ret
= close(new_sock
);
4326 rcu_thread_online();
4328 memset(&reply
, 0, sizeof(reply
));
4329 for (i
= 0; i
< NR_HEALTH_SESSIOND_TYPES
; i
++) {
4331 * health_check_state returns 0 if health is
4334 if (!health_check_state(health_sessiond
, i
)) {
4335 reply
.ret_code
|= 1ULL << i
;
4339 DBG2("Health check return value %" PRIx64
, reply
.ret_code
);
4341 ret
= send_unix_sock(new_sock
, (void *) &reply
, sizeof(reply
));
4343 ERR("Failed to send health data back to client");
4346 /* End of transmission */
4347 ret
= close(new_sock
);
4356 ERR("Health error occurred in %s", __func__
);
4358 DBG("Health check thread dying");
4359 unlink(health_unix_sock_path
);
4367 lttng_poll_clean(&events
);
4369 rcu_unregister_thread();
4374 * This thread manage all clients request using the unix client socket for
4377 static void *thread_manage_clients(void *data
)
4379 int sock
= -1, ret
, i
, pollfd
, err
= -1;
4381 uint32_t revents
, nb_fd
;
4382 struct command_ctx
*cmd_ctx
= NULL
;
4383 struct lttng_poll_event events
;
4385 DBG("[thread] Manage client started");
4387 rcu_register_thread();
4389 health_register(health_sessiond
, HEALTH_SESSIOND_TYPE_CMD
);
4391 health_code_update();
4393 ret
= lttcomm_listen_unix_sock(client_sock
);
4399 * Pass 2 as size here for the thread quit pipe and client_sock. Nothing
4400 * more will be added to this poll set.
4402 ret
= sessiond_set_thread_pollset(&events
, 2);
4404 goto error_create_poll
;
4407 /* Add the application registration socket */
4408 ret
= lttng_poll_add(&events
, client_sock
, LPOLLIN
| LPOLLPRI
);
4413 ret
= sem_post(&load_info
->message_thread_ready
);
4415 PERROR("sem_post message_thread_ready");
4420 * Wait until all support threads are initialized before accepting
4423 while (uatomic_read(<tng_sessiond_ready
) != 0) {
4425 struct timeval timeout
;
4428 FD_SET(thread_quit_pipe
[0], &read_fds
);
4429 memset(&timeout
, 0, sizeof(timeout
));
4430 timeout
.tv_usec
= 1000;
4433 * If a support thread failed to launch, it may signal that
4434 * we must exit and the sessiond would never be marked as
4437 * The timeout is set to 1ms, which serves as a way to
4438 * pace down this check.
4440 ret
= select(thread_quit_pipe
[0] + 1, &read_fds
, NULL
, NULL
,
4442 if (ret
> 0 || (ret
< 0 && errno
!= EINTR
)) {
4447 * This barrier is paired with the one in sessiond_notify_ready() to
4448 * ensure that loads accessing data initialized by the other threads,
4449 * on which this thread was waiting, are not performed before this point.
4451 * Note that this could be a 'read' memory barrier, but a full barrier
4452 * is used in case the code changes. The performance implications of
4453 * this choice are minimal since this is a slow path.
4457 /* This testpoint is after we signal readiness to the parent. */
4458 if (testpoint(sessiond_thread_manage_clients
)) {
4462 if (testpoint(sessiond_thread_manage_clients_before_loop
)) {
4466 health_code_update();
4469 DBG("Accepting client command ...");
4471 /* Inifinite blocking call, waiting for transmission */
4473 health_poll_entry();
4474 ret
= lttng_poll_wait(&events
, -1);
4478 * Restart interrupted system call.
4480 if (errno
== EINTR
) {
4488 for (i
= 0; i
< nb_fd
; i
++) {
4489 /* Fetch once the poll data */
4490 revents
= LTTNG_POLL_GETEV(&events
, i
);
4491 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4493 health_code_update();
4496 /* No activity for this FD (poll implementation). */
4500 /* Thread quit pipe has been closed. Killing thread. */
4501 ret
= sessiond_check_thread_quit_pipe(pollfd
, revents
);
4507 /* Event on the registration socket */
4508 if (pollfd
== client_sock
) {
4509 if (revents
& LPOLLIN
) {
4511 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4512 ERR("Client socket poll error");
4515 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
4521 DBG("Wait for client response");
4523 health_code_update();
4525 sock
= lttcomm_accept_unix_sock(client_sock
);
4531 * Set the CLOEXEC flag. Return code is useless because either way, the
4534 (void) utils_set_fd_cloexec(sock
);
4536 /* Set socket option for credentials retrieval */
4537 ret
= lttcomm_setsockopt_creds_unix_sock(sock
);
4542 /* Allocate context command to process the client request */
4543 cmd_ctx
= zmalloc(sizeof(struct command_ctx
));
4544 if (cmd_ctx
== NULL
) {
4545 PERROR("zmalloc cmd_ctx");
4549 /* Allocate data buffer for reception */
4550 cmd_ctx
->lsm
= zmalloc(sizeof(struct lttcomm_session_msg
));
4551 if (cmd_ctx
->lsm
== NULL
) {
4552 PERROR("zmalloc cmd_ctx->lsm");
4556 cmd_ctx
->llm
= NULL
;
4557 cmd_ctx
->session
= NULL
;
4559 health_code_update();
4562 * Data is received from the lttng client. The struct
4563 * lttcomm_session_msg (lsm) contains the command and data request of
4566 DBG("Receiving data from client ...");
4567 ret
= lttcomm_recv_creds_unix_sock(sock
, cmd_ctx
->lsm
,
4568 sizeof(struct lttcomm_session_msg
), &cmd_ctx
->creds
);
4570 DBG("Nothing recv() from client... continuing");
4576 clean_command_ctx(&cmd_ctx
);
4580 health_code_update();
4582 // TODO: Validate cmd_ctx including sanity check for
4583 // security purpose.
4585 rcu_thread_online();
4587 * This function dispatch the work to the kernel or userspace tracer
4588 * libs and fill the lttcomm_lttng_msg data structure of all the needed
4589 * informations for the client. The command context struct contains
4590 * everything this function may needs.
4592 ret
= process_client_msg(cmd_ctx
, sock
, &sock_error
);
4593 rcu_thread_offline();
4601 * TODO: Inform client somehow of the fatal error. At
4602 * this point, ret < 0 means that a zmalloc failed
4603 * (ENOMEM). Error detected but still accept
4604 * command, unless a socket error has been
4607 clean_command_ctx(&cmd_ctx
);
4611 health_code_update();
4613 DBG("Sending response (size: %d, retcode: %s (%d))",
4614 cmd_ctx
->lttng_msg_size
,
4615 lttng_strerror(-cmd_ctx
->llm
->ret_code
),
4616 cmd_ctx
->llm
->ret_code
);
4617 ret
= send_unix_sock(sock
, cmd_ctx
->llm
, cmd_ctx
->lttng_msg_size
);
4619 ERR("Failed to send data back to client");
4622 /* End of transmission */
4629 clean_command_ctx(&cmd_ctx
);
4631 health_code_update();
4643 lttng_poll_clean(&events
);
4644 clean_command_ctx(&cmd_ctx
);
4648 unlink(client_unix_sock_path
);
4649 if (client_sock
>= 0) {
4650 ret
= close(client_sock
);
4658 ERR("Health error occurred in %s", __func__
);
4661 health_unregister(health_sessiond
);
4663 DBG("Client thread dying");
4665 rcu_unregister_thread();
4668 * Since we are creating the consumer threads, we own them, so we need
4669 * to join them before our thread exits.
4671 ret
= join_consumer_thread(&kconsumer_data
);
4674 PERROR("join_consumer");
4677 ret
= join_consumer_thread(&ustconsumer32_data
);
4680 PERROR("join_consumer ust32");
4683 ret
= join_consumer_thread(&ustconsumer64_data
);
4686 PERROR("join_consumer ust64");
4691 static int string_match(const char *str1
, const char *str2
)
4693 return (str1
&& str2
) && !strcmp(str1
, str2
);
4697 * Take an option from the getopt output and set it in the right variable to be
4700 * Return 0 on success else a negative value.
4702 static int set_option(int opt
, const char *arg
, const char *optname
)
4706 if (string_match(optname
, "client-sock") || opt
== 'c') {
4707 if (!arg
|| *arg
== '\0') {
4711 if (lttng_is_setuid_setgid()) {
4712 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4713 "-c, --client-sock");
4715 snprintf(client_unix_sock_path
, PATH_MAX
, "%s", arg
);
4717 } else if (string_match(optname
, "apps-sock") || opt
== 'a') {
4718 if (!arg
|| *arg
== '\0') {
4722 if (lttng_is_setuid_setgid()) {
4723 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4726 snprintf(apps_unix_sock_path
, PATH_MAX
, "%s", arg
);
4728 } else if (string_match(optname
, "daemonize") || opt
== 'd') {
4730 } else if (string_match(optname
, "background") || opt
== 'b') {
4732 } else if (string_match(optname
, "group") || opt
== 'g') {
4733 if (!arg
|| *arg
== '\0') {
4737 if (lttng_is_setuid_setgid()) {
4738 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4742 * If the override option is set, the pointer points to a
4743 * *non* const thus freeing it even though the variable type is
4746 if (tracing_group_name_override
) {
4747 free((void *) tracing_group_name
);
4749 tracing_group_name
= strdup(arg
);
4750 if (!tracing_group_name
) {
4754 tracing_group_name_override
= 1;
4756 } else if (string_match(optname
, "help") || opt
== 'h') {
4757 ret
= utils_show_man_page(8, "lttng-sessiond");
4759 ERR("Cannot view man page lttng-sessiond(8)");
4762 exit(ret
? EXIT_FAILURE
: EXIT_SUCCESS
);
4763 } else if (string_match(optname
, "version") || opt
== 'V') {
4764 opt_print_version
= 1;
4765 } else if (string_match(optname
, "sig-parent") || opt
== 'S') {
4767 } else if (string_match(optname
, "kconsumerd-err-sock")) {
4768 if (!arg
|| *arg
== '\0') {
4772 if (lttng_is_setuid_setgid()) {
4773 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4774 "--kconsumerd-err-sock");
4776 snprintf(kconsumer_data
.err_unix_sock_path
, PATH_MAX
, "%s", arg
);
4778 } else if (string_match(optname
, "kconsumerd-cmd-sock")) {
4779 if (!arg
|| *arg
== '\0') {
4783 if (lttng_is_setuid_setgid()) {
4784 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4785 "--kconsumerd-cmd-sock");
4787 snprintf(kconsumer_data
.cmd_unix_sock_path
, PATH_MAX
, "%s", arg
);
4789 } else if (string_match(optname
, "ustconsumerd64-err-sock")) {
4790 if (!arg
|| *arg
== '\0') {
4794 if (lttng_is_setuid_setgid()) {
4795 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4796 "--ustconsumerd64-err-sock");
4798 snprintf(ustconsumer64_data
.err_unix_sock_path
, PATH_MAX
, "%s", arg
);
4800 } else if (string_match(optname
, "ustconsumerd64-cmd-sock")) {
4801 if (!arg
|| *arg
== '\0') {
4805 if (lttng_is_setuid_setgid()) {
4806 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4807 "--ustconsumerd64-cmd-sock");
4809 snprintf(ustconsumer64_data
.cmd_unix_sock_path
, PATH_MAX
, "%s", arg
);
4811 } else if (string_match(optname
, "ustconsumerd32-err-sock")) {
4812 if (!arg
|| *arg
== '\0') {
4816 if (lttng_is_setuid_setgid()) {
4817 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4818 "--ustconsumerd32-err-sock");
4820 snprintf(ustconsumer32_data
.err_unix_sock_path
, PATH_MAX
, "%s", arg
);
4822 } else if (string_match(optname
, "ustconsumerd32-cmd-sock")) {
4823 if (!arg
|| *arg
== '\0') {
4827 if (lttng_is_setuid_setgid()) {
4828 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4829 "--ustconsumerd32-cmd-sock");
4831 snprintf(ustconsumer32_data
.cmd_unix_sock_path
, PATH_MAX
, "%s", arg
);
4833 } else if (string_match(optname
, "no-kernel")) {
4835 } else if (string_match(optname
, "quiet") || opt
== 'q') {
4836 lttng_opt_quiet
= 1;
4837 } else if (string_match(optname
, "verbose") || opt
== 'v') {
4838 /* Verbose level can increase using multiple -v */
4840 /* Value obtained from config file */
4841 lttng_opt_verbose
= config_parse_value(arg
);
4843 /* -v used on command line */
4844 lttng_opt_verbose
++;
4846 /* Clamp value to [0, 3] */
4847 lttng_opt_verbose
= lttng_opt_verbose
< 0 ? 0 :
4848 (lttng_opt_verbose
<= 3 ? lttng_opt_verbose
: 3);
4849 } else if (string_match(optname
, "verbose-consumer")) {
4851 opt_verbose_consumer
= config_parse_value(arg
);
4853 opt_verbose_consumer
++;
4855 } else if (string_match(optname
, "consumerd32-path")) {
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 "--consumerd32-path");
4864 if (consumerd32_bin_override
) {
4865 free((void *) consumerd32_bin
);
4867 consumerd32_bin
= strdup(arg
);
4868 if (!consumerd32_bin
) {
4872 consumerd32_bin_override
= 1;
4874 } else if (string_match(optname
, "consumerd32-libdir")) {
4875 if (!arg
|| *arg
== '\0') {
4879 if (lttng_is_setuid_setgid()) {
4880 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4881 "--consumerd32-libdir");
4883 if (consumerd32_libdir_override
) {
4884 free((void *) consumerd32_libdir
);
4886 consumerd32_libdir
= strdup(arg
);
4887 if (!consumerd32_libdir
) {
4891 consumerd32_libdir_override
= 1;
4893 } else if (string_match(optname
, "consumerd64-path")) {
4894 if (!arg
|| *arg
== '\0') {
4898 if (lttng_is_setuid_setgid()) {
4899 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4900 "--consumerd64-path");
4902 if (consumerd64_bin_override
) {
4903 free((void *) consumerd64_bin
);
4905 consumerd64_bin
= strdup(arg
);
4906 if (!consumerd64_bin
) {
4910 consumerd64_bin_override
= 1;
4912 } else if (string_match(optname
, "consumerd64-libdir")) {
4913 if (!arg
|| *arg
== '\0') {
4917 if (lttng_is_setuid_setgid()) {
4918 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4919 "--consumerd64-libdir");
4921 if (consumerd64_libdir_override
) {
4922 free((void *) consumerd64_libdir
);
4924 consumerd64_libdir
= strdup(arg
);
4925 if (!consumerd64_libdir
) {
4929 consumerd64_libdir_override
= 1;
4931 } else if (string_match(optname
, "pidfile") || opt
== 'p') {
4932 if (!arg
|| *arg
== '\0') {
4936 if (lttng_is_setuid_setgid()) {
4937 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4941 opt_pidfile
= strdup(arg
);
4947 } else if (string_match(optname
, "agent-tcp-port")) {
4948 if (!arg
|| *arg
== '\0') {
4952 if (lttng_is_setuid_setgid()) {
4953 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4954 "--agent-tcp-port");
4959 v
= strtoul(arg
, NULL
, 0);
4960 if (errno
!= 0 || !isdigit(arg
[0])) {
4961 ERR("Wrong value in --agent-tcp-port parameter: %s", arg
);
4964 if (v
== 0 || v
>= 65535) {
4965 ERR("Port overflow in --agent-tcp-port parameter: %s", arg
);
4968 agent_tcp_port
= (uint32_t) v
;
4969 DBG3("Agent TCP port set to non default: %u", agent_tcp_port
);
4971 } else if (string_match(optname
, "load") || opt
== 'l') {
4972 if (!arg
|| *arg
== '\0') {
4976 if (lttng_is_setuid_setgid()) {
4977 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4980 free(opt_load_session_path
);
4981 opt_load_session_path
= strdup(arg
);
4982 if (!opt_load_session_path
) {
4987 } else if (string_match(optname
, "kmod-probes")) {
4988 if (!arg
|| *arg
== '\0') {
4992 if (lttng_is_setuid_setgid()) {
4993 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4996 free(kmod_probes_list
);
4997 kmod_probes_list
= strdup(arg
);
4998 if (!kmod_probes_list
) {
5003 } else if (string_match(optname
, "extra-kmod-probes")) {
5004 if (!arg
|| *arg
== '\0') {
5008 if (lttng_is_setuid_setgid()) {
5009 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
5010 "--extra-kmod-probes");
5012 free(kmod_extra_probes_list
);
5013 kmod_extra_probes_list
= strdup(arg
);
5014 if (!kmod_extra_probes_list
) {
5019 } else if (string_match(optname
, "config") || opt
== 'f') {
5020 /* This is handled in set_options() thus silent skip. */
5023 /* Unknown option or other error.
5024 * Error is printed by getopt, just return */
5029 if (ret
== -EINVAL
) {
5030 const char *opt_name
= "unknown";
5033 for (i
= 0; i
< sizeof(long_options
) / sizeof(struct option
);
5035 if (opt
== long_options
[i
].val
) {
5036 opt_name
= long_options
[i
].name
;
5041 WARN("Invalid argument provided for option \"%s\", using default value.",
5049 * config_entry_handler_cb used to handle options read from a config file.
5050 * See config_entry_handler_cb comment in common/config/session-config.h for the
5051 * return value conventions.
5053 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
5057 if (!entry
|| !entry
->name
|| !entry
->value
) {
5062 /* Check if the option is to be ignored */
5063 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
5064 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
5069 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1;
5072 /* Ignore if not fully matched. */
5073 if (strcmp(entry
->name
, long_options
[i
].name
)) {
5078 * If the option takes no argument on the command line, we have to
5079 * check if the value is "true". We support non-zero numeric values,
5082 if (!long_options
[i
].has_arg
) {
5083 ret
= config_parse_value(entry
->value
);
5086 WARN("Invalid configuration value \"%s\" for option %s",
5087 entry
->value
, entry
->name
);
5089 /* False, skip boolean config option. */
5094 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
5098 WARN("Unrecognized option \"%s\" in daemon configuration file.", entry
->name
);
5104 static void sessiond_config_log(void)
5106 DBG("LTTng-sessiond " VERSION
" - " VERSION_NAME
"%s%s",
5107 GIT_VERSION
[0] == '\0' ? "" : " - " GIT_VERSION
,
5108 EXTRA_VERSION_NAME
[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME
);
5109 if (EXTRA_VERSION_DESCRIPTION
[0] != '\0') {
5110 DBG("LTTng-sessiond extra version description:\n\t" EXTRA_VERSION_DESCRIPTION
"\n");
5114 static void print_version(void) {
5115 fprintf(stdout
, "%s\n", VERSION
);
5119 * daemon configuration loading and argument parsing
5121 static int set_options(int argc
, char **argv
)
5123 int ret
= 0, c
= 0, option_index
= 0;
5124 int orig_optopt
= optopt
, orig_optind
= optind
;
5126 const char *config_path
= NULL
;
5128 optstring
= utils_generate_optstring(long_options
,
5129 sizeof(long_options
) / sizeof(struct option
));
5135 /* Check for the --config option */
5136 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
5137 &option_index
)) != -1) {
5141 } else if (c
!= 'f') {
5142 /* if not equal to --config option. */
5146 if (lttng_is_setuid_setgid()) {
5147 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
5150 config_path
= utils_expand_path(optarg
);
5152 ERR("Failed to resolve path: %s", optarg
);
5157 ret
= config_get_section_entries(config_path
, config_section_name
,
5158 config_entry_handler
, NULL
);
5161 ERR("Invalid configuration option at line %i", ret
);
5167 /* Reset getopt's global state */
5168 optopt
= orig_optopt
;
5169 optind
= orig_optind
;
5173 * getopt_long() will not set option_index if it encounters a
5176 c
= getopt_long(argc
, argv
, optstring
, long_options
,
5183 * Pass NULL as the long option name if popt left the index
5186 ret
= set_option(c
, optarg
,
5187 option_index
< 0 ? NULL
:
5188 long_options
[option_index
].name
);
5200 * Creates the two needed socket by the daemon.
5201 * apps_sock - The communication socket for all UST apps.
5202 * client_sock - The communication of the cli tool (lttng).
5204 static int init_daemon_socket(void)
5209 old_umask
= umask(0);
5211 /* Create client tool unix socket */
5212 client_sock
= lttcomm_create_unix_sock(client_unix_sock_path
);
5213 if (client_sock
< 0) {
5214 ERR("Create unix sock failed: %s", client_unix_sock_path
);
5219 /* Set the cloexec flag */
5220 ret
= utils_set_fd_cloexec(client_sock
);
5222 ERR("Unable to set CLOEXEC flag to the client Unix socket (fd: %d). "
5223 "Continuing but note that the consumer daemon will have a "
5224 "reference to this socket on exec()", client_sock
);
5227 /* File permission MUST be 660 */
5228 ret
= chmod(client_unix_sock_path
, S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
5230 ERR("Set file permissions failed: %s", client_unix_sock_path
);
5235 /* Create the application unix socket */
5236 apps_sock
= lttcomm_create_unix_sock(apps_unix_sock_path
);
5237 if (apps_sock
< 0) {
5238 ERR("Create unix sock failed: %s", apps_unix_sock_path
);
5243 /* Set the cloexec flag */
5244 ret
= utils_set_fd_cloexec(apps_sock
);
5246 ERR("Unable to set CLOEXEC flag to the app Unix socket (fd: %d). "
5247 "Continuing but note that the consumer daemon will have a "
5248 "reference to this socket on exec()", apps_sock
);
5251 /* File permission MUST be 666 */
5252 ret
= chmod(apps_unix_sock_path
,
5253 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
| S_IROTH
| S_IWOTH
);
5255 ERR("Set file permissions failed: %s", apps_unix_sock_path
);
5260 DBG3("Session daemon client socket %d and application socket %d created",
5261 client_sock
, apps_sock
);
5269 * Check if the global socket is available, and if a daemon is answering at the
5270 * other side. If yes, error is returned.
5272 static int check_existing_daemon(void)
5274 /* Is there anybody out there ? */
5275 if (lttng_session_daemon_alive()) {
5283 * Set the tracing group gid onto the client socket.
5285 * Race window between mkdir and chown is OK because we are going from more
5286 * permissive (root.root) to less permissive (root.tracing).
5288 static int set_permissions(char *rundir
)
5293 gid
= utils_get_group_id(tracing_group_name
);
5295 /* Set lttng run dir */
5296 ret
= chown(rundir
, 0, gid
);
5298 ERR("Unable to set group on %s", rundir
);
5303 * Ensure all applications and tracing group can search the run
5304 * dir. Allow everyone to read the directory, since it does not
5305 * buy us anything to hide its content.
5307 ret
= chmod(rundir
, S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
5309 ERR("Unable to set permissions on %s", rundir
);
5313 /* lttng client socket path */
5314 ret
= chown(client_unix_sock_path
, 0, gid
);
5316 ERR("Unable to set group on %s", client_unix_sock_path
);
5320 /* kconsumer error socket path */
5321 ret
= chown(kconsumer_data
.err_unix_sock_path
, 0, 0);
5323 ERR("Unable to set group on %s", kconsumer_data
.err_unix_sock_path
);
5327 /* 64-bit ustconsumer error socket path */
5328 ret
= chown(ustconsumer64_data
.err_unix_sock_path
, 0, 0);
5330 ERR("Unable to set group on %s", ustconsumer64_data
.err_unix_sock_path
);
5334 /* 32-bit ustconsumer compat32 error socket path */
5335 ret
= chown(ustconsumer32_data
.err_unix_sock_path
, 0, 0);
5337 ERR("Unable to set group on %s", ustconsumer32_data
.err_unix_sock_path
);
5341 DBG("All permissions are set");
5347 * Create the lttng run directory needed for all global sockets and pipe.
5349 static int create_lttng_rundir(const char *rundir
)
5353 DBG3("Creating LTTng run directory: %s", rundir
);
5355 ret
= mkdir(rundir
, S_IRWXU
);
5357 if (errno
!= EEXIST
) {
5358 ERR("Unable to create %s", rundir
);
5370 * Setup sockets and directory needed by the kconsumerd communication with the
5373 static int set_consumer_sockets(struct consumer_data
*consumer_data
,
5377 char path
[PATH_MAX
];
5379 switch (consumer_data
->type
) {
5380 case LTTNG_CONSUMER_KERNEL
:
5381 snprintf(path
, PATH_MAX
, DEFAULT_KCONSUMERD_PATH
, rundir
);
5383 case LTTNG_CONSUMER64_UST
:
5384 snprintf(path
, PATH_MAX
, DEFAULT_USTCONSUMERD64_PATH
, rundir
);
5386 case LTTNG_CONSUMER32_UST
:
5387 snprintf(path
, PATH_MAX
, DEFAULT_USTCONSUMERD32_PATH
, rundir
);
5390 ERR("Consumer type unknown");
5395 DBG2("Creating consumer directory: %s", path
);
5397 ret
= mkdir(path
, S_IRWXU
| S_IRGRP
| S_IXGRP
);
5399 if (errno
!= EEXIST
) {
5401 ERR("Failed to create %s", path
);
5407 ret
= chown(path
, 0, utils_get_group_id(tracing_group_name
));
5409 ERR("Unable to set group on %s", path
);
5415 /* Create the kconsumerd error unix socket */
5416 consumer_data
->err_sock
=
5417 lttcomm_create_unix_sock(consumer_data
->err_unix_sock_path
);
5418 if (consumer_data
->err_sock
< 0) {
5419 ERR("Create unix sock failed: %s", consumer_data
->err_unix_sock_path
);
5425 * Set the CLOEXEC flag. Return code is useless because either way, the
5428 ret
= utils_set_fd_cloexec(consumer_data
->err_sock
);
5430 PERROR("utils_set_fd_cloexec");
5431 /* continue anyway */
5434 /* File permission MUST be 660 */
5435 ret
= chmod(consumer_data
->err_unix_sock_path
,
5436 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
5438 ERR("Set file permissions failed: %s", consumer_data
->err_unix_sock_path
);
5448 * Signal handler for the daemon
5450 * Simply stop all worker threads, leaving main() return gracefully after
5451 * joining all threads and calling cleanup().
5453 static void sighandler(int sig
)
5457 DBG("SIGINT caught");
5461 DBG("SIGTERM caught");
5465 CMM_STORE_SHARED(recv_child_signal
, 1);
5473 * Setup signal handler for :
5474 * SIGINT, SIGTERM, SIGPIPE
5476 static int set_signal_handler(void)
5479 struct sigaction sa
;
5482 if ((ret
= sigemptyset(&sigset
)) < 0) {
5483 PERROR("sigemptyset");
5487 sa
.sa_mask
= sigset
;
5490 sa
.sa_handler
= sighandler
;
5491 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
5492 PERROR("sigaction");
5496 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
5497 PERROR("sigaction");
5501 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
5502 PERROR("sigaction");
5506 sa
.sa_handler
= SIG_IGN
;
5507 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
5508 PERROR("sigaction");
5512 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
5518 * Set open files limit to unlimited. This daemon can open a large number of
5519 * file descriptors in order to consume multiple kernel traces.
5521 static void set_ulimit(void)
5526 /* The kernel does not allow an infinite limit for open files */
5527 lim
.rlim_cur
= 65535;
5528 lim
.rlim_max
= 65535;
5530 ret
= setrlimit(RLIMIT_NOFILE
, &lim
);
5532 PERROR("failed to set open files limit");
5537 * Write pidfile using the rundir and opt_pidfile.
5539 static int write_pidfile(void)
5542 char pidfile_path
[PATH_MAX
];
5547 if (lttng_strncpy(pidfile_path
, opt_pidfile
, sizeof(pidfile_path
))) {
5552 /* Build pidfile path from rundir and opt_pidfile. */
5553 ret
= snprintf(pidfile_path
, sizeof(pidfile_path
), "%s/"
5554 DEFAULT_LTTNG_SESSIOND_PIDFILE
, rundir
);
5556 PERROR("snprintf pidfile path");
5562 * Create pid file in rundir.
5564 ret
= utils_create_pid_file(getpid(), pidfile_path
);
5570 * Create lockfile using the rundir and return its fd.
5572 static int create_lockfile(void)
5575 char lockfile_path
[PATH_MAX
];
5577 ret
= generate_lock_file_path(lockfile_path
, sizeof(lockfile_path
));
5582 ret
= utils_create_lock_file(lockfile_path
);
5588 * Write agent TCP port using the rundir.
5590 static int write_agent_port(void)
5593 char path
[PATH_MAX
];
5597 ret
= snprintf(path
, sizeof(path
), "%s/"
5598 DEFAULT_LTTNG_SESSIOND_AGENTPORT_FILE
, rundir
);
5600 PERROR("snprintf agent port path");
5605 * Create TCP agent port file in rundir.
5607 ret
= utils_create_pid_file(agent_tcp_port
, path
);
5613 static int set_clock_plugin_env(void)
5616 const char *original_env_value
;
5617 char *full_path
= NULL
;
5618 char *new_env_value
= NULL
;
5620 original_env_value
= getenv("LTTNG_UST_CLOCK_PLUGIN");
5621 if (!original_env_value
) {
5625 full_path
= utils_expand_path(original_env_value
);
5627 ERR("Failed to expand LTTNG_UST_CLOCK_PLUGIN path \"%s\"",
5628 original_env_value
);
5632 ret
= asprintf(&new_env_value
, "LTTNG_UST_CLOCK_PLUGIN=%s",
5640 DBG("Updating environment: %s", new_env_value
);
5641 ret
= putenv(new_env_value
);
5643 free(new_env_value
);
5644 PERROR("putenv of LTTNG_UST_CLOCK_PLUGIN");
5654 int main(int argc
, char **argv
)
5656 int ret
= 0, retval
= 0;
5658 const char *home_path
, *env_app_timeout
;
5660 init_kernel_workarounds();
5662 rcu_register_thread();
5664 if (set_signal_handler()) {
5666 goto exit_set_signal_handler
;
5669 setup_consumerd_path();
5671 page_size
= sysconf(_SC_PAGESIZE
);
5672 if (page_size
< 0) {
5673 PERROR("sysconf _SC_PAGESIZE");
5674 page_size
= LONG_MAX
;
5675 WARN("Fallback page size to %ld", page_size
);
5679 * Parse arguments and load the daemon configuration file.
5681 * We have an exit_options exit path to free memory reserved by
5682 * set_options. This is needed because the rest of sessiond_cleanup()
5683 * depends on ht_cleanup_thread, which depends on lttng_daemonize, which
5684 * depends on set_options.
5687 if (set_options(argc
, argv
)) {
5692 sessiond_config_log();
5694 if (opt_print_version
) {
5700 ret
= set_clock_plugin_env();
5707 if (opt_daemon
|| opt_background
) {
5710 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
5718 * We are in the child. Make sure all other file descriptors are
5719 * closed, in case we are called with more opened file
5720 * descriptors than the standard ones.
5722 for (i
= 3; i
< sysconf(_SC_OPEN_MAX
); i
++) {
5727 if (run_as_create_worker(argv
[0]) < 0) {
5728 goto exit_create_run_as_worker_cleanup
;
5732 * Starting from here, we can create threads. This needs to be after
5733 * lttng_daemonize due to RCU.
5737 * Initialize the health check subsystem. This call should set the
5738 * appropriate time values.
5740 health_sessiond
= health_app_create(NR_HEALTH_SESSIOND_TYPES
);
5741 if (!health_sessiond
) {
5742 PERROR("health_app_create error");
5744 goto exit_health_sessiond_cleanup
;
5747 /* Create thread to clean up RCU hash tables */
5748 if (init_ht_cleanup_thread(&ht_cleanup_thread
)) {
5750 goto exit_ht_cleanup
;
5753 /* Create thread quit pipe */
5754 if (init_thread_quit_pipe()) {
5756 goto exit_init_data
;
5759 /* Check if daemon is UID = 0 */
5760 is_root
= !getuid();
5763 rundir
= strdup(DEFAULT_LTTNG_RUNDIR
);
5766 goto exit_init_data
;
5769 /* Create global run dir with root access */
5770 if (create_lttng_rundir(rundir
)) {
5772 goto exit_init_data
;
5775 if (strlen(apps_unix_sock_path
) == 0) {
5776 ret
= snprintf(apps_unix_sock_path
, PATH_MAX
,
5777 DEFAULT_GLOBAL_APPS_UNIX_SOCK
);
5780 goto exit_init_data
;
5784 if (strlen(client_unix_sock_path
) == 0) {
5785 ret
= snprintf(client_unix_sock_path
, PATH_MAX
,
5786 DEFAULT_GLOBAL_CLIENT_UNIX_SOCK
);
5789 goto exit_init_data
;
5793 /* Set global SHM for ust */
5794 if (strlen(wait_shm_path
) == 0) {
5795 ret
= snprintf(wait_shm_path
, PATH_MAX
,
5796 DEFAULT_GLOBAL_APPS_WAIT_SHM_PATH
);
5799 goto exit_init_data
;
5803 if (strlen(health_unix_sock_path
) == 0) {
5804 ret
= snprintf(health_unix_sock_path
,
5805 sizeof(health_unix_sock_path
),
5806 DEFAULT_GLOBAL_HEALTH_UNIX_SOCK
);
5809 goto exit_init_data
;
5813 /* Setup kernel consumerd path */
5814 ret
= snprintf(kconsumer_data
.err_unix_sock_path
, PATH_MAX
,
5815 DEFAULT_KCONSUMERD_ERR_SOCK_PATH
, rundir
);
5818 goto exit_init_data
;
5820 ret
= snprintf(kconsumer_data
.cmd_unix_sock_path
, PATH_MAX
,
5821 DEFAULT_KCONSUMERD_CMD_SOCK_PATH
, rundir
);
5824 goto exit_init_data
;
5827 DBG2("Kernel consumer err path: %s",
5828 kconsumer_data
.err_unix_sock_path
);
5829 DBG2("Kernel consumer cmd path: %s",
5830 kconsumer_data
.cmd_unix_sock_path
);
5832 home_path
= utils_get_home_dir();
5833 if (home_path
== NULL
) {
5834 /* TODO: Add --socket PATH option */
5835 ERR("Can't get HOME directory for sockets creation.");
5837 goto exit_init_data
;
5841 * Create rundir from home path. This will create something like
5844 ret
= asprintf(&rundir
, DEFAULT_LTTNG_HOME_RUNDIR
, home_path
);
5847 goto exit_init_data
;
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_HOME_APPS_UNIX_SOCK
,
5861 goto exit_init_data
;
5865 /* Set the cli tool unix socket path */
5866 if (strlen(client_unix_sock_path
) == 0) {
5867 ret
= snprintf(client_unix_sock_path
, PATH_MAX
,
5868 DEFAULT_HOME_CLIENT_UNIX_SOCK
,
5872 goto exit_init_data
;
5876 /* Set global SHM for ust */
5877 if (strlen(wait_shm_path
) == 0) {
5878 ret
= snprintf(wait_shm_path
, PATH_MAX
,
5879 DEFAULT_HOME_APPS_WAIT_SHM_PATH
,
5883 goto exit_init_data
;
5887 /* Set health check Unix path */
5888 if (strlen(health_unix_sock_path
) == 0) {
5889 ret
= snprintf(health_unix_sock_path
,
5890 sizeof(health_unix_sock_path
),
5891 DEFAULT_HOME_HEALTH_UNIX_SOCK
,
5895 goto exit_init_data
;
5900 lockfile_fd
= create_lockfile();
5901 if (lockfile_fd
< 0) {
5903 goto exit_init_data
;
5906 /* Set consumer initial state */
5907 kernel_consumerd_state
= CONSUMER_STOPPED
;
5908 ust_consumerd_state
= CONSUMER_STOPPED
;
5910 DBG("Client socket path %s", client_unix_sock_path
);
5911 DBG("Application socket path %s", apps_unix_sock_path
);
5912 DBG("Application wait path %s", wait_shm_path
);
5913 DBG("LTTng run directory path: %s", rundir
);
5915 /* 32 bits consumerd path setup */
5916 ret
= snprintf(ustconsumer32_data
.err_unix_sock_path
, PATH_MAX
,
5917 DEFAULT_USTCONSUMERD32_ERR_SOCK_PATH
, rundir
);
5919 PERROR("snprintf 32-bit consumer error socket path");
5921 goto exit_init_data
;
5923 ret
= snprintf(ustconsumer32_data
.cmd_unix_sock_path
, PATH_MAX
,
5924 DEFAULT_USTCONSUMERD32_CMD_SOCK_PATH
, rundir
);
5926 PERROR("snprintf 32-bit consumer command socket path");
5928 goto exit_init_data
;
5931 DBG2("UST consumer 32 bits err path: %s",
5932 ustconsumer32_data
.err_unix_sock_path
);
5933 DBG2("UST consumer 32 bits cmd path: %s",
5934 ustconsumer32_data
.cmd_unix_sock_path
);
5936 /* 64 bits consumerd path setup */
5937 ret
= snprintf(ustconsumer64_data
.err_unix_sock_path
, PATH_MAX
,
5938 DEFAULT_USTCONSUMERD64_ERR_SOCK_PATH
, rundir
);
5940 PERROR("snprintf 64-bit consumer error socket path");
5942 goto exit_init_data
;
5944 ret
= snprintf(ustconsumer64_data
.cmd_unix_sock_path
, PATH_MAX
,
5945 DEFAULT_USTCONSUMERD64_CMD_SOCK_PATH
, rundir
);
5947 PERROR("snprintf 64-bit consumer command socket path");
5949 goto exit_init_data
;
5952 DBG2("UST consumer 64 bits err path: %s",
5953 ustconsumer64_data
.err_unix_sock_path
);
5954 DBG2("UST consumer 64 bits cmd path: %s",
5955 ustconsumer64_data
.cmd_unix_sock_path
);
5958 * See if daemon already exist.
5960 if (check_existing_daemon()) {
5961 ERR("Already running daemon.\n");
5963 * We do not goto exit because we must not cleanup()
5964 * because a daemon is already running.
5967 goto exit_init_data
;
5971 * Init UST app hash table. Alloc hash table before this point since
5972 * cleanup() can get called after that point.
5974 if (ust_app_ht_alloc()) {
5975 ERR("Failed to allocate UST app hash table");
5977 goto exit_init_data
;
5981 * Initialize agent app hash table. We allocate the hash table here
5982 * since cleanup() can get called after this point.
5984 if (agent_app_ht_alloc()) {
5985 ERR("Failed to allocate Agent app hash table");
5987 goto exit_init_data
;
5991 * These actions must be executed as root. We do that *after* setting up
5992 * the sockets path because we MUST make the check for another daemon using
5993 * those paths *before* trying to set the kernel consumer sockets and init
5997 if (set_consumer_sockets(&kconsumer_data
, rundir
)) {
5999 goto exit_init_data
;
6002 /* Setup kernel tracer */
6003 if (!opt_no_kernel
) {
6004 init_kernel_tracer();
6005 if (kernel_tracer_fd
>= 0) {
6006 ret
= syscall_init_table();
6008 ERR("Unable to populate syscall table. "
6009 "Syscall tracing won't work "
6010 "for this session daemon.");
6015 /* Set ulimit for open files */
6018 /* init lttng_fd tracking must be done after set_ulimit. */
6021 if (set_consumer_sockets(&ustconsumer64_data
, rundir
)) {
6023 goto exit_init_data
;
6026 if (set_consumer_sockets(&ustconsumer32_data
, rundir
)) {
6028 goto exit_init_data
;
6031 /* Setup the needed unix socket */
6032 if (init_daemon_socket()) {
6034 goto exit_init_data
;
6037 /* Set credentials to socket */
6038 if (is_root
&& set_permissions(rundir
)) {
6040 goto exit_init_data
;
6043 /* Get parent pid if -S, --sig-parent is specified. */
6044 if (opt_sig_parent
) {
6048 /* Setup the kernel pipe for waking up the kernel thread */
6049 if (is_root
&& !opt_no_kernel
) {
6050 if (utils_create_pipe_cloexec(kernel_poll_pipe
)) {
6052 goto exit_init_data
;
6056 /* Setup the thread apps communication pipe. */
6057 if (utils_create_pipe_cloexec(apps_cmd_pipe
)) {
6059 goto exit_init_data
;
6062 /* Setup the thread apps notify communication pipe. */
6063 if (utils_create_pipe_cloexec(apps_cmd_notify_pipe
)) {
6065 goto exit_init_data
;
6068 /* Initialize global buffer per UID and PID registry. */
6069 buffer_reg_init_uid_registry();
6070 buffer_reg_init_pid_registry();
6072 /* Init UST command queue. */
6073 cds_wfcq_init(&ust_cmd_queue
.head
, &ust_cmd_queue
.tail
);
6076 * Get session list pointer. This pointer MUST NOT be free'd. This list
6077 * is statically declared in session.c
6079 session_list_ptr
= session_get_list();
6083 /* Check for the application socket timeout env variable. */
6084 env_app_timeout
= getenv(DEFAULT_APP_SOCKET_TIMEOUT_ENV
);
6085 if (env_app_timeout
) {
6086 app_socket_timeout
= atoi(env_app_timeout
);
6088 app_socket_timeout
= DEFAULT_APP_SOCKET_RW_TIMEOUT
;
6091 ret
= write_pidfile();
6093 ERR("Error in write_pidfile");
6095 goto exit_init_data
;
6097 ret
= write_agent_port();
6099 ERR("Error in write_agent_port");
6101 goto exit_init_data
;
6104 /* Initialize communication library */
6106 /* Initialize TCP timeout values */
6107 lttcomm_inet_init();
6109 if (load_session_init_data(&load_info
) < 0) {
6111 goto exit_init_data
;
6113 load_info
->path
= opt_load_session_path
;
6115 /* Create health-check thread */
6116 ret
= pthread_create(&health_thread
, default_pthread_attr(),
6117 thread_manage_health
, (void *) NULL
);
6120 PERROR("pthread_create health");
6125 /* Create thread to manage the client socket */
6126 ret
= pthread_create(&client_thread
, default_pthread_attr(),
6127 thread_manage_clients
, (void *) NULL
);
6130 PERROR("pthread_create clients");
6135 /* Create thread to dispatch registration */
6136 ret
= pthread_create(&dispatch_thread
, default_pthread_attr(),
6137 thread_dispatch_ust_registration
, (void *) NULL
);
6140 PERROR("pthread_create dispatch");
6145 /* Create thread to manage application registration. */
6146 ret
= pthread_create(®_apps_thread
, default_pthread_attr(),
6147 thread_registration_apps
, (void *) NULL
);
6150 PERROR("pthread_create registration");
6155 /* Create thread to manage application socket */
6156 ret
= pthread_create(&apps_thread
, default_pthread_attr(),
6157 thread_manage_apps
, (void *) NULL
);
6160 PERROR("pthread_create apps");
6165 /* Create thread to manage application notify socket */
6166 ret
= pthread_create(&apps_notify_thread
, default_pthread_attr(),
6167 ust_thread_manage_notify
, (void *) NULL
);
6170 PERROR("pthread_create notify");
6172 goto exit_apps_notify
;
6175 /* Create agent registration thread. */
6176 ret
= pthread_create(&agent_reg_thread
, default_pthread_attr(),
6177 agent_thread_manage_registration
, (void *) NULL
);
6180 PERROR("pthread_create agent");
6182 goto exit_agent_reg
;
6185 /* Don't start this thread if kernel tracing is not requested nor root */
6186 if (is_root
&& !opt_no_kernel
) {
6187 /* Create kernel thread to manage kernel event */
6188 ret
= pthread_create(&kernel_thread
, default_pthread_attr(),
6189 thread_manage_kernel
, (void *) NULL
);
6192 PERROR("pthread_create kernel");
6198 /* Create session loading thread. */
6199 ret
= pthread_create(&load_session_thread
, default_pthread_attr(),
6200 thread_load_session
, load_info
);
6203 PERROR("pthread_create load_session_thread");
6205 goto exit_load_session
;
6209 * This is where we start awaiting program completion (e.g. through
6210 * signal that asks threads to teardown).
6213 ret
= pthread_join(load_session_thread
, &status
);
6216 PERROR("pthread_join load_session_thread");
6221 if (is_root
&& !opt_no_kernel
) {
6222 ret
= pthread_join(kernel_thread
, &status
);
6225 PERROR("pthread_join");
6231 ret
= pthread_join(agent_reg_thread
, &status
);
6234 PERROR("pthread_join agent");
6239 ret
= pthread_join(apps_notify_thread
, &status
);
6242 PERROR("pthread_join apps notify");
6247 ret
= pthread_join(apps_thread
, &status
);
6250 PERROR("pthread_join apps");
6255 ret
= pthread_join(reg_apps_thread
, &status
);
6258 PERROR("pthread_join");
6264 * Join dispatch thread after joining reg_apps_thread to ensure
6265 * we don't leak applications in the queue.
6267 ret
= pthread_join(dispatch_thread
, &status
);
6270 PERROR("pthread_join");
6275 ret
= pthread_join(client_thread
, &status
);
6278 PERROR("pthread_join");
6283 ret
= pthread_join(health_thread
, &status
);
6286 PERROR("pthread_join health thread");
6293 * Wait for all pending call_rcu work to complete before tearing
6294 * down data structures. call_rcu worker may be trying to
6295 * perform lookups in those structures.
6299 * sessiond_cleanup() is called when no other thread is running, except
6300 * the ht_cleanup thread, which is needed to destroy the hash tables.
6302 rcu_thread_online();
6304 rcu_thread_offline();
6305 rcu_unregister_thread();
6308 * Ensure all prior call_rcu are done. call_rcu callbacks may push
6309 * hash tables to the ht_cleanup thread. Therefore, we ensure that
6310 * the queue is empty before shutting down the clean-up thread.
6314 ret
= fini_ht_cleanup_thread(&ht_cleanup_thread
);
6320 health_app_destroy(health_sessiond
);
6321 exit_health_sessiond_cleanup
:
6322 exit_create_run_as_worker_cleanup
:
6325 sessiond_cleanup_options();
6327 exit_set_signal_handler
: