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