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