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