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