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