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