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