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