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