Fix: unprivilieged sessiond agent port clashes with root sessiond
[lttng-tools.git] / src / bin / lttng-sessiond / main.c
1 /*
2 * Copyright (C) 2011 - David Goulet <david.goulet@polymtl.ca>
3 * Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
4 * 2013 - Jérémie Galarneau <jeremie.galarneau@efficios.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License, version 2 only,
8 * as published by the Free Software Foundation.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #define _LGPL_SOURCE
21 #include <getopt.h>
22 #include <grp.h>
23 #include <limits.h>
24 #include <paths.h>
25 #include <pthread.h>
26 #include <signal.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <inttypes.h>
31 #include <sys/mman.h>
32 #include <sys/mount.h>
33 #include <sys/resource.h>
34 #include <sys/socket.h>
35 #include <sys/stat.h>
36 #include <sys/types.h>
37 #include <sys/wait.h>
38 #include <urcu/uatomic.h>
39 #include <unistd.h>
40 #include <ctype.h>
41
42 #include <common/common.h>
43 #include <common/compat/socket.h>
44 #include <common/compat/getenv.h>
45 #include <common/defaults.h>
46 #include <common/kernel-consumer/kernel-consumer.h>
47 #include <common/futex.h>
48 #include <common/relayd/relayd.h>
49 #include <common/utils.h>
50 #include <common/daemonize.h>
51 #include <common/config/session-config.h>
52
53 #include "lttng-sessiond.h"
54 #include "buffer-registry.h"
55 #include "channel.h"
56 #include "cmd.h"
57 #include "consumer.h"
58 #include "context.h"
59 #include "event.h"
60 #include "kernel.h"
61 #include "kernel-consumer.h"
62 #include "modprobe.h"
63 #include "shm.h"
64 #include "ust-ctl.h"
65 #include "ust-consumer.h"
66 #include "utils.h"
67 #include "fd-limit.h"
68 #include "health-sessiond.h"
69 #include "testpoint.h"
70 #include "ust-thread.h"
71 #include "agent-thread.h"
72 #include "save.h"
73 #include "load-session-thread.h"
74 #include "notification-thread.h"
75 #include "notification-thread-commands.h"
76 #include "rotation-thread.h"
77 #include "lttng-syscall.h"
78 #include "agent.h"
79 #include "ht-cleanup.h"
80 #include "sessiond-config.h"
81 #include "sessiond-timer.h"
82
83 static const char *help_msg =
84 #ifdef LTTNG_EMBED_HELP
85 #include <lttng-sessiond.8.h>
86 #else
87 NULL
88 #endif
89 ;
90
91 const char *progname;
92 static pid_t ppid; /* Parent PID for --sig-parent option */
93 static pid_t child_ppid; /* Internal parent PID use with daemonize. */
94 static int lockfile_fd = -1;
95
96 /* Set to 1 when a SIGUSR1 signal is received. */
97 static int recv_child_signal;
98
99 static struct lttng_kernel_tracer_version kernel_tracer_version;
100 static struct lttng_kernel_tracer_abi_version kernel_tracer_abi_version;
101
102 /*
103 * Consumer daemon specific control data. Every value not initialized here is
104 * set to 0 by the static definition.
105 */
106 static struct consumer_data kconsumer_data = {
107 .type = LTTNG_CONSUMER_KERNEL,
108 .err_sock = -1,
109 .cmd_sock = -1,
110 .channel_monitor_pipe = -1,
111 .channel_rotate_pipe = -1,
112 .pid_mutex = PTHREAD_MUTEX_INITIALIZER,
113 .lock = PTHREAD_MUTEX_INITIALIZER,
114 .cond = PTHREAD_COND_INITIALIZER,
115 .cond_mutex = PTHREAD_MUTEX_INITIALIZER,
116 };
117 static struct consumer_data ustconsumer64_data = {
118 .type = LTTNG_CONSUMER64_UST,
119 .err_sock = -1,
120 .cmd_sock = -1,
121 .channel_monitor_pipe = -1,
122 .channel_rotate_pipe = -1,
123 .pid_mutex = PTHREAD_MUTEX_INITIALIZER,
124 .lock = PTHREAD_MUTEX_INITIALIZER,
125 .cond = PTHREAD_COND_INITIALIZER,
126 .cond_mutex = PTHREAD_MUTEX_INITIALIZER,
127 };
128 static struct consumer_data ustconsumer32_data = {
129 .type = LTTNG_CONSUMER32_UST,
130 .err_sock = -1,
131 .cmd_sock = -1,
132 .channel_monitor_pipe = -1,
133 .channel_rotate_pipe = -1,
134 .pid_mutex = PTHREAD_MUTEX_INITIALIZER,
135 .lock = PTHREAD_MUTEX_INITIALIZER,
136 .cond = PTHREAD_COND_INITIALIZER,
137 .cond_mutex = PTHREAD_MUTEX_INITIALIZER,
138 };
139
140 /* Command line options */
141 static const struct option long_options[] = {
142 { "client-sock", required_argument, 0, 'c' },
143 { "apps-sock", required_argument, 0, 'a' },
144 { "kconsumerd-cmd-sock", required_argument, 0, '\0' },
145 { "kconsumerd-err-sock", required_argument, 0, '\0' },
146 { "ustconsumerd32-cmd-sock", required_argument, 0, '\0' },
147 { "ustconsumerd32-err-sock", required_argument, 0, '\0' },
148 { "ustconsumerd64-cmd-sock", required_argument, 0, '\0' },
149 { "ustconsumerd64-err-sock", required_argument, 0, '\0' },
150 { "consumerd32-path", required_argument, 0, '\0' },
151 { "consumerd32-libdir", required_argument, 0, '\0' },
152 { "consumerd64-path", required_argument, 0, '\0' },
153 { "consumerd64-libdir", required_argument, 0, '\0' },
154 { "daemonize", no_argument, 0, 'd' },
155 { "background", no_argument, 0, 'b' },
156 { "sig-parent", no_argument, 0, 'S' },
157 { "help", no_argument, 0, 'h' },
158 { "group", required_argument, 0, 'g' },
159 { "version", no_argument, 0, 'V' },
160 { "quiet", no_argument, 0, 'q' },
161 { "verbose", no_argument, 0, 'v' },
162 { "verbose-consumer", no_argument, 0, '\0' },
163 { "no-kernel", no_argument, 0, '\0' },
164 { "pidfile", required_argument, 0, 'p' },
165 { "agent-tcp-port", required_argument, 0, '\0' },
166 { "config", required_argument, 0, 'f' },
167 { "load", required_argument, 0, 'l' },
168 { "kmod-probes", required_argument, 0, '\0' },
169 { "extra-kmod-probes", required_argument, 0, '\0' },
170 { NULL, 0, 0, 0 }
171 };
172
173 struct sessiond_config config;
174
175 /* Command line options to ignore from configuration file */
176 static const char *config_ignore_options[] = { "help", "version", "config" };
177
178 /* Shared between threads */
179 static int dispatch_thread_exit;
180
181 /* Sockets and FDs */
182 static int client_sock = -1;
183 static int apps_sock = -1;
184 int kernel_tracer_fd = -1;
185 static int kernel_poll_pipe[2] = { -1, -1 };
186
187 /*
188 * Quit pipe for all threads. This permits a single cancellation point
189 * for all threads when receiving an event on the pipe.
190 */
191 static int thread_quit_pipe[2] = { -1, -1 };
192
193 /*
194 * This pipe is used to inform the thread managing application communication
195 * that a command is queued and ready to be processed.
196 */
197 static int apps_cmd_pipe[2] = { -1, -1 };
198
199 int apps_cmd_notify_pipe[2] = { -1, -1 };
200
201 /* Pthread, Mutexes and Semaphores */
202 static pthread_t apps_thread;
203 static pthread_t apps_notify_thread;
204 static pthread_t reg_apps_thread;
205 static pthread_t client_thread;
206 static pthread_t kernel_thread;
207 static pthread_t dispatch_thread;
208 static pthread_t health_thread;
209 static pthread_t ht_cleanup_thread;
210 static pthread_t agent_reg_thread;
211 static pthread_t load_session_thread;
212 static pthread_t notification_thread;
213 static pthread_t rotation_thread;
214 static pthread_t timer_thread;
215
216 /*
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
219 *
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.
224 */
225 static struct ust_cmd_queue ust_cmd_queue;
226
227 /*
228 * Pointer initialized before thread creation.
229 *
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.
233 *
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.
236 */
237 static struct ltt_session_list *session_list_ptr;
238
239 int ust_consumerd64_fd = -1;
240 int ust_consumerd32_fd = -1;
241
242 static const char *module_proc_lttng = "/proc/lttng";
243
244 /*
245 * Consumer daemon state which is changed when spawning it, killing it or in
246 * case of a fatal error.
247 */
248 enum consumerd_state {
249 CONSUMER_STARTED = 1,
250 CONSUMER_STOPPED = 2,
251 CONSUMER_ERROR = 3,
252 };
253
254 /*
255 * This consumer daemon state is used to validate if a client command will be
256 * able to reach the consumer. If not, the client is informed. For instance,
257 * doing a "lttng start" when the consumer state is set to ERROR will return an
258 * error to the client.
259 *
260 * The following example shows a possible race condition of this scheme:
261 *
262 * consumer thread error happens
263 * client cmd arrives
264 * client cmd checks state -> still OK
265 * consumer thread exit, sets error
266 * client cmd try to talk to consumer
267 * ...
268 *
269 * However, since the consumer is a different daemon, we have no way of making
270 * sure the command will reach it safely even with this state flag. This is why
271 * we consider that up to the state validation during command processing, the
272 * command is safe. After that, we can not guarantee the correctness of the
273 * client request vis-a-vis the consumer.
274 */
275 static enum consumerd_state ust_consumerd_state;
276 static enum consumerd_state kernel_consumerd_state;
277
278 /* Set in main() with the current page size. */
279 long page_size;
280
281 /* Application health monitoring */
282 struct health_app *health_sessiond;
283
284 /* Am I root or not. */
285 int is_root; /* Set to 1 if the daemon is running as root */
286
287 const char * const config_section_name = "sessiond";
288
289 /* Load session thread information to operate. */
290 struct load_session_thread_data *load_info;
291
292 /* Notification thread handle. */
293 struct notification_thread_handle *notification_thread_handle;
294
295 /* Rotation thread handle. */
296 struct rotation_thread_handle *rotation_thread_handle;
297
298 /* Global hash tables */
299 struct lttng_ht *agent_apps_ht_by_sock = NULL;
300
301 /*
302 * Whether sessiond is ready for commands/notification channel/health check
303 * requests.
304 * NR_LTTNG_SESSIOND_READY must match the number of calls to
305 * sessiond_notify_ready().
306 */
307 #define NR_LTTNG_SESSIOND_READY 6
308 int lttng_sessiond_ready = NR_LTTNG_SESSIOND_READY;
309
310 int sessiond_check_thread_quit_pipe(int fd, uint32_t events)
311 {
312 return (fd == thread_quit_pipe[0] && (events & LPOLLIN)) ? 1 : 0;
313 }
314
315 /* Notify parents that we are ready for cmd and health check */
316 LTTNG_HIDDEN
317 void sessiond_notify_ready(void)
318 {
319 if (uatomic_sub_return(&lttng_sessiond_ready, 1) == 0) {
320 /*
321 * Notify parent pid that we are ready to accept command
322 * for client side. This ppid is the one from the
323 * external process that spawned us.
324 */
325 if (config.sig_parent) {
326 kill(ppid, SIGUSR1);
327 }
328
329 /*
330 * Notify the parent of the fork() process that we are
331 * ready.
332 */
333 if (config.daemonize || config.background) {
334 kill(child_ppid, SIGUSR1);
335 }
336 }
337 }
338
339 static
340 int __sessiond_set_thread_pollset(struct lttng_poll_event *events, size_t size,
341 int *a_pipe)
342 {
343 int ret;
344
345 assert(events);
346
347 ret = lttng_poll_create(events, size, LTTNG_CLOEXEC);
348 if (ret < 0) {
349 goto error;
350 }
351
352 /* Add quit pipe */
353 ret = lttng_poll_add(events, a_pipe[0], LPOLLIN | LPOLLERR);
354 if (ret < 0) {
355 goto error;
356 }
357
358 return 0;
359
360 error:
361 return ret;
362 }
363
364 /*
365 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
366 */
367 int sessiond_set_thread_pollset(struct lttng_poll_event *events, size_t size)
368 {
369 return __sessiond_set_thread_pollset(events, size, thread_quit_pipe);
370 }
371
372 /*
373 * Init thread quit pipe.
374 *
375 * Return -1 on error or 0 if all pipes are created.
376 */
377 static int __init_thread_quit_pipe(int *a_pipe)
378 {
379 int ret, i;
380
381 ret = pipe(a_pipe);
382 if (ret < 0) {
383 PERROR("thread quit pipe");
384 goto error;
385 }
386
387 for (i = 0; i < 2; i++) {
388 ret = fcntl(a_pipe[i], F_SETFD, FD_CLOEXEC);
389 if (ret < 0) {
390 PERROR("fcntl");
391 goto error;
392 }
393 }
394
395 error:
396 return ret;
397 }
398
399 static int init_thread_quit_pipe(void)
400 {
401 return __init_thread_quit_pipe(thread_quit_pipe);
402 }
403
404 /*
405 * Stop all threads by closing the thread quit pipe.
406 */
407 static void stop_threads(void)
408 {
409 int ret;
410
411 /* Stopping all threads */
412 DBG("Terminating all threads");
413 ret = notify_thread_pipe(thread_quit_pipe[1]);
414 if (ret < 0) {
415 ERR("write error on thread quit pipe");
416 }
417
418 /* Dispatch thread */
419 CMM_STORE_SHARED(dispatch_thread_exit, 1);
420 futex_nto1_wake(&ust_cmd_queue.futex);
421 }
422
423 /*
424 * Close every consumer sockets.
425 */
426 static void close_consumer_sockets(void)
427 {
428 int ret;
429
430 if (kconsumer_data.err_sock >= 0) {
431 ret = close(kconsumer_data.err_sock);
432 if (ret < 0) {
433 PERROR("kernel consumer err_sock close");
434 }
435 }
436 if (ustconsumer32_data.err_sock >= 0) {
437 ret = close(ustconsumer32_data.err_sock);
438 if (ret < 0) {
439 PERROR("UST consumerd32 err_sock close");
440 }
441 }
442 if (ustconsumer64_data.err_sock >= 0) {
443 ret = close(ustconsumer64_data.err_sock);
444 if (ret < 0) {
445 PERROR("UST consumerd64 err_sock close");
446 }
447 }
448 if (kconsumer_data.cmd_sock >= 0) {
449 ret = close(kconsumer_data.cmd_sock);
450 if (ret < 0) {
451 PERROR("kernel consumer cmd_sock close");
452 }
453 }
454 if (ustconsumer32_data.cmd_sock >= 0) {
455 ret = close(ustconsumer32_data.cmd_sock);
456 if (ret < 0) {
457 PERROR("UST consumerd32 cmd_sock close");
458 }
459 }
460 if (ustconsumer64_data.cmd_sock >= 0) {
461 ret = close(ustconsumer64_data.cmd_sock);
462 if (ret < 0) {
463 PERROR("UST consumerd64 cmd_sock close");
464 }
465 }
466 if (kconsumer_data.channel_monitor_pipe >= 0) {
467 ret = close(kconsumer_data.channel_monitor_pipe);
468 if (ret < 0) {
469 PERROR("kernel consumer channel monitor pipe close");
470 }
471 }
472 if (ustconsumer32_data.channel_monitor_pipe >= 0) {
473 ret = close(ustconsumer32_data.channel_monitor_pipe);
474 if (ret < 0) {
475 PERROR("UST consumerd32 channel monitor pipe close");
476 }
477 }
478 if (ustconsumer64_data.channel_monitor_pipe >= 0) {
479 ret = close(ustconsumer64_data.channel_monitor_pipe);
480 if (ret < 0) {
481 PERROR("UST consumerd64 channel monitor pipe close");
482 }
483 }
484 if (kconsumer_data.channel_rotate_pipe >= 0) {
485 ret = close(kconsumer_data.channel_rotate_pipe);
486 if (ret < 0) {
487 PERROR("kernel consumer channel rotate pipe close");
488 }
489 }
490 if (ustconsumer32_data.channel_rotate_pipe >= 0) {
491 ret = close(ustconsumer32_data.channel_rotate_pipe);
492 if (ret < 0) {
493 PERROR("UST consumerd32 channel rotate pipe close");
494 }
495 }
496 if (ustconsumer64_data.channel_rotate_pipe >= 0) {
497 ret = close(ustconsumer64_data.channel_rotate_pipe);
498 if (ret < 0) {
499 PERROR("UST consumerd64 channel rotate pipe close");
500 }
501 }
502 }
503
504 /*
505 * Wait on consumer process termination.
506 *
507 * Need to be called with the consumer data lock held or from a context
508 * ensuring no concurrent access to data (e.g: cleanup).
509 */
510 static void wait_consumer(struct consumer_data *consumer_data)
511 {
512 pid_t ret;
513 int status;
514
515 if (consumer_data->pid <= 0) {
516 return;
517 }
518
519 DBG("Waiting for complete teardown of consumerd (PID: %d)",
520 consumer_data->pid);
521 ret = waitpid(consumer_data->pid, &status, 0);
522 if (ret == -1) {
523 PERROR("consumerd waitpid pid: %d", consumer_data->pid)
524 } else if (!WIFEXITED(status)) {
525 ERR("consumerd termination with error: %d",
526 WEXITSTATUS(ret));
527 }
528 consumer_data->pid = 0;
529 }
530
531 /*
532 * Cleanup the session daemon's data structures.
533 */
534 static void sessiond_cleanup(void)
535 {
536 int ret;
537 struct ltt_session *sess, *stmp;
538
539 DBG("Cleanup sessiond");
540
541 /*
542 * Close the thread quit pipe. It has already done its job,
543 * since we are now called.
544 */
545 utils_close_pipe(thread_quit_pipe);
546
547 /*
548 * If config.pid_file_path.value is undefined, the default file will be
549 * wiped when removing the rundir.
550 */
551 if (config.pid_file_path.value) {
552 ret = remove(config.pid_file_path.value);
553 if (ret < 0) {
554 PERROR("remove pidfile %s", config.pid_file_path.value);
555 }
556 }
557
558 DBG("Removing sessiond and consumerd content of directory %s",
559 config.rundir.value);
560
561 /* sessiond */
562 DBG("Removing %s", config.pid_file_path.value);
563 (void) unlink(config.pid_file_path.value);
564
565 DBG("Removing %s", config.agent_port_file_path.value);
566 (void) unlink(config.agent_port_file_path.value);
567
568 /* kconsumerd */
569 DBG("Removing %s", kconsumer_data.err_unix_sock_path);
570 (void) unlink(kconsumer_data.err_unix_sock_path);
571
572 DBG("Removing directory %s", config.kconsumerd_path.value);
573 (void) rmdir(config.kconsumerd_path.value);
574
575 /* ust consumerd 32 */
576 DBG("Removing %s", config.consumerd32_err_unix_sock_path.value);
577 (void) unlink(config.consumerd32_err_unix_sock_path.value);
578
579 DBG("Removing directory %s", config.consumerd32_path.value);
580 (void) rmdir(config.consumerd32_path.value);
581
582 /* ust consumerd 64 */
583 DBG("Removing %s", config.consumerd64_err_unix_sock_path.value);
584 (void) unlink(config.consumerd64_err_unix_sock_path.value);
585
586 DBG("Removing directory %s", config.consumerd64_path.value);
587 (void) rmdir(config.consumerd64_path.value);
588
589 DBG("Cleaning up all sessions");
590
591 /* Destroy session list mutex */
592 if (session_list_ptr != NULL) {
593 pthread_mutex_destroy(&session_list_ptr->lock);
594
595 /* Cleanup ALL session */
596 cds_list_for_each_entry_safe(sess, stmp,
597 &session_list_ptr->head, list) {
598 cmd_destroy_session(sess, kernel_poll_pipe[1],
599 notification_thread_handle);
600 }
601 }
602
603 wait_consumer(&kconsumer_data);
604 wait_consumer(&ustconsumer64_data);
605 wait_consumer(&ustconsumer32_data);
606
607 DBG("Cleaning up all agent apps");
608 agent_app_ht_clean();
609
610 DBG("Closing all UST sockets");
611 ust_app_clean_list();
612 buffer_reg_destroy_registries();
613
614 if (is_root && !config.no_kernel) {
615 DBG2("Closing kernel fd");
616 if (kernel_tracer_fd >= 0) {
617 ret = close(kernel_tracer_fd);
618 if (ret) {
619 PERROR("close");
620 }
621 }
622 DBG("Unloading kernel modules");
623 modprobe_remove_lttng_all();
624 free(syscall_table);
625 }
626
627 close_consumer_sockets();
628
629 if (load_info) {
630 load_session_destroy_data(load_info);
631 free(load_info);
632 }
633
634 /*
635 * We do NOT rmdir rundir because there are other processes
636 * using it, for instance lttng-relayd, which can start in
637 * parallel with this teardown.
638 */
639 }
640
641 /*
642 * Cleanup the daemon's option data structures.
643 */
644 static void sessiond_cleanup_options(void)
645 {
646 DBG("Cleaning up options");
647
648 sessiond_config_fini(&config);
649
650 run_as_destroy_worker();
651 }
652
653 /*
654 * Send data on a unix socket using the liblttsessiondcomm API.
655 *
656 * Return lttcomm error code.
657 */
658 static int send_unix_sock(int sock, void *buf, size_t len)
659 {
660 /* Check valid length */
661 if (len == 0) {
662 return -1;
663 }
664
665 return lttcomm_send_unix_sock(sock, buf, len);
666 }
667
668 /*
669 * Free memory of a command context structure.
670 */
671 static void clean_command_ctx(struct command_ctx **cmd_ctx)
672 {
673 DBG("Clean command context structure");
674 if (*cmd_ctx) {
675 if ((*cmd_ctx)->llm) {
676 free((*cmd_ctx)->llm);
677 }
678 if ((*cmd_ctx)->lsm) {
679 free((*cmd_ctx)->lsm);
680 }
681 free(*cmd_ctx);
682 *cmd_ctx = NULL;
683 }
684 }
685
686 /*
687 * Notify UST applications using the shm mmap futex.
688 */
689 static int notify_ust_apps(int active)
690 {
691 char *wait_shm_mmap;
692
693 DBG("Notifying applications of session daemon state: %d", active);
694
695 /* See shm.c for this call implying mmap, shm and futex calls */
696 wait_shm_mmap = shm_ust_get_mmap(config.wait_shm_path.value, is_root);
697 if (wait_shm_mmap == NULL) {
698 goto error;
699 }
700
701 /* Wake waiting process */
702 futex_wait_update((int32_t *) wait_shm_mmap, active);
703
704 /* Apps notified successfully */
705 return 0;
706
707 error:
708 return -1;
709 }
710
711 /*
712 * Setup the outgoing data buffer for the response (llm) by allocating the
713 * right amount of memory and copying the original information from the lsm
714 * structure.
715 *
716 * Return 0 on success, negative value on error.
717 */
718 static int setup_lttng_msg(struct command_ctx *cmd_ctx,
719 const void *payload_buf, size_t payload_len,
720 const void *cmd_header_buf, size_t cmd_header_len)
721 {
722 int ret = 0;
723 const size_t header_len = sizeof(struct lttcomm_lttng_msg);
724 const size_t cmd_header_offset = header_len;
725 const size_t payload_offset = cmd_header_offset + cmd_header_len;
726 const size_t total_msg_size = header_len + cmd_header_len + payload_len;
727
728 cmd_ctx->llm = zmalloc(total_msg_size);
729
730 if (cmd_ctx->llm == NULL) {
731 PERROR("zmalloc");
732 ret = -ENOMEM;
733 goto end;
734 }
735
736 /* Copy common data */
737 cmd_ctx->llm->cmd_type = cmd_ctx->lsm->cmd_type;
738 cmd_ctx->llm->pid = cmd_ctx->lsm->domain.attr.pid;
739 cmd_ctx->llm->cmd_header_size = cmd_header_len;
740 cmd_ctx->llm->data_size = payload_len;
741 cmd_ctx->lttng_msg_size = total_msg_size;
742
743 /* Copy command header */
744 if (cmd_header_len) {
745 memcpy(((uint8_t *) cmd_ctx->llm) + cmd_header_offset, cmd_header_buf,
746 cmd_header_len);
747 }
748
749 /* Copy payload */
750 if (payload_len) {
751 memcpy(((uint8_t *) cmd_ctx->llm) + payload_offset, payload_buf,
752 payload_len);
753 }
754
755 end:
756 return ret;
757 }
758
759 /*
760 * Version of setup_lttng_msg() without command header.
761 */
762 static int setup_lttng_msg_no_cmd_header(struct command_ctx *cmd_ctx,
763 void *payload_buf, size_t payload_len)
764 {
765 return setup_lttng_msg(cmd_ctx, payload_buf, payload_len, NULL, 0);
766 }
767 /*
768 * Update the kernel poll set of all channel fd available over all tracing
769 * session. Add the wakeup pipe at the end of the set.
770 */
771 static int update_kernel_poll(struct lttng_poll_event *events)
772 {
773 int ret;
774 struct ltt_session *session;
775 struct ltt_kernel_channel *channel;
776
777 DBG("Updating kernel poll set");
778
779 session_lock_list();
780 cds_list_for_each_entry(session, &session_list_ptr->head, list) {
781 session_lock(session);
782 if (session->kernel_session == NULL) {
783 session_unlock(session);
784 continue;
785 }
786
787 cds_list_for_each_entry(channel,
788 &session->kernel_session->channel_list.head, list) {
789 /* Add channel fd to the kernel poll set */
790 ret = lttng_poll_add(events, channel->fd, LPOLLIN | LPOLLRDNORM);
791 if (ret < 0) {
792 session_unlock(session);
793 goto error;
794 }
795 DBG("Channel fd %d added to kernel set", channel->fd);
796 }
797 session_unlock(session);
798 }
799 session_unlock_list();
800
801 return 0;
802
803 error:
804 session_unlock_list();
805 return -1;
806 }
807
808 /*
809 * Find the channel fd from 'fd' over all tracing session. When found, check
810 * for new channel stream and send those stream fds to the kernel consumer.
811 *
812 * Useful for CPU hotplug feature.
813 */
814 static int update_kernel_stream(struct consumer_data *consumer_data, int fd)
815 {
816 int ret = 0;
817 struct ltt_session *session;
818 struct ltt_kernel_session *ksess;
819 struct ltt_kernel_channel *channel;
820
821 DBG("Updating kernel streams for channel fd %d", fd);
822
823 session_lock_list();
824 cds_list_for_each_entry(session, &session_list_ptr->head, list) {
825 session_lock(session);
826 if (session->kernel_session == NULL) {
827 session_unlock(session);
828 continue;
829 }
830 ksess = session->kernel_session;
831
832 cds_list_for_each_entry(channel,
833 &ksess->channel_list.head, list) {
834 struct lttng_ht_iter iter;
835 struct consumer_socket *socket;
836
837 if (channel->fd != fd) {
838 continue;
839 }
840 DBG("Channel found, updating kernel streams");
841 ret = kernel_open_channel_stream(channel);
842 if (ret < 0) {
843 goto error;
844 }
845 /* Update the stream global counter */
846 ksess->stream_count_global += ret;
847
848 /*
849 * Have we already sent fds to the consumer? If yes, it
850 * means that tracing is started so it is safe to send
851 * our updated stream fds.
852 */
853 if (ksess->consumer_fds_sent != 1
854 || ksess->consumer == NULL) {
855 ret = -1;
856 goto error;
857 }
858
859 rcu_read_lock();
860 cds_lfht_for_each_entry(ksess->consumer->socks->ht,
861 &iter.iter, socket, node.node) {
862 pthread_mutex_lock(socket->lock);
863 ret = kernel_consumer_send_channel_stream(socket,
864 channel, ksess,
865 session->output_traces ? 1 : 0);
866 pthread_mutex_unlock(socket->lock);
867 if (ret < 0) {
868 rcu_read_unlock();
869 goto error;
870 }
871 }
872 rcu_read_unlock();
873 }
874 session_unlock(session);
875 }
876 session_unlock_list();
877 return ret;
878
879 error:
880 session_unlock(session);
881 session_unlock_list();
882 return ret;
883 }
884
885 /*
886 * For each tracing session, update newly registered apps. The session list
887 * lock MUST be acquired before calling this.
888 */
889 static void update_ust_app(int app_sock)
890 {
891 struct ltt_session *sess, *stmp;
892
893 /* Consumer is in an ERROR state. Stop any application update. */
894 if (uatomic_read(&ust_consumerd_state) == CONSUMER_ERROR) {
895 /* Stop the update process since the consumer is dead. */
896 return;
897 }
898
899 /* For all tracing session(s) */
900 cds_list_for_each_entry_safe(sess, stmp, &session_list_ptr->head, list) {
901 struct ust_app *app;
902
903 session_lock(sess);
904 if (!sess->ust_session) {
905 goto unlock_session;
906 }
907
908 rcu_read_lock();
909 assert(app_sock >= 0);
910 app = ust_app_find_by_sock(app_sock);
911 if (app == NULL) {
912 /*
913 * Application can be unregistered before so
914 * this is possible hence simply stopping the
915 * update.
916 */
917 DBG3("UST app update failed to find app sock %d",
918 app_sock);
919 goto unlock_rcu;
920 }
921 ust_app_global_update(sess->ust_session, app);
922 unlock_rcu:
923 rcu_read_unlock();
924 unlock_session:
925 session_unlock(sess);
926 }
927 }
928
929 /*
930 * This thread manage event coming from the kernel.
931 *
932 * Features supported in this thread:
933 * -) CPU Hotplug
934 */
935 static void *thread_manage_kernel(void *data)
936 {
937 int ret, i, pollfd, update_poll_flag = 1, err = -1;
938 uint32_t revents, nb_fd;
939 char tmp;
940 struct lttng_poll_event events;
941
942 DBG("[thread] Thread manage kernel started");
943
944 health_register(health_sessiond, HEALTH_SESSIOND_TYPE_KERNEL);
945
946 /*
947 * This first step of the while is to clean this structure which could free
948 * non NULL pointers so initialize it before the loop.
949 */
950 lttng_poll_init(&events);
951
952 if (testpoint(sessiond_thread_manage_kernel)) {
953 goto error_testpoint;
954 }
955
956 health_code_update();
957
958 if (testpoint(sessiond_thread_manage_kernel_before_loop)) {
959 goto error_testpoint;
960 }
961
962 while (1) {
963 health_code_update();
964
965 if (update_poll_flag == 1) {
966 /* Clean events object. We are about to populate it again. */
967 lttng_poll_clean(&events);
968
969 ret = sessiond_set_thread_pollset(&events, 2);
970 if (ret < 0) {
971 goto error_poll_create;
972 }
973
974 ret = lttng_poll_add(&events, kernel_poll_pipe[0], LPOLLIN);
975 if (ret < 0) {
976 goto error;
977 }
978
979 /* This will add the available kernel channel if any. */
980 ret = update_kernel_poll(&events);
981 if (ret < 0) {
982 goto error;
983 }
984 update_poll_flag = 0;
985 }
986
987 DBG("Thread kernel polling");
988
989 /* Poll infinite value of time */
990 restart:
991 health_poll_entry();
992 ret = lttng_poll_wait(&events, -1);
993 DBG("Thread kernel return from poll on %d fds",
994 LTTNG_POLL_GETNB(&events));
995 health_poll_exit();
996 if (ret < 0) {
997 /*
998 * Restart interrupted system call.
999 */
1000 if (errno == EINTR) {
1001 goto restart;
1002 }
1003 goto error;
1004 } else if (ret == 0) {
1005 /* Should not happen since timeout is infinite */
1006 ERR("Return value of poll is 0 with an infinite timeout.\n"
1007 "This should not have happened! Continuing...");
1008 continue;
1009 }
1010
1011 nb_fd = ret;
1012
1013 for (i = 0; i < nb_fd; i++) {
1014 /* Fetch once the poll data */
1015 revents = LTTNG_POLL_GETEV(&events, i);
1016 pollfd = LTTNG_POLL_GETFD(&events, i);
1017
1018 health_code_update();
1019
1020 if (!revents) {
1021 /* No activity for this FD (poll implementation). */
1022 continue;
1023 }
1024
1025 /* Thread quit pipe has been closed. Killing thread. */
1026 ret = sessiond_check_thread_quit_pipe(pollfd, revents);
1027 if (ret) {
1028 err = 0;
1029 goto exit;
1030 }
1031
1032 /* Check for data on kernel pipe */
1033 if (revents & LPOLLIN) {
1034 if (pollfd == kernel_poll_pipe[0]) {
1035 (void) lttng_read(kernel_poll_pipe[0],
1036 &tmp, 1);
1037 /*
1038 * Ret value is useless here, if this pipe gets any actions an
1039 * update is required anyway.
1040 */
1041 update_poll_flag = 1;
1042 continue;
1043 } else {
1044 /*
1045 * New CPU detected by the kernel. Adding kernel stream to
1046 * kernel session and updating the kernel consumer
1047 */
1048 ret = update_kernel_stream(&kconsumer_data, pollfd);
1049 if (ret < 0) {
1050 continue;
1051 }
1052 break;
1053 }
1054 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
1055 update_poll_flag = 1;
1056 continue;
1057 } else {
1058 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
1059 goto error;
1060 }
1061 }
1062 }
1063
1064 exit:
1065 error:
1066 lttng_poll_clean(&events);
1067 error_poll_create:
1068 error_testpoint:
1069 utils_close_pipe(kernel_poll_pipe);
1070 kernel_poll_pipe[0] = kernel_poll_pipe[1] = -1;
1071 if (err) {
1072 health_error();
1073 ERR("Health error occurred in %s", __func__);
1074 WARN("Kernel thread died unexpectedly. "
1075 "Kernel tracing can continue but CPU hotplug is disabled.");
1076 }
1077 health_unregister(health_sessiond);
1078 DBG("Kernel thread dying");
1079 return NULL;
1080 }
1081
1082 /*
1083 * Signal pthread condition of the consumer data that the thread.
1084 */
1085 static void signal_consumer_condition(struct consumer_data *data, int state)
1086 {
1087 pthread_mutex_lock(&data->cond_mutex);
1088
1089 /*
1090 * The state is set before signaling. It can be any value, it's the waiter
1091 * job to correctly interpret this condition variable associated to the
1092 * consumer pthread_cond.
1093 *
1094 * A value of 0 means that the corresponding thread of the consumer data
1095 * was not started. 1 indicates that the thread has started and is ready
1096 * for action. A negative value means that there was an error during the
1097 * thread bootstrap.
1098 */
1099 data->consumer_thread_is_ready = state;
1100 (void) pthread_cond_signal(&data->cond);
1101
1102 pthread_mutex_unlock(&data->cond_mutex);
1103 }
1104
1105 /*
1106 * This thread manage the consumer error sent back to the session daemon.
1107 */
1108 static void *thread_manage_consumer(void *data)
1109 {
1110 int sock = -1, i, ret, pollfd, err = -1, should_quit = 0;
1111 uint32_t revents, nb_fd;
1112 enum lttcomm_return_code code;
1113 struct lttng_poll_event events;
1114 struct consumer_data *consumer_data = data;
1115 struct consumer_socket *cmd_socket_wrapper = NULL;
1116
1117 DBG("[thread] Manage consumer started");
1118
1119 rcu_register_thread();
1120 rcu_thread_online();
1121
1122 health_register(health_sessiond, HEALTH_SESSIOND_TYPE_CONSUMER);
1123
1124 health_code_update();
1125
1126 /*
1127 * Pass 3 as size here for the thread quit pipe, consumerd_err_sock and the
1128 * metadata_sock. Nothing more will be added to this poll set.
1129 */
1130 ret = sessiond_set_thread_pollset(&events, 3);
1131 if (ret < 0) {
1132 goto error_poll;
1133 }
1134
1135 /*
1136 * The error socket here is already in a listening state which was done
1137 * just before spawning this thread to avoid a race between the consumer
1138 * daemon exec trying to connect and the listen() call.
1139 */
1140 ret = lttng_poll_add(&events, consumer_data->err_sock, LPOLLIN | LPOLLRDHUP);
1141 if (ret < 0) {
1142 goto error;
1143 }
1144
1145 health_code_update();
1146
1147 /* Infinite blocking call, waiting for transmission */
1148 restart:
1149 health_poll_entry();
1150
1151 if (testpoint(sessiond_thread_manage_consumer)) {
1152 goto error;
1153 }
1154
1155 ret = lttng_poll_wait(&events, -1);
1156 health_poll_exit();
1157 if (ret < 0) {
1158 /*
1159 * Restart interrupted system call.
1160 */
1161 if (errno == EINTR) {
1162 goto restart;
1163 }
1164 goto error;
1165 }
1166
1167 nb_fd = ret;
1168
1169 for (i = 0; i < nb_fd; i++) {
1170 /* Fetch once the poll data */
1171 revents = LTTNG_POLL_GETEV(&events, i);
1172 pollfd = LTTNG_POLL_GETFD(&events, i);
1173
1174 health_code_update();
1175
1176 if (!revents) {
1177 /* No activity for this FD (poll implementation). */
1178 continue;
1179 }
1180
1181 /* Thread quit pipe has been closed. Killing thread. */
1182 ret = sessiond_check_thread_quit_pipe(pollfd, revents);
1183 if (ret) {
1184 err = 0;
1185 goto exit;
1186 }
1187
1188 /* Event on the registration socket */
1189 if (pollfd == consumer_data->err_sock) {
1190 if (revents & LPOLLIN) {
1191 continue;
1192 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
1193 ERR("consumer err socket poll error");
1194 goto error;
1195 } else {
1196 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
1197 goto error;
1198 }
1199 }
1200 }
1201
1202 sock = lttcomm_accept_unix_sock(consumer_data->err_sock);
1203 if (sock < 0) {
1204 goto error;
1205 }
1206
1207 /*
1208 * Set the CLOEXEC flag. Return code is useless because either way, the
1209 * show must go on.
1210 */
1211 (void) utils_set_fd_cloexec(sock);
1212
1213 health_code_update();
1214
1215 DBG2("Receiving code from consumer err_sock");
1216
1217 /* Getting status code from kconsumerd */
1218 ret = lttcomm_recv_unix_sock(sock, &code,
1219 sizeof(enum lttcomm_return_code));
1220 if (ret <= 0) {
1221 goto error;
1222 }
1223
1224 health_code_update();
1225 if (code != LTTCOMM_CONSUMERD_COMMAND_SOCK_READY) {
1226 ERR("consumer error when waiting for SOCK_READY : %s",
1227 lttcomm_get_readable_code(-code));
1228 goto error;
1229 }
1230
1231 /* Connect both command and metadata sockets. */
1232 consumer_data->cmd_sock =
1233 lttcomm_connect_unix_sock(
1234 consumer_data->cmd_unix_sock_path);
1235 consumer_data->metadata_fd =
1236 lttcomm_connect_unix_sock(
1237 consumer_data->cmd_unix_sock_path);
1238 if (consumer_data->cmd_sock < 0 || consumer_data->metadata_fd < 0) {
1239 PERROR("consumer connect cmd socket");
1240 /* On error, signal condition and quit. */
1241 signal_consumer_condition(consumer_data, -1);
1242 goto error;
1243 }
1244
1245 consumer_data->metadata_sock.fd_ptr = &consumer_data->metadata_fd;
1246
1247 /* Create metadata socket lock. */
1248 consumer_data->metadata_sock.lock = zmalloc(sizeof(pthread_mutex_t));
1249 if (consumer_data->metadata_sock.lock == NULL) {
1250 PERROR("zmalloc pthread mutex");
1251 goto error;
1252 }
1253 pthread_mutex_init(consumer_data->metadata_sock.lock, NULL);
1254
1255 DBG("Consumer command socket ready (fd: %d", consumer_data->cmd_sock);
1256 DBG("Consumer metadata socket ready (fd: %d)",
1257 consumer_data->metadata_fd);
1258
1259 /*
1260 * Remove the consumerd error sock since we've established a connection.
1261 */
1262 ret = lttng_poll_del(&events, consumer_data->err_sock);
1263 if (ret < 0) {
1264 goto error;
1265 }
1266
1267 /* Add new accepted error socket. */
1268 ret = lttng_poll_add(&events, sock, LPOLLIN | LPOLLRDHUP);
1269 if (ret < 0) {
1270 goto error;
1271 }
1272
1273 /* Add metadata socket that is successfully connected. */
1274 ret = lttng_poll_add(&events, consumer_data->metadata_fd,
1275 LPOLLIN | LPOLLRDHUP);
1276 if (ret < 0) {
1277 goto error;
1278 }
1279
1280 health_code_update();
1281
1282 /*
1283 * Transfer the write-end of the channel monitoring and rotate pipe
1284 * to the consumer by issuing a SET_CHANNEL_MONITOR_PIPE and
1285 * SET_CHANNEL_ROTATE_PIPE commands.
1286 */
1287 cmd_socket_wrapper = consumer_allocate_socket(&consumer_data->cmd_sock);
1288 if (!cmd_socket_wrapper) {
1289 goto error;
1290 }
1291 cmd_socket_wrapper->lock = &consumer_data->lock;
1292
1293 ret = consumer_send_channel_monitor_pipe(cmd_socket_wrapper,
1294 consumer_data->channel_monitor_pipe);
1295 if (ret) {
1296 goto error;
1297 }
1298
1299 ret = consumer_send_channel_rotate_pipe(cmd_socket_wrapper,
1300 consumer_data->channel_rotate_pipe);
1301 if (ret) {
1302 goto error;
1303 }
1304
1305 /* Discard the socket wrapper as it is no longer needed. */
1306 consumer_destroy_socket(cmd_socket_wrapper);
1307 cmd_socket_wrapper = NULL;
1308
1309 /* The thread is completely initialized, signal that it is ready. */
1310 signal_consumer_condition(consumer_data, 1);
1311
1312 /* Infinite blocking call, waiting for transmission */
1313 restart_poll:
1314 while (1) {
1315 health_code_update();
1316
1317 /* Exit the thread because the thread quit pipe has been triggered. */
1318 if (should_quit) {
1319 /* Not a health error. */
1320 err = 0;
1321 goto exit;
1322 }
1323
1324 health_poll_entry();
1325 ret = lttng_poll_wait(&events, -1);
1326 health_poll_exit();
1327 if (ret < 0) {
1328 /*
1329 * Restart interrupted system call.
1330 */
1331 if (errno == EINTR) {
1332 goto restart_poll;
1333 }
1334 goto error;
1335 }
1336
1337 nb_fd = ret;
1338
1339 for (i = 0; i < nb_fd; i++) {
1340 /* Fetch once the poll data */
1341 revents = LTTNG_POLL_GETEV(&events, i);
1342 pollfd = LTTNG_POLL_GETFD(&events, i);
1343
1344 health_code_update();
1345
1346 if (!revents) {
1347 /* No activity for this FD (poll implementation). */
1348 continue;
1349 }
1350
1351 /*
1352 * Thread quit pipe has been triggered, flag that we should stop
1353 * but continue the current loop to handle potential data from
1354 * consumer.
1355 */
1356 should_quit = sessiond_check_thread_quit_pipe(pollfd, revents);
1357
1358 if (pollfd == sock) {
1359 /* Event on the consumerd socket */
1360 if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)
1361 && !(revents & LPOLLIN)) {
1362 ERR("consumer err socket second poll error");
1363 goto error;
1364 }
1365 health_code_update();
1366 /* Wait for any kconsumerd error */
1367 ret = lttcomm_recv_unix_sock(sock, &code,
1368 sizeof(enum lttcomm_return_code));
1369 if (ret <= 0) {
1370 ERR("consumer closed the command socket");
1371 goto error;
1372 }
1373
1374 ERR("consumer return code : %s",
1375 lttcomm_get_readable_code(-code));
1376
1377 goto exit;
1378 } else if (pollfd == consumer_data->metadata_fd) {
1379 if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)
1380 && !(revents & LPOLLIN)) {
1381 ERR("consumer err metadata socket second poll error");
1382 goto error;
1383 }
1384 /* UST metadata requests */
1385 ret = ust_consumer_metadata_request(
1386 &consumer_data->metadata_sock);
1387 if (ret < 0) {
1388 ERR("Handling metadata request");
1389 goto error;
1390 }
1391 }
1392 /* No need for an else branch all FDs are tested prior. */
1393 }
1394 health_code_update();
1395 }
1396
1397 exit:
1398 error:
1399 /*
1400 * We lock here because we are about to close the sockets and some other
1401 * thread might be using them so get exclusive access which will abort all
1402 * other consumer command by other threads.
1403 */
1404 pthread_mutex_lock(&consumer_data->lock);
1405
1406 /* Immediately set the consumerd state to stopped */
1407 if (consumer_data->type == LTTNG_CONSUMER_KERNEL) {
1408 uatomic_set(&kernel_consumerd_state, CONSUMER_ERROR);
1409 } else if (consumer_data->type == LTTNG_CONSUMER64_UST ||
1410 consumer_data->type == LTTNG_CONSUMER32_UST) {
1411 uatomic_set(&ust_consumerd_state, CONSUMER_ERROR);
1412 } else {
1413 /* Code flow error... */
1414 assert(0);
1415 }
1416
1417 if (consumer_data->err_sock >= 0) {
1418 ret = close(consumer_data->err_sock);
1419 if (ret) {
1420 PERROR("close");
1421 }
1422 consumer_data->err_sock = -1;
1423 }
1424 if (consumer_data->cmd_sock >= 0) {
1425 ret = close(consumer_data->cmd_sock);
1426 if (ret) {
1427 PERROR("close");
1428 }
1429 consumer_data->cmd_sock = -1;
1430 }
1431 if (consumer_data->metadata_sock.fd_ptr &&
1432 *consumer_data->metadata_sock.fd_ptr >= 0) {
1433 ret = close(*consumer_data->metadata_sock.fd_ptr);
1434 if (ret) {
1435 PERROR("close");
1436 }
1437 }
1438 if (sock >= 0) {
1439 ret = close(sock);
1440 if (ret) {
1441 PERROR("close");
1442 }
1443 }
1444
1445 unlink(consumer_data->err_unix_sock_path);
1446 unlink(consumer_data->cmd_unix_sock_path);
1447 pthread_mutex_unlock(&consumer_data->lock);
1448
1449 /* Cleanup metadata socket mutex. */
1450 if (consumer_data->metadata_sock.lock) {
1451 pthread_mutex_destroy(consumer_data->metadata_sock.lock);
1452 free(consumer_data->metadata_sock.lock);
1453 }
1454 lttng_poll_clean(&events);
1455
1456 if (cmd_socket_wrapper) {
1457 consumer_destroy_socket(cmd_socket_wrapper);
1458 }
1459 error_poll:
1460 if (err) {
1461 health_error();
1462 ERR("Health error occurred in %s", __func__);
1463 }
1464 health_unregister(health_sessiond);
1465 DBG("consumer thread cleanup completed");
1466
1467 rcu_thread_offline();
1468 rcu_unregister_thread();
1469
1470 return NULL;
1471 }
1472
1473 /*
1474 * This thread receives application command sockets (FDs) on the
1475 * apps_cmd_pipe and waits (polls) on them until they are closed
1476 * or an error occurs.
1477 *
1478 * At that point, it flushes the data (tracing and metadata) associated
1479 * with this application and tears down ust app sessions and other
1480 * associated data structures through ust_app_unregister().
1481 *
1482 * Note that this thread never sends commands to the applications
1483 * through the command sockets; it merely listens for hang-ups
1484 * and errors on those sockets and cleans-up as they occur.
1485 */
1486 static void *thread_manage_apps(void *data)
1487 {
1488 int i, ret, pollfd, err = -1;
1489 ssize_t size_ret;
1490 uint32_t revents, nb_fd;
1491 struct lttng_poll_event events;
1492
1493 DBG("[thread] Manage application started");
1494
1495 rcu_register_thread();
1496 rcu_thread_online();
1497
1498 health_register(health_sessiond, HEALTH_SESSIOND_TYPE_APP_MANAGE);
1499
1500 if (testpoint(sessiond_thread_manage_apps)) {
1501 goto error_testpoint;
1502 }
1503
1504 health_code_update();
1505
1506 ret = sessiond_set_thread_pollset(&events, 2);
1507 if (ret < 0) {
1508 goto error_poll_create;
1509 }
1510
1511 ret = lttng_poll_add(&events, apps_cmd_pipe[0], LPOLLIN | LPOLLRDHUP);
1512 if (ret < 0) {
1513 goto error;
1514 }
1515
1516 if (testpoint(sessiond_thread_manage_apps_before_loop)) {
1517 goto error;
1518 }
1519
1520 health_code_update();
1521
1522 while (1) {
1523 DBG("Apps thread polling");
1524
1525 /* Inifinite blocking call, waiting for transmission */
1526 restart:
1527 health_poll_entry();
1528 ret = lttng_poll_wait(&events, -1);
1529 DBG("Apps thread return from poll on %d fds",
1530 LTTNG_POLL_GETNB(&events));
1531 health_poll_exit();
1532 if (ret < 0) {
1533 /*
1534 * Restart interrupted system call.
1535 */
1536 if (errno == EINTR) {
1537 goto restart;
1538 }
1539 goto error;
1540 }
1541
1542 nb_fd = ret;
1543
1544 for (i = 0; i < nb_fd; i++) {
1545 /* Fetch once the poll data */
1546 revents = LTTNG_POLL_GETEV(&events, i);
1547 pollfd = LTTNG_POLL_GETFD(&events, i);
1548
1549 health_code_update();
1550
1551 if (!revents) {
1552 /* No activity for this FD (poll implementation). */
1553 continue;
1554 }
1555
1556 /* Thread quit pipe has been closed. Killing thread. */
1557 ret = sessiond_check_thread_quit_pipe(pollfd, revents);
1558 if (ret) {
1559 err = 0;
1560 goto exit;
1561 }
1562
1563 /* Inspect the apps cmd pipe */
1564 if (pollfd == apps_cmd_pipe[0]) {
1565 if (revents & LPOLLIN) {
1566 int sock;
1567
1568 /* Empty pipe */
1569 size_ret = lttng_read(apps_cmd_pipe[0], &sock, sizeof(sock));
1570 if (size_ret < sizeof(sock)) {
1571 PERROR("read apps cmd pipe");
1572 goto error;
1573 }
1574
1575 health_code_update();
1576
1577 /*
1578 * Since this is a command socket (write then read),
1579 * we only monitor the error events of the socket.
1580 */
1581 ret = lttng_poll_add(&events, sock,
1582 LPOLLERR | LPOLLHUP | LPOLLRDHUP);
1583 if (ret < 0) {
1584 goto error;
1585 }
1586
1587 DBG("Apps with sock %d added to poll set", sock);
1588 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
1589 ERR("Apps command pipe error");
1590 goto error;
1591 } else {
1592 ERR("Unknown poll events %u for sock %d", revents, pollfd);
1593 goto error;
1594 }
1595 } else {
1596 /*
1597 * At this point, we know that a registered application made
1598 * the event at poll_wait.
1599 */
1600 if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
1601 /* Removing from the poll set */
1602 ret = lttng_poll_del(&events, pollfd);
1603 if (ret < 0) {
1604 goto error;
1605 }
1606
1607 /* Socket closed on remote end. */
1608 ust_app_unregister(pollfd);
1609 } else {
1610 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
1611 goto error;
1612 }
1613 }
1614
1615 health_code_update();
1616 }
1617 }
1618
1619 exit:
1620 error:
1621 lttng_poll_clean(&events);
1622 error_poll_create:
1623 error_testpoint:
1624 utils_close_pipe(apps_cmd_pipe);
1625 apps_cmd_pipe[0] = apps_cmd_pipe[1] = -1;
1626
1627 /*
1628 * We don't clean the UST app hash table here since already registered
1629 * applications can still be controlled so let them be until the session
1630 * daemon dies or the applications stop.
1631 */
1632
1633 if (err) {
1634 health_error();
1635 ERR("Health error occurred in %s", __func__);
1636 }
1637 health_unregister(health_sessiond);
1638 DBG("Application communication apps thread cleanup complete");
1639 rcu_thread_offline();
1640 rcu_unregister_thread();
1641 return NULL;
1642 }
1643
1644 /*
1645 * Send a socket to a thread This is called from the dispatch UST registration
1646 * thread once all sockets are set for the application.
1647 *
1648 * The sock value can be invalid, we don't really care, the thread will handle
1649 * it and make the necessary cleanup if so.
1650 *
1651 * On success, return 0 else a negative value being the errno message of the
1652 * write().
1653 */
1654 static int send_socket_to_thread(int fd, int sock)
1655 {
1656 ssize_t ret;
1657
1658 /*
1659 * It's possible that the FD is set as invalid with -1 concurrently just
1660 * before calling this function being a shutdown state of the thread.
1661 */
1662 if (fd < 0) {
1663 ret = -EBADF;
1664 goto error;
1665 }
1666
1667 ret = lttng_write(fd, &sock, sizeof(sock));
1668 if (ret < sizeof(sock)) {
1669 PERROR("write apps pipe %d", fd);
1670 if (ret < 0) {
1671 ret = -errno;
1672 }
1673 goto error;
1674 }
1675
1676 /* All good. Don't send back the write positive ret value. */
1677 ret = 0;
1678 error:
1679 return (int) ret;
1680 }
1681
1682 /*
1683 * Sanitize the wait queue of the dispatch registration thread meaning removing
1684 * invalid nodes from it. This is to avoid memory leaks for the case the UST
1685 * notify socket is never received.
1686 */
1687 static void sanitize_wait_queue(struct ust_reg_wait_queue *wait_queue)
1688 {
1689 int ret, nb_fd = 0, i;
1690 unsigned int fd_added = 0;
1691 struct lttng_poll_event events;
1692 struct ust_reg_wait_node *wait_node = NULL, *tmp_wait_node;
1693
1694 assert(wait_queue);
1695
1696 lttng_poll_init(&events);
1697
1698 /* Just skip everything for an empty queue. */
1699 if (!wait_queue->count) {
1700 goto end;
1701 }
1702
1703 ret = lttng_poll_create(&events, wait_queue->count, LTTNG_CLOEXEC);
1704 if (ret < 0) {
1705 goto error_create;
1706 }
1707
1708 cds_list_for_each_entry_safe(wait_node, tmp_wait_node,
1709 &wait_queue->head, head) {
1710 assert(wait_node->app);
1711 ret = lttng_poll_add(&events, wait_node->app->sock,
1712 LPOLLHUP | LPOLLERR);
1713 if (ret < 0) {
1714 goto error;
1715 }
1716
1717 fd_added = 1;
1718 }
1719
1720 if (!fd_added) {
1721 goto end;
1722 }
1723
1724 /*
1725 * Poll but don't block so we can quickly identify the faulty events and
1726 * clean them afterwards from the wait queue.
1727 */
1728 ret = lttng_poll_wait(&events, 0);
1729 if (ret < 0) {
1730 goto error;
1731 }
1732 nb_fd = ret;
1733
1734 for (i = 0; i < nb_fd; i++) {
1735 /* Get faulty FD. */
1736 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
1737 int pollfd = LTTNG_POLL_GETFD(&events, i);
1738
1739 if (!revents) {
1740 /* No activity for this FD (poll implementation). */
1741 continue;
1742 }
1743
1744 cds_list_for_each_entry_safe(wait_node, tmp_wait_node,
1745 &wait_queue->head, head) {
1746 if (pollfd == wait_node->app->sock &&
1747 (revents & (LPOLLHUP | LPOLLERR))) {
1748 cds_list_del(&wait_node->head);
1749 wait_queue->count--;
1750 ust_app_destroy(wait_node->app);
1751 free(wait_node);
1752 /*
1753 * Silence warning of use-after-free in
1754 * cds_list_for_each_entry_safe which uses
1755 * __typeof__(*wait_node).
1756 */
1757 wait_node = NULL;
1758 break;
1759 } else {
1760 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
1761 goto error;
1762 }
1763 }
1764 }
1765
1766 if (nb_fd > 0) {
1767 DBG("Wait queue sanitized, %d node were cleaned up", nb_fd);
1768 }
1769
1770 end:
1771 lttng_poll_clean(&events);
1772 return;
1773
1774 error:
1775 lttng_poll_clean(&events);
1776 error_create:
1777 ERR("Unable to sanitize wait queue");
1778 return;
1779 }
1780
1781 /*
1782 * Dispatch request from the registration threads to the application
1783 * communication thread.
1784 */
1785 static void *thread_dispatch_ust_registration(void *data)
1786 {
1787 int ret, err = -1;
1788 struct cds_wfcq_node *node;
1789 struct ust_command *ust_cmd = NULL;
1790 struct ust_reg_wait_node *wait_node = NULL, *tmp_wait_node;
1791 struct ust_reg_wait_queue wait_queue = {
1792 .count = 0,
1793 };
1794
1795 rcu_register_thread();
1796
1797 health_register(health_sessiond, HEALTH_SESSIOND_TYPE_APP_REG_DISPATCH);
1798
1799 if (testpoint(sessiond_thread_app_reg_dispatch)) {
1800 goto error_testpoint;
1801 }
1802
1803 health_code_update();
1804
1805 CDS_INIT_LIST_HEAD(&wait_queue.head);
1806
1807 DBG("[thread] Dispatch UST command started");
1808
1809 for (;;) {
1810 health_code_update();
1811
1812 /* Atomically prepare the queue futex */
1813 futex_nto1_prepare(&ust_cmd_queue.futex);
1814
1815 if (CMM_LOAD_SHARED(dispatch_thread_exit)) {
1816 break;
1817 }
1818
1819 do {
1820 struct ust_app *app = NULL;
1821 ust_cmd = NULL;
1822
1823 /*
1824 * Make sure we don't have node(s) that have hung up before receiving
1825 * the notify socket. This is to clean the list in order to avoid
1826 * memory leaks from notify socket that are never seen.
1827 */
1828 sanitize_wait_queue(&wait_queue);
1829
1830 health_code_update();
1831 /* Dequeue command for registration */
1832 node = cds_wfcq_dequeue_blocking(&ust_cmd_queue.head, &ust_cmd_queue.tail);
1833 if (node == NULL) {
1834 DBG("Woken up but nothing in the UST command queue");
1835 /* Continue thread execution */
1836 break;
1837 }
1838
1839 ust_cmd = caa_container_of(node, struct ust_command, node);
1840
1841 DBG("Dispatching UST registration pid:%d ppid:%d uid:%d"
1842 " gid:%d sock:%d name:%s (version %d.%d)",
1843 ust_cmd->reg_msg.pid, ust_cmd->reg_msg.ppid,
1844 ust_cmd->reg_msg.uid, ust_cmd->reg_msg.gid,
1845 ust_cmd->sock, ust_cmd->reg_msg.name,
1846 ust_cmd->reg_msg.major, ust_cmd->reg_msg.minor);
1847
1848 if (ust_cmd->reg_msg.type == USTCTL_SOCKET_CMD) {
1849 wait_node = zmalloc(sizeof(*wait_node));
1850 if (!wait_node) {
1851 PERROR("zmalloc wait_node dispatch");
1852 ret = close(ust_cmd->sock);
1853 if (ret < 0) {
1854 PERROR("close ust sock dispatch %d", ust_cmd->sock);
1855 }
1856 lttng_fd_put(LTTNG_FD_APPS, 1);
1857 free(ust_cmd);
1858 goto error;
1859 }
1860 CDS_INIT_LIST_HEAD(&wait_node->head);
1861
1862 /* Create application object if socket is CMD. */
1863 wait_node->app = ust_app_create(&ust_cmd->reg_msg,
1864 ust_cmd->sock);
1865 if (!wait_node->app) {
1866 ret = close(ust_cmd->sock);
1867 if (ret < 0) {
1868 PERROR("close ust sock dispatch %d", ust_cmd->sock);
1869 }
1870 lttng_fd_put(LTTNG_FD_APPS, 1);
1871 free(wait_node);
1872 free(ust_cmd);
1873 continue;
1874 }
1875 /*
1876 * Add application to the wait queue so we can set the notify
1877 * socket before putting this object in the global ht.
1878 */
1879 cds_list_add(&wait_node->head, &wait_queue.head);
1880 wait_queue.count++;
1881
1882 free(ust_cmd);
1883 /*
1884 * We have to continue here since we don't have the notify
1885 * socket and the application MUST be added to the hash table
1886 * only at that moment.
1887 */
1888 continue;
1889 } else {
1890 /*
1891 * Look for the application in the local wait queue and set the
1892 * notify socket if found.
1893 */
1894 cds_list_for_each_entry_safe(wait_node, tmp_wait_node,
1895 &wait_queue.head, head) {
1896 health_code_update();
1897 if (wait_node->app->pid == ust_cmd->reg_msg.pid) {
1898 wait_node->app->notify_sock = ust_cmd->sock;
1899 cds_list_del(&wait_node->head);
1900 wait_queue.count--;
1901 app = wait_node->app;
1902 free(wait_node);
1903 DBG3("UST app notify socket %d is set", ust_cmd->sock);
1904 break;
1905 }
1906 }
1907
1908 /*
1909 * With no application at this stage the received socket is
1910 * basically useless so close it before we free the cmd data
1911 * structure for good.
1912 */
1913 if (!app) {
1914 ret = close(ust_cmd->sock);
1915 if (ret < 0) {
1916 PERROR("close ust sock dispatch %d", ust_cmd->sock);
1917 }
1918 lttng_fd_put(LTTNG_FD_APPS, 1);
1919 }
1920 free(ust_cmd);
1921 }
1922
1923 if (app) {
1924 /*
1925 * @session_lock_list
1926 *
1927 * Lock the global session list so from the register up to the
1928 * registration done message, no thread can see the application
1929 * and change its state.
1930 */
1931 session_lock_list();
1932 rcu_read_lock();
1933
1934 /*
1935 * Add application to the global hash table. This needs to be
1936 * done before the update to the UST registry can locate the
1937 * application.
1938 */
1939 ust_app_add(app);
1940
1941 /* Set app version. This call will print an error if needed. */
1942 (void) ust_app_version(app);
1943
1944 /* Send notify socket through the notify pipe. */
1945 ret = send_socket_to_thread(apps_cmd_notify_pipe[1],
1946 app->notify_sock);
1947 if (ret < 0) {
1948 rcu_read_unlock();
1949 session_unlock_list();
1950 /*
1951 * No notify thread, stop the UST tracing. However, this is
1952 * not an internal error of the this thread thus setting
1953 * the health error code to a normal exit.
1954 */
1955 err = 0;
1956 goto error;
1957 }
1958
1959 /*
1960 * Update newly registered application with the tracing
1961 * registry info already enabled information.
1962 */
1963 update_ust_app(app->sock);
1964
1965 /*
1966 * Don't care about return value. Let the manage apps threads
1967 * handle app unregistration upon socket close.
1968 */
1969 (void) ust_app_register_done(app);
1970
1971 /*
1972 * Even if the application socket has been closed, send the app
1973 * to the thread and unregistration will take place at that
1974 * place.
1975 */
1976 ret = send_socket_to_thread(apps_cmd_pipe[1], app->sock);
1977 if (ret < 0) {
1978 rcu_read_unlock();
1979 session_unlock_list();
1980 /*
1981 * No apps. thread, stop the UST tracing. However, this is
1982 * not an internal error of the this thread thus setting
1983 * the health error code to a normal exit.
1984 */
1985 err = 0;
1986 goto error;
1987 }
1988
1989 rcu_read_unlock();
1990 session_unlock_list();
1991 }
1992 } while (node != NULL);
1993
1994 health_poll_entry();
1995 /* Futex wait on queue. Blocking call on futex() */
1996 futex_nto1_wait(&ust_cmd_queue.futex);
1997 health_poll_exit();
1998 }
1999 /* Normal exit, no error */
2000 err = 0;
2001
2002 error:
2003 /* Clean up wait queue. */
2004 cds_list_for_each_entry_safe(wait_node, tmp_wait_node,
2005 &wait_queue.head, head) {
2006 cds_list_del(&wait_node->head);
2007 wait_queue.count--;
2008 free(wait_node);
2009 }
2010
2011 /* Empty command queue. */
2012 for (;;) {
2013 /* Dequeue command for registration */
2014 node = cds_wfcq_dequeue_blocking(&ust_cmd_queue.head, &ust_cmd_queue.tail);
2015 if (node == NULL) {
2016 break;
2017 }
2018 ust_cmd = caa_container_of(node, struct ust_command, node);
2019 ret = close(ust_cmd->sock);
2020 if (ret < 0) {
2021 PERROR("close ust sock exit dispatch %d", ust_cmd->sock);
2022 }
2023 lttng_fd_put(LTTNG_FD_APPS, 1);
2024 free(ust_cmd);
2025 }
2026
2027 error_testpoint:
2028 DBG("Dispatch thread dying");
2029 if (err) {
2030 health_error();
2031 ERR("Health error occurred in %s", __func__);
2032 }
2033 health_unregister(health_sessiond);
2034 rcu_unregister_thread();
2035 return NULL;
2036 }
2037
2038 /*
2039 * This thread manage application registration.
2040 */
2041 static void *thread_registration_apps(void *data)
2042 {
2043 int sock = -1, i, ret, pollfd, err = -1;
2044 uint32_t revents, nb_fd;
2045 struct lttng_poll_event events;
2046 /*
2047 * Get allocated in this thread, enqueued to a global queue, dequeued and
2048 * freed in the manage apps thread.
2049 */
2050 struct ust_command *ust_cmd = NULL;
2051
2052 DBG("[thread] Manage application registration started");
2053
2054 health_register(health_sessiond, HEALTH_SESSIOND_TYPE_APP_REG);
2055
2056 if (testpoint(sessiond_thread_registration_apps)) {
2057 goto error_testpoint;
2058 }
2059
2060 ret = lttcomm_listen_unix_sock(apps_sock);
2061 if (ret < 0) {
2062 goto error_listen;
2063 }
2064
2065 /*
2066 * Pass 2 as size here for the thread quit pipe and apps socket. Nothing
2067 * more will be added to this poll set.
2068 */
2069 ret = sessiond_set_thread_pollset(&events, 2);
2070 if (ret < 0) {
2071 goto error_create_poll;
2072 }
2073
2074 /* Add the application registration socket */
2075 ret = lttng_poll_add(&events, apps_sock, LPOLLIN | LPOLLRDHUP);
2076 if (ret < 0) {
2077 goto error_poll_add;
2078 }
2079
2080 /* Notify all applications to register */
2081 ret = notify_ust_apps(1);
2082 if (ret < 0) {
2083 ERR("Failed to notify applications or create the wait shared memory.\n"
2084 "Execution continues but there might be problem for already\n"
2085 "running applications that wishes to register.");
2086 }
2087
2088 while (1) {
2089 DBG("Accepting application registration");
2090
2091 /* Inifinite blocking call, waiting for transmission */
2092 restart:
2093 health_poll_entry();
2094 ret = lttng_poll_wait(&events, -1);
2095 health_poll_exit();
2096 if (ret < 0) {
2097 /*
2098 * Restart interrupted system call.
2099 */
2100 if (errno == EINTR) {
2101 goto restart;
2102 }
2103 goto error;
2104 }
2105
2106 nb_fd = ret;
2107
2108 for (i = 0; i < nb_fd; i++) {
2109 health_code_update();
2110
2111 /* Fetch once the poll data */
2112 revents = LTTNG_POLL_GETEV(&events, i);
2113 pollfd = LTTNG_POLL_GETFD(&events, i);
2114
2115 if (!revents) {
2116 /* No activity for this FD (poll implementation). */
2117 continue;
2118 }
2119
2120 /* Thread quit pipe has been closed. Killing thread. */
2121 ret = sessiond_check_thread_quit_pipe(pollfd, revents);
2122 if (ret) {
2123 err = 0;
2124 goto exit;
2125 }
2126
2127 /* Event on the registration socket */
2128 if (pollfd == apps_sock) {
2129 if (revents & LPOLLIN) {
2130 sock = lttcomm_accept_unix_sock(apps_sock);
2131 if (sock < 0) {
2132 goto error;
2133 }
2134
2135 /*
2136 * Set socket timeout for both receiving and ending.
2137 * app_socket_timeout is in seconds, whereas
2138 * lttcomm_setsockopt_rcv_timeout and
2139 * lttcomm_setsockopt_snd_timeout expect msec as
2140 * parameter.
2141 */
2142 if (config.app_socket_timeout >= 0) {
2143 (void) lttcomm_setsockopt_rcv_timeout(sock,
2144 config.app_socket_timeout * 1000);
2145 (void) lttcomm_setsockopt_snd_timeout(sock,
2146 config.app_socket_timeout * 1000);
2147 }
2148
2149 /*
2150 * Set the CLOEXEC flag. Return code is useless because
2151 * either way, the show must go on.
2152 */
2153 (void) utils_set_fd_cloexec(sock);
2154
2155 /* Create UST registration command for enqueuing */
2156 ust_cmd = zmalloc(sizeof(struct ust_command));
2157 if (ust_cmd == NULL) {
2158 PERROR("ust command zmalloc");
2159 ret = close(sock);
2160 if (ret) {
2161 PERROR("close");
2162 }
2163 goto error;
2164 }
2165
2166 /*
2167 * Using message-based transmissions to ensure we don't
2168 * have to deal with partially received messages.
2169 */
2170 ret = lttng_fd_get(LTTNG_FD_APPS, 1);
2171 if (ret < 0) {
2172 ERR("Exhausted file descriptors allowed for applications.");
2173 free(ust_cmd);
2174 ret = close(sock);
2175 if (ret) {
2176 PERROR("close");
2177 }
2178 sock = -1;
2179 continue;
2180 }
2181
2182 health_code_update();
2183 ret = ust_app_recv_registration(sock, &ust_cmd->reg_msg);
2184 if (ret < 0) {
2185 free(ust_cmd);
2186 /* Close socket of the application. */
2187 ret = close(sock);
2188 if (ret) {
2189 PERROR("close");
2190 }
2191 lttng_fd_put(LTTNG_FD_APPS, 1);
2192 sock = -1;
2193 continue;
2194 }
2195 health_code_update();
2196
2197 ust_cmd->sock = sock;
2198 sock = -1;
2199
2200 DBG("UST registration received with pid:%d ppid:%d uid:%d"
2201 " gid:%d sock:%d name:%s (version %d.%d)",
2202 ust_cmd->reg_msg.pid, ust_cmd->reg_msg.ppid,
2203 ust_cmd->reg_msg.uid, ust_cmd->reg_msg.gid,
2204 ust_cmd->sock, ust_cmd->reg_msg.name,
2205 ust_cmd->reg_msg.major, ust_cmd->reg_msg.minor);
2206
2207 /*
2208 * Lock free enqueue the registration request. The red pill
2209 * has been taken! This apps will be part of the *system*.
2210 */
2211 cds_wfcq_enqueue(&ust_cmd_queue.head, &ust_cmd_queue.tail, &ust_cmd->node);
2212
2213 /*
2214 * Wake the registration queue futex. Implicit memory
2215 * barrier with the exchange in cds_wfcq_enqueue.
2216 */
2217 futex_nto1_wake(&ust_cmd_queue.futex);
2218 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2219 ERR("Register apps socket poll error");
2220 goto error;
2221 } else {
2222 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
2223 goto error;
2224 }
2225 }
2226 }
2227 }
2228
2229 exit:
2230 error:
2231 /* Notify that the registration thread is gone */
2232 notify_ust_apps(0);
2233
2234 if (apps_sock >= 0) {
2235 ret = close(apps_sock);
2236 if (ret) {
2237 PERROR("close");
2238 }
2239 }
2240 if (sock >= 0) {
2241 ret = close(sock);
2242 if (ret) {
2243 PERROR("close");
2244 }
2245 lttng_fd_put(LTTNG_FD_APPS, 1);
2246 }
2247 unlink(config.apps_unix_sock_path.value);
2248
2249 error_poll_add:
2250 lttng_poll_clean(&events);
2251 error_listen:
2252 error_create_poll:
2253 error_testpoint:
2254 DBG("UST Registration thread cleanup complete");
2255 if (err) {
2256 health_error();
2257 ERR("Health error occurred in %s", __func__);
2258 }
2259 health_unregister(health_sessiond);
2260
2261 return NULL;
2262 }
2263
2264 /*
2265 * Start the thread_manage_consumer. This must be done after a lttng-consumerd
2266 * exec or it will fails.
2267 */
2268 static int spawn_consumer_thread(struct consumer_data *consumer_data)
2269 {
2270 int ret, clock_ret;
2271 struct timespec timeout;
2272
2273 /*
2274 * Make sure we set the readiness flag to 0 because we are NOT ready.
2275 * This access to consumer_thread_is_ready does not need to be
2276 * protected by consumer_data.cond_mutex (yet) since the consumer
2277 * management thread has not been started at this point.
2278 */
2279 consumer_data->consumer_thread_is_ready = 0;
2280
2281 /* Setup pthread condition */
2282 ret = pthread_condattr_init(&consumer_data->condattr);
2283 if (ret) {
2284 errno = ret;
2285 PERROR("pthread_condattr_init consumer data");
2286 goto error;
2287 }
2288
2289 /*
2290 * Set the monotonic clock in order to make sure we DO NOT jump in time
2291 * between the clock_gettime() call and the timedwait call. See bug #324
2292 * for a more details and how we noticed it.
2293 */
2294 ret = pthread_condattr_setclock(&consumer_data->condattr, CLOCK_MONOTONIC);
2295 if (ret) {
2296 errno = ret;
2297 PERROR("pthread_condattr_setclock consumer data");
2298 goto error;
2299 }
2300
2301 ret = pthread_cond_init(&consumer_data->cond, &consumer_data->condattr);
2302 if (ret) {
2303 errno = ret;
2304 PERROR("pthread_cond_init consumer data");
2305 goto error;
2306 }
2307
2308 ret = pthread_create(&consumer_data->thread, default_pthread_attr(),
2309 thread_manage_consumer, consumer_data);
2310 if (ret) {
2311 errno = ret;
2312 PERROR("pthread_create consumer");
2313 ret = -1;
2314 goto error;
2315 }
2316
2317 /* We are about to wait on a pthread condition */
2318 pthread_mutex_lock(&consumer_data->cond_mutex);
2319
2320 /* Get time for sem_timedwait absolute timeout */
2321 clock_ret = lttng_clock_gettime(CLOCK_MONOTONIC, &timeout);
2322 /*
2323 * Set the timeout for the condition timed wait even if the clock gettime
2324 * call fails since we might loop on that call and we want to avoid to
2325 * increment the timeout too many times.
2326 */
2327 timeout.tv_sec += DEFAULT_SEM_WAIT_TIMEOUT;
2328
2329 /*
2330 * The following loop COULD be skipped in some conditions so this is why we
2331 * set ret to 0 in order to make sure at least one round of the loop is
2332 * done.
2333 */
2334 ret = 0;
2335
2336 /*
2337 * Loop until the condition is reached or when a timeout is reached. Note
2338 * that the pthread_cond_timedwait(P) man page specifies that EINTR can NOT
2339 * be returned but the pthread_cond(3), from the glibc-doc, says that it is
2340 * possible. This loop does not take any chances and works with both of
2341 * them.
2342 */
2343 while (!consumer_data->consumer_thread_is_ready && ret != ETIMEDOUT) {
2344 if (clock_ret < 0) {
2345 PERROR("clock_gettime spawn consumer");
2346 /* Infinite wait for the consumerd thread to be ready */
2347 ret = pthread_cond_wait(&consumer_data->cond,
2348 &consumer_data->cond_mutex);
2349 } else {
2350 ret = pthread_cond_timedwait(&consumer_data->cond,
2351 &consumer_data->cond_mutex, &timeout);
2352 }
2353 }
2354
2355 /* Release the pthread condition */
2356 pthread_mutex_unlock(&consumer_data->cond_mutex);
2357
2358 if (ret != 0) {
2359 errno = ret;
2360 if (ret == ETIMEDOUT) {
2361 int pth_ret;
2362
2363 /*
2364 * Call has timed out so we kill the kconsumerd_thread and return
2365 * an error.
2366 */
2367 ERR("Condition timed out. The consumer thread was never ready."
2368 " Killing it");
2369 pth_ret = pthread_cancel(consumer_data->thread);
2370 if (pth_ret < 0) {
2371 PERROR("pthread_cancel consumer thread");
2372 }
2373 } else {
2374 PERROR("pthread_cond_wait failed consumer thread");
2375 }
2376 /* Caller is expecting a negative value on failure. */
2377 ret = -1;
2378 goto error;
2379 }
2380
2381 pthread_mutex_lock(&consumer_data->pid_mutex);
2382 if (consumer_data->pid == 0) {
2383 ERR("Consumerd did not start");
2384 pthread_mutex_unlock(&consumer_data->pid_mutex);
2385 goto error;
2386 }
2387 pthread_mutex_unlock(&consumer_data->pid_mutex);
2388
2389 return 0;
2390
2391 error:
2392 return ret;
2393 }
2394
2395 /*
2396 * Join consumer thread
2397 */
2398 static int join_consumer_thread(struct consumer_data *consumer_data)
2399 {
2400 void *status;
2401
2402 /* Consumer pid must be a real one. */
2403 if (consumer_data->pid > 0) {
2404 int ret;
2405 ret = kill(consumer_data->pid, SIGTERM);
2406 if (ret) {
2407 PERROR("Error killing consumer daemon");
2408 return ret;
2409 }
2410 return pthread_join(consumer_data->thread, &status);
2411 } else {
2412 return 0;
2413 }
2414 }
2415
2416 /*
2417 * Fork and exec a consumer daemon (consumerd).
2418 *
2419 * Return pid if successful else -1.
2420 */
2421 static pid_t spawn_consumerd(struct consumer_data *consumer_data)
2422 {
2423 int ret;
2424 pid_t pid;
2425 const char *consumer_to_use;
2426 const char *verbosity;
2427 struct stat st;
2428
2429 DBG("Spawning consumerd");
2430
2431 pid = fork();
2432 if (pid == 0) {
2433 /*
2434 * Exec consumerd.
2435 */
2436 if (config.verbose_consumer) {
2437 verbosity = "--verbose";
2438 } else if (lttng_opt_quiet) {
2439 verbosity = "--quiet";
2440 } else {
2441 verbosity = "";
2442 }
2443
2444 switch (consumer_data->type) {
2445 case LTTNG_CONSUMER_KERNEL:
2446 /*
2447 * Find out which consumerd to execute. We will first try the
2448 * 64-bit path, then the sessiond's installation directory, and
2449 * fallback on the 32-bit one,
2450 */
2451 DBG3("Looking for a kernel consumer at these locations:");
2452 DBG3(" 1) %s", config.consumerd64_bin_path.value ? : "NULL");
2453 DBG3(" 2) %s/%s", INSTALL_BIN_PATH, DEFAULT_CONSUMERD_FILE);
2454 DBG3(" 3) %s", config.consumerd32_bin_path.value ? : "NULL");
2455 if (stat(config.consumerd64_bin_path.value, &st) == 0) {
2456 DBG3("Found location #1");
2457 consumer_to_use = config.consumerd64_bin_path.value;
2458 } else if (stat(INSTALL_BIN_PATH "/" DEFAULT_CONSUMERD_FILE, &st) == 0) {
2459 DBG3("Found location #2");
2460 consumer_to_use = INSTALL_BIN_PATH "/" DEFAULT_CONSUMERD_FILE;
2461 } else if (stat(config.consumerd32_bin_path.value, &st) == 0) {
2462 DBG3("Found location #3");
2463 consumer_to_use = config.consumerd32_bin_path.value;
2464 } else {
2465 DBG("Could not find any valid consumerd executable");
2466 ret = -EINVAL;
2467 goto error;
2468 }
2469 DBG("Using kernel consumer at: %s", consumer_to_use);
2470 (void) execl(consumer_to_use,
2471 "lttng-consumerd", verbosity, "-k",
2472 "--consumerd-cmd-sock", consumer_data->cmd_unix_sock_path,
2473 "--consumerd-err-sock", consumer_data->err_unix_sock_path,
2474 "--group", config.tracing_group_name.value,
2475 NULL);
2476 break;
2477 case LTTNG_CONSUMER64_UST:
2478 {
2479 if (config.consumerd64_lib_dir.value) {
2480 char *tmp;
2481 size_t tmplen;
2482 char *tmpnew;
2483
2484 tmp = lttng_secure_getenv("LD_LIBRARY_PATH");
2485 if (!tmp) {
2486 tmp = "";
2487 }
2488 tmplen = strlen(config.consumerd64_lib_dir.value) + 1 /* : */ + strlen(tmp);
2489 tmpnew = zmalloc(tmplen + 1 /* \0 */);
2490 if (!tmpnew) {
2491 ret = -ENOMEM;
2492 goto error;
2493 }
2494 strcat(tmpnew, config.consumerd64_lib_dir.value);
2495 if (tmp[0] != '\0') {
2496 strcat(tmpnew, ":");
2497 strcat(tmpnew, tmp);
2498 }
2499 ret = setenv("LD_LIBRARY_PATH", tmpnew, 1);
2500 free(tmpnew);
2501 if (ret) {
2502 ret = -errno;
2503 goto error;
2504 }
2505 }
2506 DBG("Using 64-bit UST consumer at: %s", config.consumerd64_bin_path.value);
2507 (void) execl(config.consumerd64_bin_path.value, "lttng-consumerd", verbosity, "-u",
2508 "--consumerd-cmd-sock", consumer_data->cmd_unix_sock_path,
2509 "--consumerd-err-sock", consumer_data->err_unix_sock_path,
2510 "--group", config.tracing_group_name.value,
2511 NULL);
2512 break;
2513 }
2514 case LTTNG_CONSUMER32_UST:
2515 {
2516 if (config.consumerd32_lib_dir.value) {
2517 char *tmp;
2518 size_t tmplen;
2519 char *tmpnew;
2520
2521 tmp = lttng_secure_getenv("LD_LIBRARY_PATH");
2522 if (!tmp) {
2523 tmp = "";
2524 }
2525 tmplen = strlen(config.consumerd32_lib_dir.value) + 1 /* : */ + strlen(tmp);
2526 tmpnew = zmalloc(tmplen + 1 /* \0 */);
2527 if (!tmpnew) {
2528 ret = -ENOMEM;
2529 goto error;
2530 }
2531 strcat(tmpnew, config.consumerd32_lib_dir.value);
2532 if (tmp[0] != '\0') {
2533 strcat(tmpnew, ":");
2534 strcat(tmpnew, tmp);
2535 }
2536 ret = setenv("LD_LIBRARY_PATH", tmpnew, 1);
2537 free(tmpnew);
2538 if (ret) {
2539 ret = -errno;
2540 goto error;
2541 }
2542 }
2543 DBG("Using 32-bit UST consumer at: %s", config.consumerd32_bin_path.value);
2544 (void) execl(config.consumerd32_bin_path.value, "lttng-consumerd", verbosity, "-u",
2545 "--consumerd-cmd-sock", consumer_data->cmd_unix_sock_path,
2546 "--consumerd-err-sock", consumer_data->err_unix_sock_path,
2547 "--group", config.tracing_group_name.value,
2548 NULL);
2549 break;
2550 }
2551 default:
2552 ERR("unknown consumer type");
2553 errno = 0;
2554 }
2555 if (errno != 0) {
2556 PERROR("Consumer execl()");
2557 }
2558 /* Reaching this point, we got a failure on our execl(). */
2559 exit(EXIT_FAILURE);
2560 } else if (pid > 0) {
2561 ret = pid;
2562 } else {
2563 PERROR("start consumer fork");
2564 ret = -errno;
2565 }
2566 error:
2567 return ret;
2568 }
2569
2570 /*
2571 * Spawn the consumerd daemon and session daemon thread.
2572 */
2573 static int start_consumerd(struct consumer_data *consumer_data)
2574 {
2575 int ret;
2576
2577 /*
2578 * Set the listen() state on the socket since there is a possible race
2579 * between the exec() of the consumer daemon and this call if place in the
2580 * consumer thread. See bug #366 for more details.
2581 */
2582 ret = lttcomm_listen_unix_sock(consumer_data->err_sock);
2583 if (ret < 0) {
2584 goto error;
2585 }
2586
2587 pthread_mutex_lock(&consumer_data->pid_mutex);
2588 if (consumer_data->pid != 0) {
2589 pthread_mutex_unlock(&consumer_data->pid_mutex);
2590 goto end;
2591 }
2592
2593 ret = spawn_consumerd(consumer_data);
2594 if (ret < 0) {
2595 ERR("Spawning consumerd failed");
2596 pthread_mutex_unlock(&consumer_data->pid_mutex);
2597 goto error;
2598 }
2599
2600 /* Setting up the consumer_data pid */
2601 consumer_data->pid = ret;
2602 DBG2("Consumer pid %d", consumer_data->pid);
2603 pthread_mutex_unlock(&consumer_data->pid_mutex);
2604
2605 DBG2("Spawning consumer control thread");
2606 ret = spawn_consumer_thread(consumer_data);
2607 if (ret < 0) {
2608 ERR("Fatal error spawning consumer control thread");
2609 goto error;
2610 }
2611
2612 end:
2613 return 0;
2614
2615 error:
2616 /* Cleanup already created sockets on error. */
2617 if (consumer_data->err_sock >= 0) {
2618 int err;
2619
2620 err = close(consumer_data->err_sock);
2621 if (err < 0) {
2622 PERROR("close consumer data error socket");
2623 }
2624 }
2625 return ret;
2626 }
2627
2628 /*
2629 * Setup necessary data for kernel tracer action.
2630 */
2631 static int init_kernel_tracer(void)
2632 {
2633 int ret;
2634
2635 /* Modprobe lttng kernel modules */
2636 ret = modprobe_lttng_control();
2637 if (ret < 0) {
2638 goto error;
2639 }
2640
2641 /* Open debugfs lttng */
2642 kernel_tracer_fd = open(module_proc_lttng, O_RDWR);
2643 if (kernel_tracer_fd < 0) {
2644 DBG("Failed to open %s", module_proc_lttng);
2645 goto error_open;
2646 }
2647
2648 /* Validate kernel version */
2649 ret = kernel_validate_version(kernel_tracer_fd, &kernel_tracer_version,
2650 &kernel_tracer_abi_version);
2651 if (ret < 0) {
2652 goto error_version;
2653 }
2654
2655 ret = modprobe_lttng_data();
2656 if (ret < 0) {
2657 goto error_modules;
2658 }
2659
2660 ret = kernel_supports_ring_buffer_snapshot_sample_positions(
2661 kernel_tracer_fd);
2662 if (ret < 0) {
2663 goto error_modules;
2664 }
2665
2666 if (ret < 1) {
2667 WARN("Kernel tracer does not support buffer monitoring. "
2668 "The monitoring timer of channels in the kernel domain "
2669 "will be set to 0 (disabled).");
2670 }
2671
2672 DBG("Kernel tracer fd %d", kernel_tracer_fd);
2673 return 0;
2674
2675 error_version:
2676 modprobe_remove_lttng_control();
2677 ret = close(kernel_tracer_fd);
2678 if (ret) {
2679 PERROR("close");
2680 }
2681 kernel_tracer_fd = -1;
2682 return LTTNG_ERR_KERN_VERSION;
2683
2684 error_modules:
2685 ret = close(kernel_tracer_fd);
2686 if (ret) {
2687 PERROR("close");
2688 }
2689
2690 error_open:
2691 modprobe_remove_lttng_control();
2692
2693 error:
2694 WARN("No kernel tracer available");
2695 kernel_tracer_fd = -1;
2696 if (!is_root) {
2697 return LTTNG_ERR_NEED_ROOT_SESSIOND;
2698 } else {
2699 return LTTNG_ERR_KERN_NA;
2700 }
2701 }
2702
2703
2704 /*
2705 * Copy consumer output from the tracing session to the domain session. The
2706 * function also applies the right modification on a per domain basis for the
2707 * trace files destination directory.
2708 *
2709 * Should *NOT* be called with RCU read-side lock held.
2710 */
2711 static int copy_session_consumer(int domain, struct ltt_session *session)
2712 {
2713 int ret;
2714 const char *dir_name;
2715 struct consumer_output *consumer;
2716
2717 assert(session);
2718 assert(session->consumer);
2719
2720 switch (domain) {
2721 case LTTNG_DOMAIN_KERNEL:
2722 DBG3("Copying tracing session consumer output in kernel session");
2723 /*
2724 * XXX: We should audit the session creation and what this function
2725 * does "extra" in order to avoid a destroy since this function is used
2726 * in the domain session creation (kernel and ust) only. Same for UST
2727 * domain.
2728 */
2729 if (session->kernel_session->consumer) {
2730 consumer_output_put(session->kernel_session->consumer);
2731 }
2732 session->kernel_session->consumer =
2733 consumer_copy_output(session->consumer);
2734 /* Ease our life a bit for the next part */
2735 consumer = session->kernel_session->consumer;
2736 dir_name = DEFAULT_KERNEL_TRACE_DIR;
2737 break;
2738 case LTTNG_DOMAIN_JUL:
2739 case LTTNG_DOMAIN_LOG4J:
2740 case LTTNG_DOMAIN_PYTHON:
2741 case LTTNG_DOMAIN_UST:
2742 DBG3("Copying tracing session consumer output in UST session");
2743 if (session->ust_session->consumer) {
2744 consumer_output_put(session->ust_session->consumer);
2745 }
2746 session->ust_session->consumer =
2747 consumer_copy_output(session->consumer);
2748 /* Ease our life a bit for the next part */
2749 consumer = session->ust_session->consumer;
2750 dir_name = DEFAULT_UST_TRACE_DIR;
2751 break;
2752 default:
2753 ret = LTTNG_ERR_UNKNOWN_DOMAIN;
2754 goto error;
2755 }
2756
2757 /* Append correct directory to subdir */
2758 strncat(consumer->subdir, dir_name,
2759 sizeof(consumer->subdir) - strlen(consumer->subdir) - 1);
2760 DBG3("Copy session consumer subdir %s", consumer->subdir);
2761
2762 ret = LTTNG_OK;
2763
2764 error:
2765 return ret;
2766 }
2767
2768 /*
2769 * Create an UST session and add it to the session ust list.
2770 *
2771 * Should *NOT* be called with RCU read-side lock held.
2772 */
2773 static int create_ust_session(struct ltt_session *session,
2774 struct lttng_domain *domain)
2775 {
2776 int ret;
2777 struct ltt_ust_session *lus = NULL;
2778
2779 assert(session);
2780 assert(domain);
2781 assert(session->consumer);
2782
2783 switch (domain->type) {
2784 case LTTNG_DOMAIN_JUL:
2785 case LTTNG_DOMAIN_LOG4J:
2786 case LTTNG_DOMAIN_PYTHON:
2787 case LTTNG_DOMAIN_UST:
2788 break;
2789 default:
2790 ERR("Unknown UST domain on create session %d", domain->type);
2791 ret = LTTNG_ERR_UNKNOWN_DOMAIN;
2792 goto error;
2793 }
2794
2795 DBG("Creating UST session");
2796
2797 lus = trace_ust_create_session(session->id);
2798 if (lus == NULL) {
2799 ret = LTTNG_ERR_UST_SESS_FAIL;
2800 goto error;
2801 }
2802
2803 lus->uid = session->uid;
2804 lus->gid = session->gid;
2805 lus->output_traces = session->output_traces;
2806 lus->snapshot_mode = session->snapshot_mode;
2807 lus->live_timer_interval = session->live_timer;
2808 session->ust_session = lus;
2809 if (session->shm_path[0]) {
2810 strncpy(lus->root_shm_path, session->shm_path,
2811 sizeof(lus->root_shm_path));
2812 lus->root_shm_path[sizeof(lus->root_shm_path) - 1] = '\0';
2813 strncpy(lus->shm_path, session->shm_path,
2814 sizeof(lus->shm_path));
2815 lus->shm_path[sizeof(lus->shm_path) - 1] = '\0';
2816 strncat(lus->shm_path, "/ust",
2817 sizeof(lus->shm_path) - strlen(lus->shm_path) - 1);
2818 }
2819 /* Copy session output to the newly created UST session */
2820 ret = copy_session_consumer(domain->type, session);
2821 if (ret != LTTNG_OK) {
2822 goto error;
2823 }
2824
2825 return LTTNG_OK;
2826
2827 error:
2828 free(lus);
2829 session->ust_session = NULL;
2830 return ret;
2831 }
2832
2833 /*
2834 * Create a kernel tracer session then create the default channel.
2835 */
2836 static int create_kernel_session(struct ltt_session *session)
2837 {
2838 int ret;
2839
2840 DBG("Creating kernel session");
2841
2842 ret = kernel_create_session(session, kernel_tracer_fd);
2843 if (ret < 0) {
2844 ret = LTTNG_ERR_KERN_SESS_FAIL;
2845 goto error;
2846 }
2847
2848 /* Code flow safety */
2849 assert(session->kernel_session);
2850
2851 /* Copy session output to the newly created Kernel session */
2852 ret = copy_session_consumer(LTTNG_DOMAIN_KERNEL, session);
2853 if (ret != LTTNG_OK) {
2854 goto error;
2855 }
2856
2857 session->kernel_session->uid = session->uid;
2858 session->kernel_session->gid = session->gid;
2859 session->kernel_session->output_traces = session->output_traces;
2860 session->kernel_session->snapshot_mode = session->snapshot_mode;
2861
2862 return LTTNG_OK;
2863
2864 error:
2865 trace_kernel_destroy_session(session->kernel_session);
2866 session->kernel_session = NULL;
2867 return ret;
2868 }
2869
2870 /*
2871 * Count number of session permitted by uid/gid.
2872 */
2873 static unsigned int lttng_sessions_count(uid_t uid, gid_t gid)
2874 {
2875 unsigned int i = 0;
2876 struct ltt_session *session;
2877
2878 DBG("Counting number of available session for UID %d GID %d",
2879 uid, gid);
2880 cds_list_for_each_entry(session, &session_list_ptr->head, list) {
2881 /*
2882 * Only list the sessions the user can control.
2883 */
2884 if (!session_access_ok(session, uid, gid)) {
2885 continue;
2886 }
2887 i++;
2888 }
2889 return i;
2890 }
2891
2892 /*
2893 * Check if the current kernel tracer supports the session rotation feature.
2894 * Return 1 if it does, 0 otherwise.
2895 */
2896 static int check_rotate_compatible(void)
2897 {
2898 int ret = 1;
2899
2900 if (kernel_tracer_version.major != 2 || kernel_tracer_version.minor < 11) {
2901 DBG("Kernel tracer version is not compatible with the rotation feature");
2902 ret = 0;
2903 }
2904
2905 return ret;
2906 }
2907
2908 /*
2909 * Process the command requested by the lttng client within the command
2910 * context structure. This function make sure that the return structure (llm)
2911 * is set and ready for transmission before returning.
2912 *
2913 * Return any error encountered or 0 for success.
2914 *
2915 * "sock" is only used for special-case var. len data.
2916 *
2917 * Should *NOT* be called with RCU read-side lock held.
2918 */
2919 static int process_client_msg(struct command_ctx *cmd_ctx, int sock,
2920 int *sock_error)
2921 {
2922 int ret = LTTNG_OK;
2923 int need_tracing_session = 1;
2924 int need_domain;
2925
2926 DBG("Processing client command %d", cmd_ctx->lsm->cmd_type);
2927
2928 assert(!rcu_read_ongoing());
2929
2930 *sock_error = 0;
2931
2932 switch (cmd_ctx->lsm->cmd_type) {
2933 case LTTNG_CREATE_SESSION:
2934 case LTTNG_CREATE_SESSION_SNAPSHOT:
2935 case LTTNG_CREATE_SESSION_LIVE:
2936 case LTTNG_DESTROY_SESSION:
2937 case LTTNG_LIST_SESSIONS:
2938 case LTTNG_LIST_DOMAINS:
2939 case LTTNG_START_TRACE:
2940 case LTTNG_STOP_TRACE:
2941 case LTTNG_DATA_PENDING:
2942 case LTTNG_SNAPSHOT_ADD_OUTPUT:
2943 case LTTNG_SNAPSHOT_DEL_OUTPUT:
2944 case LTTNG_SNAPSHOT_LIST_OUTPUT:
2945 case LTTNG_SNAPSHOT_RECORD:
2946 case LTTNG_SAVE_SESSION:
2947 case LTTNG_SET_SESSION_SHM_PATH:
2948 case LTTNG_REGENERATE_METADATA:
2949 case LTTNG_REGENERATE_STATEDUMP:
2950 case LTTNG_REGISTER_TRIGGER:
2951 case LTTNG_UNREGISTER_TRIGGER:
2952 case LTTNG_ROTATE_SESSION:
2953 case LTTNG_ROTATION_GET_INFO:
2954 case LTTNG_SESSION_GET_CURRENT_OUTPUT:
2955 case LTTNG_ROTATION_SET_SCHEDULE:
2956 case LTTNG_ROTATION_SCHEDULE_GET_TIMER_PERIOD:
2957 case LTTNG_ROTATION_SCHEDULE_GET_SIZE:
2958 need_domain = 0;
2959 break;
2960 default:
2961 need_domain = 1;
2962 }
2963
2964 if (config.no_kernel && need_domain
2965 && cmd_ctx->lsm->domain.type == LTTNG_DOMAIN_KERNEL) {
2966 if (!is_root) {
2967 ret = LTTNG_ERR_NEED_ROOT_SESSIOND;
2968 } else {
2969 ret = LTTNG_ERR_KERN_NA;
2970 }
2971 goto error;
2972 }
2973
2974 /* Deny register consumer if we already have a spawned consumer. */
2975 if (cmd_ctx->lsm->cmd_type == LTTNG_REGISTER_CONSUMER) {
2976 pthread_mutex_lock(&kconsumer_data.pid_mutex);
2977 if (kconsumer_data.pid > 0) {
2978 ret = LTTNG_ERR_KERN_CONSUMER_FAIL;
2979 pthread_mutex_unlock(&kconsumer_data.pid_mutex);
2980 goto error;
2981 }
2982 pthread_mutex_unlock(&kconsumer_data.pid_mutex);
2983 }
2984
2985 /*
2986 * Check for command that don't needs to allocate a returned payload. We do
2987 * this here so we don't have to make the call for no payload at each
2988 * command.
2989 */
2990 switch(cmd_ctx->lsm->cmd_type) {
2991 case LTTNG_LIST_SESSIONS:
2992 case LTTNG_LIST_TRACEPOINTS:
2993 case LTTNG_LIST_TRACEPOINT_FIELDS:
2994 case LTTNG_LIST_DOMAINS:
2995 case LTTNG_LIST_CHANNELS:
2996 case LTTNG_LIST_EVENTS:
2997 case LTTNG_LIST_SYSCALLS:
2998 case LTTNG_LIST_TRACKER_PIDS:
2999 case LTTNG_DATA_PENDING:
3000 case LTTNG_ROTATE_SESSION:
3001 case LTTNG_ROTATION_GET_INFO:
3002 case LTTNG_ROTATION_SCHEDULE_GET_TIMER_PERIOD:
3003 case LTTNG_ROTATION_SCHEDULE_GET_SIZE:
3004 break;
3005 default:
3006 /* Setup lttng message with no payload */
3007 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, NULL, 0);
3008 if (ret < 0) {
3009 /* This label does not try to unlock the session */
3010 goto init_setup_error;
3011 }
3012 }
3013
3014 /* Commands that DO NOT need a session. */
3015 switch (cmd_ctx->lsm->cmd_type) {
3016 case LTTNG_CREATE_SESSION:
3017 case LTTNG_CREATE_SESSION_SNAPSHOT:
3018 case LTTNG_CREATE_SESSION_LIVE:
3019 case LTTNG_LIST_SESSIONS:
3020 case LTTNG_LIST_TRACEPOINTS:
3021 case LTTNG_LIST_SYSCALLS:
3022 case LTTNG_LIST_TRACEPOINT_FIELDS:
3023 case LTTNG_SAVE_SESSION:
3024 case LTTNG_REGISTER_TRIGGER:
3025 case LTTNG_UNREGISTER_TRIGGER:
3026 need_tracing_session = 0;
3027 break;
3028 default:
3029 DBG("Getting session %s by name", cmd_ctx->lsm->session.name);
3030 /*
3031 * We keep the session list lock across _all_ commands
3032 * for now, because the per-session lock does not
3033 * handle teardown properly.
3034 */
3035 session_lock_list();
3036 cmd_ctx->session = session_find_by_name(cmd_ctx->lsm->session.name);
3037 if (cmd_ctx->session == NULL) {
3038 ret = LTTNG_ERR_SESS_NOT_FOUND;
3039 goto error;
3040 } else {
3041 /* Acquire lock for the session */
3042 session_lock(cmd_ctx->session);
3043 }
3044 break;
3045 }
3046
3047 /*
3048 * Commands that need a valid session but should NOT create one if none
3049 * exists. Instead of creating one and destroying it when the command is
3050 * handled, process that right before so we save some round trip in useless
3051 * code path.
3052 */
3053 switch (cmd_ctx->lsm->cmd_type) {
3054 case LTTNG_DISABLE_CHANNEL:
3055 case LTTNG_DISABLE_EVENT:
3056 switch (cmd_ctx->lsm->domain.type) {
3057 case LTTNG_DOMAIN_KERNEL:
3058 if (!cmd_ctx->session->kernel_session) {
3059 ret = LTTNG_ERR_NO_CHANNEL;
3060 goto error;
3061 }
3062 break;
3063 case LTTNG_DOMAIN_JUL:
3064 case LTTNG_DOMAIN_LOG4J:
3065 case LTTNG_DOMAIN_PYTHON:
3066 case LTTNG_DOMAIN_UST:
3067 if (!cmd_ctx->session->ust_session) {
3068 ret = LTTNG_ERR_NO_CHANNEL;
3069 goto error;
3070 }
3071 break;
3072 default:
3073 ret = LTTNG_ERR_UNKNOWN_DOMAIN;
3074 goto error;
3075 }
3076 default:
3077 break;
3078 }
3079
3080 if (!need_domain) {
3081 goto skip_domain;
3082 }
3083
3084 /*
3085 * Check domain type for specific "pre-action".
3086 */
3087 switch (cmd_ctx->lsm->domain.type) {
3088 case LTTNG_DOMAIN_KERNEL:
3089 if (!is_root) {
3090 ret = LTTNG_ERR_NEED_ROOT_SESSIOND;
3091 goto error;
3092 }
3093
3094 /* Kernel tracer check */
3095 if (kernel_tracer_fd == -1) {
3096 /* Basically, load kernel tracer modules */
3097 ret = init_kernel_tracer();
3098 if (ret != 0) {
3099 goto error;
3100 }
3101 }
3102
3103 /* Consumer is in an ERROR state. Report back to client */
3104 if (uatomic_read(&kernel_consumerd_state) == CONSUMER_ERROR) {
3105 ret = LTTNG_ERR_NO_KERNCONSUMERD;
3106 goto error;
3107 }
3108
3109 /* Need a session for kernel command */
3110 if (need_tracing_session) {
3111 if (cmd_ctx->session->kernel_session == NULL) {
3112 ret = create_kernel_session(cmd_ctx->session);
3113 if (ret < 0) {
3114 ret = LTTNG_ERR_KERN_SESS_FAIL;
3115 goto error;
3116 }
3117 }
3118
3119 /* Start the kernel consumer daemon */
3120 pthread_mutex_lock(&kconsumer_data.pid_mutex);
3121 if (kconsumer_data.pid == 0 &&
3122 cmd_ctx->lsm->cmd_type != LTTNG_REGISTER_CONSUMER) {
3123 pthread_mutex_unlock(&kconsumer_data.pid_mutex);
3124 ret = start_consumerd(&kconsumer_data);
3125 if (ret < 0) {
3126 ret = LTTNG_ERR_KERN_CONSUMER_FAIL;
3127 goto error;
3128 }
3129 uatomic_set(&kernel_consumerd_state, CONSUMER_STARTED);
3130 } else {
3131 pthread_mutex_unlock(&kconsumer_data.pid_mutex);
3132 }
3133
3134 /*
3135 * The consumer was just spawned so we need to add the socket to
3136 * the consumer output of the session if exist.
3137 */
3138 ret = consumer_create_socket(&kconsumer_data,
3139 cmd_ctx->session->kernel_session->consumer);
3140 if (ret < 0) {
3141 goto error;
3142 }
3143 }
3144
3145 break;
3146 case LTTNG_DOMAIN_JUL:
3147 case LTTNG_DOMAIN_LOG4J:
3148 case LTTNG_DOMAIN_PYTHON:
3149 case LTTNG_DOMAIN_UST:
3150 {
3151 if (!ust_app_supported()) {
3152 ret = LTTNG_ERR_NO_UST;
3153 goto error;
3154 }
3155 /* Consumer is in an ERROR state. Report back to client */
3156 if (uatomic_read(&ust_consumerd_state) == CONSUMER_ERROR) {
3157 ret = LTTNG_ERR_NO_USTCONSUMERD;
3158 goto error;
3159 }
3160
3161 if (need_tracing_session) {
3162 /* Create UST session if none exist. */
3163 if (cmd_ctx->session->ust_session == NULL) {
3164 ret = create_ust_session(cmd_ctx->session,
3165 &cmd_ctx->lsm->domain);
3166 if (ret != LTTNG_OK) {
3167 goto error;
3168 }
3169 }
3170
3171 /* Start the UST consumer daemons */
3172 /* 64-bit */
3173 pthread_mutex_lock(&ustconsumer64_data.pid_mutex);
3174 if (config.consumerd64_bin_path.value &&
3175 ustconsumer64_data.pid == 0 &&
3176 cmd_ctx->lsm->cmd_type != LTTNG_REGISTER_CONSUMER) {
3177 pthread_mutex_unlock(&ustconsumer64_data.pid_mutex);
3178 ret = start_consumerd(&ustconsumer64_data);
3179 if (ret < 0) {
3180 ret = LTTNG_ERR_UST_CONSUMER64_FAIL;
3181 uatomic_set(&ust_consumerd64_fd, -EINVAL);
3182 goto error;
3183 }
3184
3185 uatomic_set(&ust_consumerd64_fd, ustconsumer64_data.cmd_sock);
3186 uatomic_set(&ust_consumerd_state, CONSUMER_STARTED);
3187 } else {
3188 pthread_mutex_unlock(&ustconsumer64_data.pid_mutex);
3189 }
3190
3191 /*
3192 * Setup socket for consumer 64 bit. No need for atomic access
3193 * since it was set above and can ONLY be set in this thread.
3194 */
3195 ret = consumer_create_socket(&ustconsumer64_data,
3196 cmd_ctx->session->ust_session->consumer);
3197 if (ret < 0) {
3198 goto error;
3199 }
3200
3201 /* 32-bit */
3202 pthread_mutex_lock(&ustconsumer32_data.pid_mutex);
3203 if (config.consumerd32_bin_path.value &&
3204 ustconsumer32_data.pid == 0 &&
3205 cmd_ctx->lsm->cmd_type != LTTNG_REGISTER_CONSUMER) {
3206 pthread_mutex_unlock(&ustconsumer32_data.pid_mutex);
3207 ret = start_consumerd(&ustconsumer32_data);
3208 if (ret < 0) {
3209 ret = LTTNG_ERR_UST_CONSUMER32_FAIL;
3210 uatomic_set(&ust_consumerd32_fd, -EINVAL);
3211 goto error;
3212 }
3213
3214 uatomic_set(&ust_consumerd32_fd, ustconsumer32_data.cmd_sock);
3215 uatomic_set(&ust_consumerd_state, CONSUMER_STARTED);
3216 } else {
3217 pthread_mutex_unlock(&ustconsumer32_data.pid_mutex);
3218 }
3219
3220 /*