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