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