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