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