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