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