Docs: document safety of consumer_thread_is_ready access
[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 /*
2375 * Make sure we set the readiness flag to 0 because we are NOT ready.
2376 * This access to consumer_thread_is_ready does not need to be
2377 * protected by consumer_data.cond_mutex (yet) since the consumer
2378 * management thread has not been started at this point.
2379 */
2380 consumer_data->consumer_thread_is_ready = 0;
2381
2382 /* Setup pthread condition */
2383 ret = pthread_condattr_init(&consumer_data->condattr);
2384 if (ret) {
2385 errno = ret;
2386 PERROR("pthread_condattr_init consumer data");
2387 goto error;
2388 }
2389
2390 /*
2391 * Set the monotonic clock in order to make sure we DO NOT jump in time
2392 * between the clock_gettime() call and the timedwait call. See bug #324
2393 * for a more details and how we noticed it.
2394 */
2395 ret = pthread_condattr_setclock(&consumer_data->condattr, CLOCK_MONOTONIC);
2396 if (ret) {
2397 errno = ret;
2398 PERROR("pthread_condattr_setclock consumer data");
2399 goto error;
2400 }
2401
2402 ret = pthread_cond_init(&consumer_data->cond, &consumer_data->condattr);
2403 if (ret) {
2404 errno = ret;
2405 PERROR("pthread_cond_init consumer data");
2406 goto error;
2407 }
2408
2409 ret = pthread_create(&consumer_data->thread, NULL, thread_manage_consumer,
2410 consumer_data);
2411 if (ret) {
2412 errno = ret;
2413 PERROR("pthread_create consumer");
2414 ret = -1;
2415 goto error;
2416 }
2417
2418 /* We are about to wait on a pthread condition */
2419 pthread_mutex_lock(&consumer_data->cond_mutex);
2420
2421 /* Get time for sem_timedwait absolute timeout */
2422 clock_ret = clock_gettime(CLOCK_MONOTONIC, &timeout);
2423 /*
2424 * Set the timeout for the condition timed wait even if the clock gettime
2425 * call fails since we might loop on that call and we want to avoid to
2426 * increment the timeout too many times.
2427 */
2428 timeout.tv_sec += DEFAULT_SEM_WAIT_TIMEOUT;
2429
2430 /*
2431 * The following loop COULD be skipped in some conditions so this is why we
2432 * set ret to 0 in order to make sure at least one round of the loop is
2433 * done.
2434 */
2435 ret = 0;
2436
2437 /*
2438 * Loop until the condition is reached or when a timeout is reached. Note
2439 * that the pthread_cond_timedwait(P) man page specifies that EINTR can NOT
2440 * be returned but the pthread_cond(3), from the glibc-doc, says that it is
2441 * possible. This loop does not take any chances and works with both of
2442 * them.
2443 */
2444 while (!consumer_data->consumer_thread_is_ready && ret != ETIMEDOUT) {
2445 if (clock_ret < 0) {
2446 PERROR("clock_gettime spawn consumer");
2447 /* Infinite wait for the consumerd thread to be ready */
2448 ret = pthread_cond_wait(&consumer_data->cond,
2449 &consumer_data->cond_mutex);
2450 } else {
2451 ret = pthread_cond_timedwait(&consumer_data->cond,
2452 &consumer_data->cond_mutex, &timeout);
2453 }
2454 }
2455
2456 /* Release the pthread condition */
2457 pthread_mutex_unlock(&consumer_data->cond_mutex);
2458
2459 if (ret != 0) {
2460 errno = ret;
2461 if (ret == ETIMEDOUT) {
2462 int pth_ret;
2463
2464 /*
2465 * Call has timed out so we kill the kconsumerd_thread and return
2466 * an error.
2467 */
2468 ERR("Condition timed out. The consumer thread was never ready."
2469 " Killing it");
2470 pth_ret = pthread_cancel(consumer_data->thread);
2471 if (pth_ret < 0) {
2472 PERROR("pthread_cancel consumer thread");
2473 }
2474 } else {
2475 PERROR("pthread_cond_wait failed consumer thread");
2476 }
2477 /* Caller is expecting a negative value on failure. */
2478 ret = -1;
2479 goto error;
2480 }
2481
2482 pthread_mutex_lock(&consumer_data->pid_mutex);
2483 if (consumer_data->pid == 0) {
2484 ERR("Consumerd did not start");
2485 pthread_mutex_unlock(&consumer_data->pid_mutex);
2486 goto error;
2487 }
2488 pthread_mutex_unlock(&consumer_data->pid_mutex);
2489
2490 return 0;
2491
2492 error:
2493 return ret;
2494 }
2495
2496 /*
2497 * Join consumer thread
2498 */
2499 static int join_consumer_thread(struct consumer_data *consumer_data)
2500 {
2501 void *status;
2502
2503 /* Consumer pid must be a real one. */
2504 if (consumer_data->pid > 0) {
2505 int ret;
2506 ret = kill(consumer_data->pid, SIGTERM);
2507 if (ret) {
2508 PERROR("Error killing consumer daemon");
2509 return ret;
2510 }
2511 return pthread_join(consumer_data->thread, &status);
2512 } else {
2513 return 0;
2514 }
2515 }
2516
2517 /*
2518 * Fork and exec a consumer daemon (consumerd).
2519 *
2520 * Return pid if successful else -1.
2521 */
2522 static pid_t spawn_consumerd(struct consumer_data *consumer_data)
2523 {
2524 int ret;
2525 pid_t pid;
2526 const char *consumer_to_use;
2527 const char *verbosity;
2528 struct stat st;
2529
2530 DBG("Spawning consumerd");
2531
2532 pid = fork();
2533 if (pid == 0) {
2534 /*
2535 * Exec consumerd.
2536 */
2537 if (opt_verbose_consumer) {
2538 verbosity = "--verbose";
2539 } else if (lttng_opt_quiet) {
2540 verbosity = "--quiet";
2541 } else {
2542 verbosity = "";
2543 }
2544
2545 switch (consumer_data->type) {
2546 case LTTNG_CONSUMER_KERNEL:
2547 /*
2548 * Find out which consumerd to execute. We will first try the
2549 * 64-bit path, then the sessiond's installation directory, and
2550 * fallback on the 32-bit one,
2551 */
2552 DBG3("Looking for a kernel consumer at these locations:");
2553 DBG3(" 1) %s", consumerd64_bin);
2554 DBG3(" 2) %s/%s", INSTALL_BIN_PATH, CONSUMERD_FILE);
2555 DBG3(" 3) %s", consumerd32_bin);
2556 if (stat(consumerd64_bin, &st) == 0) {
2557 DBG3("Found location #1");
2558 consumer_to_use = consumerd64_bin;
2559 } else if (stat(INSTALL_BIN_PATH "/" CONSUMERD_FILE, &st) == 0) {
2560 DBG3("Found location #2");
2561 consumer_to_use = INSTALL_BIN_PATH "/" CONSUMERD_FILE;
2562 } else if (stat(consumerd32_bin, &st) == 0) {
2563 DBG3("Found location #3");
2564 consumer_to_use = consumerd32_bin;
2565 } else {
2566 DBG("Could not find any valid consumerd executable");
2567 ret = -EINVAL;
2568 break;
2569 }
2570 DBG("Using kernel consumer at: %s", consumer_to_use);
2571 ret = execl(consumer_to_use,
2572 "lttng-consumerd", verbosity, "-k",
2573 "--consumerd-cmd-sock", consumer_data->cmd_unix_sock_path,
2574 "--consumerd-err-sock", consumer_data->err_unix_sock_path,
2575 "--group", tracing_group_name,
2576 NULL);
2577 break;
2578 case LTTNG_CONSUMER64_UST:
2579 {
2580 char *tmpnew = NULL;
2581
2582 if (consumerd64_libdir[0] != '\0') {
2583 char *tmp;
2584 size_t tmplen;
2585
2586 tmp = lttng_secure_getenv("LD_LIBRARY_PATH");
2587 if (!tmp) {
2588 tmp = "";
2589 }
2590 tmplen = strlen("LD_LIBRARY_PATH=")
2591 + strlen(consumerd64_libdir) + 1 /* : */ + strlen(tmp);
2592 tmpnew = zmalloc(tmplen + 1 /* \0 */);
2593 if (!tmpnew) {
2594 ret = -ENOMEM;
2595 goto error;
2596 }
2597 strcpy(tmpnew, "LD_LIBRARY_PATH=");
2598 strcat(tmpnew, consumerd64_libdir);
2599 if (tmp[0] != '\0') {
2600 strcat(tmpnew, ":");
2601 strcat(tmpnew, tmp);
2602 }
2603 ret = putenv(tmpnew);
2604 if (ret) {
2605 ret = -errno;
2606 free(tmpnew);
2607 goto error;
2608 }
2609 }
2610 DBG("Using 64-bit UST consumer at: %s", consumerd64_bin);
2611 ret = execl(consumerd64_bin, "lttng-consumerd", verbosity, "-u",
2612 "--consumerd-cmd-sock", consumer_data->cmd_unix_sock_path,
2613 "--consumerd-err-sock", consumer_data->err_unix_sock_path,
2614 "--group", tracing_group_name,
2615 NULL);
2616 if (consumerd64_libdir[0] != '\0') {
2617 free(tmpnew);
2618 }
2619 break;
2620 }
2621 case LTTNG_CONSUMER32_UST:
2622 {
2623 char *tmpnew = NULL;
2624
2625 if (consumerd32_libdir[0] != '\0') {
2626 char *tmp;
2627 size_t tmplen;
2628
2629 tmp = lttng_secure_getenv("LD_LIBRARY_PATH");
2630 if (!tmp) {
2631 tmp = "";
2632 }
2633 tmplen = strlen("LD_LIBRARY_PATH=")
2634 + strlen(consumerd32_libdir) + 1 /* : */ + strlen(tmp);
2635 tmpnew = zmalloc(tmplen + 1 /* \0 */);
2636 if (!tmpnew) {
2637 ret = -ENOMEM;
2638 goto error;
2639 }
2640 strcpy(tmpnew, "LD_LIBRARY_PATH=");
2641 strcat(tmpnew, consumerd32_libdir);
2642 if (tmp[0] != '\0') {
2643 strcat(tmpnew, ":");
2644 strcat(tmpnew, tmp);
2645 }
2646 ret = putenv(tmpnew);
2647 if (ret) {
2648 ret = -errno;
2649 free(tmpnew);
2650 goto error;
2651 }
2652 }
2653 DBG("Using 32-bit UST consumer at: %s", consumerd32_bin);
2654 ret = execl(consumerd32_bin, "lttng-consumerd", verbosity, "-u",
2655 "--consumerd-cmd-sock", consumer_data->cmd_unix_sock_path,
2656 "--consumerd-err-sock", consumer_data->err_unix_sock_path,
2657 "--group", tracing_group_name,
2658 NULL);
2659 if (consumerd32_libdir[0] != '\0') {
2660 free(tmpnew);
2661 }
2662 break;
2663 }
2664 default:
2665 PERROR("unknown consumer type");
2666 exit(EXIT_FAILURE);
2667 }
2668 if (errno != 0) {
2669 PERROR("Consumer execl()");
2670 }
2671 /* Reaching this point, we got a failure on our execl(). */
2672 exit(EXIT_FAILURE);
2673 } else if (pid > 0) {
2674 ret = pid;
2675 } else {
2676 PERROR("start consumer fork");
2677 ret = -errno;
2678 }
2679 error:
2680 return ret;
2681 }
2682
2683 /*
2684 * Spawn the consumerd daemon and session daemon thread.
2685 */
2686 static int start_consumerd(struct consumer_data *consumer_data)
2687 {
2688 int ret;
2689
2690 /*
2691 * Set the listen() state on the socket since there is a possible race
2692 * between the exec() of the consumer daemon and this call if place in the
2693 * consumer thread. See bug #366 for more details.
2694 */
2695 ret = lttcomm_listen_unix_sock(consumer_data->err_sock);
2696 if (ret < 0) {
2697 goto error;
2698 }
2699
2700 pthread_mutex_lock(&consumer_data->pid_mutex);
2701 if (consumer_data->pid != 0) {
2702 pthread_mutex_unlock(&consumer_data->pid_mutex);
2703 goto end;
2704 }
2705
2706 ret = spawn_consumerd(consumer_data);
2707 if (ret < 0) {
2708 ERR("Spawning consumerd failed");
2709 pthread_mutex_unlock(&consumer_data->pid_mutex);
2710 goto error;
2711 }
2712
2713 /* Setting up the consumer_data pid */
2714 consumer_data->pid = ret;
2715 DBG2("Consumer pid %d", consumer_data->pid);
2716 pthread_mutex_unlock(&consumer_data->pid_mutex);
2717
2718 DBG2("Spawning consumer control thread");
2719 ret = spawn_consumer_thread(consumer_data);
2720 if (ret < 0) {
2721 ERR("Fatal error spawning consumer control thread");
2722 goto error;
2723 }
2724
2725 end:
2726 return 0;
2727
2728 error:
2729 /* Cleanup already created sockets on error. */
2730 if (consumer_data->err_sock >= 0) {
2731 int err;
2732
2733 err = close(consumer_data->err_sock);
2734 if (err < 0) {
2735 PERROR("close consumer data error socket");
2736 }
2737 }
2738 return ret;
2739 }
2740
2741 /*
2742 * Setup necessary data for kernel tracer action.
2743 */
2744 static int init_kernel_tracer(void)
2745 {
2746 int ret;
2747
2748 /* Modprobe lttng kernel modules */
2749 ret = modprobe_lttng_control();
2750 if (ret < 0) {
2751 goto error;
2752 }
2753
2754 /* Open debugfs lttng */
2755 kernel_tracer_fd = open(module_proc_lttng, O_RDWR);
2756 if (kernel_tracer_fd < 0) {
2757 DBG("Failed to open %s", module_proc_lttng);
2758 ret = -1;
2759 goto error_open;
2760 }
2761
2762 /* Validate kernel version */
2763 ret = kernel_validate_version(kernel_tracer_fd);
2764 if (ret < 0) {
2765 goto error_version;
2766 }
2767
2768 ret = modprobe_lttng_data();
2769 if (ret < 0) {
2770 goto error_modules;
2771 }
2772
2773 DBG("Kernel tracer fd %d", kernel_tracer_fd);
2774 return 0;
2775
2776 error_version:
2777 modprobe_remove_lttng_control();
2778 ret = close(kernel_tracer_fd);
2779 if (ret) {
2780 PERROR("close");
2781 }
2782 kernel_tracer_fd = -1;
2783 return LTTNG_ERR_KERN_VERSION;
2784
2785 error_modules:
2786 ret = close(kernel_tracer_fd);
2787 if (ret) {
2788 PERROR("close");
2789 }
2790
2791 error_open:
2792 modprobe_remove_lttng_control();
2793
2794 error:
2795 WARN("No kernel tracer available");
2796 kernel_tracer_fd = -1;
2797 if (!is_root) {
2798 return LTTNG_ERR_NEED_ROOT_SESSIOND;
2799 } else {
2800 return LTTNG_ERR_KERN_NA;
2801 }
2802 }
2803
2804
2805 /*
2806 * Copy consumer output from the tracing session to the domain session. The
2807 * function also applies the right modification on a per domain basis for the
2808 * trace files destination directory.
2809 *
2810 * Should *NOT* be called with RCU read-side lock held.
2811 */
2812 static int copy_session_consumer(int domain, struct ltt_session *session)
2813 {
2814 int ret;
2815 const char *dir_name;
2816 struct consumer_output *consumer;
2817
2818 assert(session);
2819 assert(session->consumer);
2820
2821 switch (domain) {
2822 case LTTNG_DOMAIN_KERNEL:
2823 DBG3("Copying tracing session consumer output in kernel session");
2824 /*
2825 * XXX: We should audit the session creation and what this function
2826 * does "extra" in order to avoid a destroy since this function is used
2827 * in the domain session creation (kernel and ust) only. Same for UST
2828 * domain.
2829 */
2830 if (session->kernel_session->consumer) {
2831 consumer_output_put(session->kernel_session->consumer);
2832 }
2833 session->kernel_session->consumer =
2834 consumer_copy_output(session->consumer);
2835 /* Ease our life a bit for the next part */
2836 consumer = session->kernel_session->consumer;
2837 dir_name = DEFAULT_KERNEL_TRACE_DIR;
2838 break;
2839 case LTTNG_DOMAIN_JUL:
2840 case LTTNG_DOMAIN_LOG4J:
2841 case LTTNG_DOMAIN_PYTHON:
2842 case LTTNG_DOMAIN_UST:
2843 DBG3("Copying tracing session consumer output in UST session");
2844 if (session->ust_session->consumer) {
2845 consumer_output_put(session->ust_session->consumer);
2846 }
2847 session->ust_session->consumer =
2848 consumer_copy_output(session->consumer);
2849 /* Ease our life a bit for the next part */
2850 consumer = session->ust_session->consumer;
2851 dir_name = DEFAULT_UST_TRACE_DIR;
2852 break;
2853 default:
2854 ret = LTTNG_ERR_UNKNOWN_DOMAIN;
2855 goto error;
2856 }
2857
2858 /* Append correct directory to subdir */
2859 strncat(consumer->subdir, dir_name,
2860 sizeof(consumer->subdir) - strlen(consumer->subdir) - 1);
2861 DBG3("Copy session consumer subdir %s", consumer->subdir);
2862
2863 ret = LTTNG_OK;
2864
2865 error:
2866 return ret;
2867 }
2868
2869 /*
2870 * Create an UST session and add it to the session ust list.
2871 *
2872 * Should *NOT* be called with RCU read-side lock held.
2873 */
2874 static int create_ust_session(struct ltt_session *session,
2875 struct lttng_domain *domain)
2876 {
2877 int ret;
2878 struct ltt_ust_session *lus = NULL;
2879
2880 assert(session);
2881 assert(domain);
2882 assert(session->consumer);
2883
2884 switch (domain->type) {
2885 case LTTNG_DOMAIN_JUL:
2886 case LTTNG_DOMAIN_LOG4J:
2887 case LTTNG_DOMAIN_PYTHON:
2888 case LTTNG_DOMAIN_UST:
2889 break;
2890 default:
2891 ERR("Unknown UST domain on create session %d", domain->type);
2892 ret = LTTNG_ERR_UNKNOWN_DOMAIN;
2893 goto error;
2894 }
2895
2896 DBG("Creating UST session");
2897
2898 lus = trace_ust_create_session(session->id);
2899 if (lus == NULL) {
2900 ret = LTTNG_ERR_UST_SESS_FAIL;
2901 goto error;
2902 }
2903
2904 lus->uid = session->uid;
2905 lus->gid = session->gid;
2906 lus->output_traces = session->output_traces;
2907 lus->snapshot_mode = session->snapshot_mode;
2908 lus->live_timer_interval = session->live_timer;
2909 session->ust_session = lus;
2910 if (session->shm_path[0]) {
2911 strncpy(lus->root_shm_path, session->shm_path,
2912 sizeof(lus->root_shm_path));
2913 lus->root_shm_path[sizeof(lus->root_shm_path) - 1] = '\0';
2914 strncpy(lus->shm_path, session->shm_path,
2915 sizeof(lus->shm_path));
2916 lus->shm_path[sizeof(lus->shm_path) - 1] = '\0';
2917 strncat(lus->shm_path, "/ust",
2918 sizeof(lus->shm_path) - strlen(lus->shm_path) - 1);
2919 }
2920 /* Copy session output to the newly created UST session */
2921 ret = copy_session_consumer(domain->type, session);
2922 if (ret != LTTNG_OK) {
2923 goto error;
2924 }
2925
2926 return LTTNG_OK;
2927
2928 error:
2929 free(lus);
2930 session->ust_session = NULL;
2931 return ret;
2932 }
2933
2934 /*
2935 * Create a kernel tracer session then create the default channel.
2936 */
2937 static int create_kernel_session(struct ltt_session *session)
2938 {
2939 int ret;
2940
2941 DBG("Creating kernel session");
2942
2943 ret = kernel_create_session(session, kernel_tracer_fd);
2944 if (ret < 0) {
2945 ret = LTTNG_ERR_KERN_SESS_FAIL;
2946 goto error;
2947 }
2948
2949 /* Code flow safety */
2950 assert(session->kernel_session);
2951
2952 /* Copy session output to the newly created Kernel session */
2953 ret = copy_session_consumer(LTTNG_DOMAIN_KERNEL, session);
2954 if (ret != LTTNG_OK) {
2955 goto error;
2956 }
2957
2958 /* Create directory(ies) on local filesystem. */
2959 if (session->kernel_session->consumer->type == CONSUMER_DST_LOCAL &&
2960 strlen(session->kernel_session->consumer->dst.trace_path) > 0) {
2961 ret = run_as_mkdir_recursive(
2962 session->kernel_session->consumer->dst.trace_path,
2963 S_IRWXU | S_IRWXG, session->uid, session->gid);
2964 if (ret < 0) {
2965 if (errno != EEXIST) {
2966 ERR("Trace directory creation error");
2967 goto error;
2968 }
2969 }
2970 }
2971
2972 session->kernel_session->uid = session->uid;
2973 session->kernel_session->gid = session->gid;
2974 session->kernel_session->output_traces = session->output_traces;
2975 session->kernel_session->snapshot_mode = session->snapshot_mode;
2976
2977 return LTTNG_OK;
2978
2979 error:
2980 trace_kernel_destroy_session(session->kernel_session);
2981 session->kernel_session = NULL;
2982 return ret;
2983 }
2984
2985 /*
2986 * Count number of session permitted by uid/gid.
2987 */
2988 static unsigned int lttng_sessions_count(uid_t uid, gid_t gid)
2989 {
2990 unsigned int i = 0;
2991 struct ltt_session *session;
2992
2993 DBG("Counting number of available session for UID %d GID %d",
2994 uid, gid);
2995 cds_list_for_each_entry(session, &session_list_ptr->head, list) {
2996 /*
2997 * Only list the sessions the user can control.
2998 */
2999 if (!session_access_ok(session, uid, gid)) {
3000 continue;
3001 }
3002 i++;
3003 }
3004 return i;
3005 }
3006
3007 /*
3008 * Process the command requested by the lttng client within the command
3009 * context structure. This function make sure that the return structure (llm)
3010 * is set and ready for transmission before returning.
3011 *
3012 * Return any error encountered or 0 for success.
3013 *
3014 * "sock" is only used for special-case var. len data.
3015 *
3016 * Should *NOT* be called with RCU read-side lock held.
3017 */
3018 static int process_client_msg(struct command_ctx *cmd_ctx, int sock,
3019 int *sock_error)
3020 {
3021 int ret = LTTNG_OK;
3022 int need_tracing_session = 1;
3023 int need_domain;
3024
3025 DBG("Processing client command %d", cmd_ctx->lsm->cmd_type);
3026
3027 assert(!rcu_read_ongoing());
3028
3029 *sock_error = 0;
3030
3031 switch (cmd_ctx->lsm->cmd_type) {
3032 case LTTNG_CREATE_SESSION:
3033 case LTTNG_CREATE_SESSION_SNAPSHOT:
3034 case LTTNG_CREATE_SESSION_LIVE:
3035 case LTTNG_DESTROY_SESSION:
3036 case LTTNG_LIST_SESSIONS:
3037 case LTTNG_LIST_DOMAINS:
3038 case LTTNG_START_TRACE:
3039 case LTTNG_STOP_TRACE:
3040 case LTTNG_DATA_PENDING:
3041 case LTTNG_SNAPSHOT_ADD_OUTPUT:
3042 case LTTNG_SNAPSHOT_DEL_OUTPUT:
3043 case LTTNG_SNAPSHOT_LIST_OUTPUT:
3044 case LTTNG_SNAPSHOT_RECORD:
3045 case LTTNG_SAVE_SESSION:
3046 case LTTNG_SET_SESSION_SHM_PATH:
3047 case LTTNG_METADATA_REGENERATE:
3048 need_domain = 0;
3049 break;
3050 default:
3051 need_domain = 1;
3052 }
3053
3054 if (opt_no_kernel && need_domain
3055 && cmd_ctx->lsm->domain.type == LTTNG_DOMAIN_KERNEL) {
3056 if (!is_root) {
3057 ret = LTTNG_ERR_NEED_ROOT_SESSIOND;
3058 } else {
3059 ret = LTTNG_ERR_KERN_NA;
3060 }
3061 goto error;
3062 }
3063
3064 /* Deny register consumer if we already have a spawned consumer. */
3065 if (cmd_ctx->lsm->cmd_type == LTTNG_REGISTER_CONSUMER) {
3066 pthread_mutex_lock(&kconsumer_data.pid_mutex);
3067 if (kconsumer_data.pid > 0) {
3068 ret = LTTNG_ERR_KERN_CONSUMER_FAIL;
3069 pthread_mutex_unlock(&kconsumer_data.pid_mutex);
3070 goto error;
3071 }
3072 pthread_mutex_unlock(&kconsumer_data.pid_mutex);
3073 }
3074
3075 /*
3076 * Check for command that don't needs to allocate a returned payload. We do
3077 * this here so we don't have to make the call for no payload at each
3078 * command.
3079 */
3080 switch(cmd_ctx->lsm->cmd_type) {
3081 case LTTNG_LIST_SESSIONS:
3082 case LTTNG_LIST_TRACEPOINTS:
3083 case LTTNG_LIST_TRACEPOINT_FIELDS:
3084 case LTTNG_LIST_DOMAINS:
3085 case LTTNG_LIST_CHANNELS:
3086 case LTTNG_LIST_EVENTS:
3087 case LTTNG_LIST_SYSCALLS:
3088 case LTTNG_LIST_TRACKER_PIDS:
3089 break;
3090 default:
3091 /* Setup lttng message with no payload */
3092 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, NULL, 0);
3093 if (ret < 0) {
3094 /* This label does not try to unlock the session */
3095 goto init_setup_error;
3096 }
3097 }
3098
3099 /* Commands that DO NOT need a session. */
3100 switch (cmd_ctx->lsm->cmd_type) {
3101 case LTTNG_CREATE_SESSION:
3102 case LTTNG_CREATE_SESSION_SNAPSHOT:
3103 case LTTNG_CREATE_SESSION_LIVE:
3104 case LTTNG_CALIBRATE:
3105 case LTTNG_LIST_SESSIONS:
3106 case LTTNG_LIST_TRACEPOINTS:
3107 case LTTNG_LIST_SYSCALLS:
3108 case LTTNG_LIST_TRACEPOINT_FIELDS:
3109 case LTTNG_SAVE_SESSION:
3110 need_tracing_session = 0;
3111 break;
3112 default:
3113 DBG("Getting session %s by name", cmd_ctx->lsm->session.name);
3114 /*
3115 * We keep the session list lock across _all_ commands
3116 * for now, because the per-session lock does not
3117 * handle teardown properly.
3118 */
3119 session_lock_list();
3120 cmd_ctx->session = session_find_by_name(cmd_ctx->lsm->session.name);
3121 if (cmd_ctx->session == NULL) {
3122 ret = LTTNG_ERR_SESS_NOT_FOUND;
3123 goto error;
3124 } else {
3125 /* Acquire lock for the session */
3126 session_lock(cmd_ctx->session);
3127 }
3128 break;
3129 }
3130
3131 /*
3132 * Commands that need a valid session but should NOT create one if none
3133 * exists. Instead of creating one and destroying it when the command is
3134 * handled, process that right before so we save some round trip in useless
3135 * code path.
3136 */
3137 switch (cmd_ctx->lsm->cmd_type) {
3138 case LTTNG_DISABLE_CHANNEL:
3139 case LTTNG_DISABLE_EVENT:
3140 switch (cmd_ctx->lsm->domain.type) {
3141 case LTTNG_DOMAIN_KERNEL:
3142 if (!cmd_ctx->session->kernel_session) {
3143 ret = LTTNG_ERR_NO_CHANNEL;
3144 goto error;
3145 }
3146 break;
3147 case LTTNG_DOMAIN_JUL:
3148 case LTTNG_DOMAIN_LOG4J:
3149 case LTTNG_DOMAIN_PYTHON:
3150 case LTTNG_DOMAIN_UST:
3151 if (!cmd_ctx->session->ust_session) {
3152 ret = LTTNG_ERR_NO_CHANNEL;
3153 goto error;
3154 }
3155 break;
3156 default:
3157 ret = LTTNG_ERR_UNKNOWN_DOMAIN;
3158 goto error;
3159 }
3160 default:
3161 break;
3162 }
3163
3164 if (!need_domain) {
3165 goto skip_domain;
3166 }
3167
3168 /*
3169 * Check domain type for specific "pre-action".
3170 */
3171 switch (cmd_ctx->lsm->domain.type) {
3172 case LTTNG_DOMAIN_KERNEL:
3173 if (!is_root) {
3174 ret = LTTNG_ERR_NEED_ROOT_SESSIOND;
3175 goto error;
3176 }
3177
3178 /* Kernel tracer check */
3179 if (kernel_tracer_fd == -1) {
3180 /* Basically, load kernel tracer modules */
3181 ret = init_kernel_tracer();
3182 if (ret != 0) {
3183 goto error;
3184 }
3185 }
3186
3187 /* Consumer is in an ERROR state. Report back to client */
3188 if (uatomic_read(&kernel_consumerd_state) == CONSUMER_ERROR) {
3189 ret = LTTNG_ERR_NO_KERNCONSUMERD;
3190 goto error;
3191 }
3192
3193 /* Need a session for kernel command */
3194 if (need_tracing_session) {
3195 if (cmd_ctx->session->kernel_session == NULL) {
3196 ret = create_kernel_session(cmd_ctx->session);
3197 if (ret < 0) {
3198 ret = LTTNG_ERR_KERN_SESS_FAIL;
3199 goto error;
3200 }
3201 }
3202
3203 /* Start the kernel consumer daemon */
3204 pthread_mutex_lock(&kconsumer_data.pid_mutex);
3205 if (kconsumer_data.pid == 0 &&
3206 cmd_ctx->lsm->cmd_type != LTTNG_REGISTER_CONSUMER) {
3207 pthread_mutex_unlock(&kconsumer_data.pid_mutex);
3208 ret = start_consumerd(&kconsumer_data);
3209 if (ret < 0) {
3210 ret = LTTNG_ERR_KERN_CONSUMER_FAIL;
3211 goto error;
3212 }
3213 uatomic_set(&kernel_consumerd_state, CONSUMER_STARTED);
3214 } else {
3215 pthread_mutex_unlock(&kconsumer_data.pid_mutex);
3216 }
3217
3218 /*
3219 * The consumer was just spawned so we need to add the socket to
3220 * the consumer output of the session if exist.
3221 */
3222 ret = consumer_create_socket(&kconsumer_data,
3223 cmd_ctx->session->kernel_session->consumer);
3224 if (ret < 0) {
3225 goto error;
3226 }
3227 }
3228
3229 break;
3230 case LTTNG_DOMAIN_JUL:
3231 case LTTNG_DOMAIN_LOG4J:
3232 case LTTNG_DOMAIN_PYTHON:
3233 case LTTNG_DOMAIN_UST:
3234 {
3235 if (!ust_app_supported()) {
3236 ret = LTTNG_ERR_NO_UST;
3237 goto error;
3238 }
3239 /* Consumer is in an ERROR state. Report back to client */
3240 if (uatomic_read(&ust_consumerd_state) == CONSUMER_ERROR) {
3241 ret = LTTNG_ERR_NO_USTCONSUMERD;
3242 goto error;
3243 }
3244
3245 if (need_tracing_session) {
3246 /* Create UST session if none exist. */
3247 if (cmd_ctx->session->ust_session == NULL) {
3248 ret = create_ust_session(cmd_ctx->session,
3249 &cmd_ctx->lsm->domain);
3250 if (ret != LTTNG_OK) {
3251 goto error;
3252 }
3253 }
3254
3255 /* Start the UST consumer daemons */
3256 /* 64-bit */
3257 pthread_mutex_lock(&ustconsumer64_data.pid_mutex);
3258 if (consumerd64_bin[0] != '\0' &&
3259 ustconsumer64_data.pid == 0 &&
3260 cmd_ctx->lsm->cmd_type != LTTNG_REGISTER_CONSUMER) {
3261 pthread_mutex_unlock(&ustconsumer64_data.pid_mutex);
3262 ret = start_consumerd(&ustconsumer64_data);
3263 if (ret < 0) {
3264 ret = LTTNG_ERR_UST_CONSUMER64_FAIL;
3265 uatomic_set(&ust_consumerd64_fd, -EINVAL);
3266 goto error;
3267 }
3268
3269 uatomic_set(&ust_consumerd64_fd, ustconsumer64_data.cmd_sock);
3270 uatomic_set(&ust_consumerd_state, CONSUMER_STARTED);
3271 } else {
3272 pthread_mutex_unlock(&ustconsumer64_data.pid_mutex);
3273 }
3274
3275 /*
3276 * Setup socket for consumer 64 bit. No need for atomic access
3277 * since it was set above and can ONLY be set in this thread.
3278 */
3279 ret = consumer_create_socket(&ustconsumer64_data,
3280 cmd_ctx->session->ust_session->consumer);
3281 if (ret < 0) {
3282 goto error;
3283 }
3284
3285 /* 32-bit */
3286 pthread_mutex_lock(&ustconsumer32_data.pid_mutex);
3287 if (consumerd32_bin[0] != '\0' &&
3288 ustconsumer32_data.pid == 0 &&
3289 cmd_ctx->lsm->cmd_type != LTTNG_REGISTER_CONSUMER) {
3290 pthread_mutex_unlock(&ustconsumer32_data.pid_mutex);
3291 ret = start_consumerd(&ustconsumer32_data);
3292 if (ret < 0) {
3293 ret = LTTNG_ERR_UST_CONSUMER32_FAIL;
3294 uatomic_set(&ust_consumerd32_fd, -EINVAL);
3295 goto error;
3296 }
3297
3298 uatomic_set(&ust_consumerd32_fd, ustconsumer32_data.cmd_sock);
3299 uatomic_set(&ust_consumerd_state, CONSUMER_STARTED);
3300 } else {
3301 pthread_mutex_unlock(&ustconsumer32_data.pid_mutex);
3302 }
3303
3304 /*
3305 * Setup socket for consumer 64 bit. No need for atomic access
3306 * since it was set above and can ONLY be set in this thread.
3307 */
3308 ret = consumer_create_socket(&ustconsumer32_data,
3309 cmd_ctx->session->ust_session->consumer);
3310 if (ret < 0) {
3311 goto error;
3312 }
3313 }
3314 break;
3315 }
3316 default:
3317 break;
3318 }
3319 skip_domain:
3320
3321 /* Validate consumer daemon state when start/stop trace command */
3322 if (cmd_ctx->lsm->cmd_type == LTTNG_START_TRACE ||
3323 cmd_ctx->lsm->cmd_type == LTTNG_STOP_TRACE) {
3324 switch (cmd_ctx->lsm->domain.type) {
3325 case LTTNG_DOMAIN_NONE:
3326 break;
3327 case LTTNG_DOMAIN_JUL:
3328 case LTTNG_DOMAIN_LOG4J:
3329 case LTTNG_DOMAIN_PYTHON:
3330 case LTTNG_DOMAIN_UST:
3331 if (uatomic_read(&ust_consumerd_state) != CONSUMER_STARTED) {
3332 ret = LTTNG_ERR_NO_USTCONSUMERD;
3333 goto error;
3334 }
3335 break;
3336 case LTTNG_DOMAIN_KERNEL:
3337 if (uatomic_read(&kernel_consumerd_state) != CONSUMER_STARTED) {
3338 ret = LTTNG_ERR_NO_KERNCONSUMERD;
3339 goto error;
3340 }
3341 break;
3342 default:
3343 ret = LTTNG_ERR_UNKNOWN_DOMAIN;
3344 goto error;
3345 }
3346 }
3347
3348 /*
3349 * Check that the UID or GID match that of the tracing session.
3350 * The root user can interact with all sessions.
3351 */
3352 if (need_tracing_session) {
3353 if (!session_access_ok(cmd_ctx->session,
3354 LTTNG_SOCK_GET_UID_CRED(&cmd_ctx->creds),
3355 LTTNG_SOCK_GET_GID_CRED(&cmd_ctx->creds))) {
3356 ret = LTTNG_ERR_EPERM;
3357 goto error;
3358 }
3359 }
3360
3361 /*
3362 * Send relayd information to consumer as soon as we have a domain and a
3363 * session defined.
3364 */
3365 if (cmd_ctx->session && need_domain) {
3366 /*
3367 * Setup relayd if not done yet. If the relayd information was already
3368 * sent to the consumer, this call will gracefully return.
3369 */
3370 ret = cmd_setup_relayd(cmd_ctx->session);
3371 if (ret != LTTNG_OK) {
3372 goto error;
3373 }
3374 }
3375
3376 /* Process by command type */
3377 switch (cmd_ctx->lsm->cmd_type) {
3378 case LTTNG_ADD_CONTEXT:
3379 {
3380 /*
3381 * An LTTNG_ADD_CONTEXT command might have a supplementary
3382 * payload if the context being added is an application context.
3383 */
3384 if (cmd_ctx->lsm->u.context.ctx.ctx ==
3385 LTTNG_EVENT_CONTEXT_APP_CONTEXT) {
3386 char *provider_name = NULL, *context_name = NULL;
3387 size_t provider_name_len =
3388 cmd_ctx->lsm->u.context.provider_name_len;
3389 size_t context_name_len =
3390 cmd_ctx->lsm->u.context.context_name_len;
3391
3392 if (provider_name_len == 0 || context_name_len == 0) {
3393 /*
3394 * Application provider and context names MUST
3395 * be provided.
3396 */
3397 ret = -LTTNG_ERR_INVALID;
3398 goto error;
3399 }
3400
3401 provider_name = zmalloc(provider_name_len + 1);
3402 if (!provider_name) {
3403 ret = -LTTNG_ERR_NOMEM;
3404 goto error;
3405 }
3406 cmd_ctx->lsm->u.context.ctx.u.app_ctx.provider_name =
3407 provider_name;
3408
3409 context_name = zmalloc(context_name_len + 1);
3410 if (!context_name) {
3411 ret = -LTTNG_ERR_NOMEM;
3412 goto error_add_context;
3413 }
3414 cmd_ctx->lsm->u.context.ctx.u.app_ctx.ctx_name =
3415 context_name;
3416
3417 ret = lttcomm_recv_unix_sock(sock, provider_name,
3418 provider_name_len);
3419 if (ret < 0) {
3420 goto error_add_context;
3421 }
3422
3423 ret = lttcomm_recv_unix_sock(sock, context_name,
3424 context_name_len);
3425 if (ret < 0) {
3426 goto error_add_context;
3427 }
3428 }
3429
3430 /*
3431 * cmd_add_context assumes ownership of the provider and context
3432 * names.
3433 */
3434 ret = cmd_add_context(cmd_ctx->session,
3435 cmd_ctx->lsm->domain.type,
3436 cmd_ctx->lsm->u.context.channel_name,
3437 &cmd_ctx->lsm->u.context.ctx,
3438 kernel_poll_pipe[1]);
3439
3440 cmd_ctx->lsm->u.context.ctx.u.app_ctx.provider_name = NULL;
3441 cmd_ctx->lsm->u.context.ctx.u.app_ctx.ctx_name = NULL;
3442 error_add_context:
3443 free(cmd_ctx->lsm->u.context.ctx.u.app_ctx.provider_name);
3444 free(cmd_ctx->lsm->u.context.ctx.u.app_ctx.ctx_name);
3445 if (ret < 0) {
3446 goto error;
3447 }
3448 break;
3449 }
3450 case LTTNG_DISABLE_CHANNEL:
3451 {
3452 ret = cmd_disable_channel(cmd_ctx->session, cmd_ctx->lsm->domain.type,
3453 cmd_ctx->lsm->u.disable.channel_name);
3454 break;
3455 }
3456 case LTTNG_DISABLE_EVENT:
3457 {
3458
3459 /*
3460 * FIXME: handle filter; for now we just receive the filter's
3461 * bytecode along with the filter expression which are sent by
3462 * liblttng-ctl and discard them.
3463 *
3464 * This fixes an issue where the client may block while sending
3465 * the filter payload and encounter an error because the session
3466 * daemon closes the socket without ever handling this data.
3467 */
3468 size_t count = cmd_ctx->lsm->u.disable.expression_len +
3469 cmd_ctx->lsm->u.disable.bytecode_len;
3470
3471 if (count) {
3472 char data[LTTNG_FILTER_MAX_LEN];
3473
3474 DBG("Discarding disable event command payload of size %zu", count);
3475 while (count) {
3476 ret = lttcomm_recv_unix_sock(sock, data,
3477 count > sizeof(data) ? sizeof(data) : count);
3478 if (ret < 0) {
3479 goto error;
3480 }
3481
3482 count -= (size_t) ret;
3483 }
3484 }
3485 /* FIXME: passing packed structure to non-packed pointer */
3486 ret = cmd_disable_event(cmd_ctx->session, cmd_ctx->lsm->domain.type,
3487 cmd_ctx->lsm->u.disable.channel_name,
3488 &cmd_ctx->lsm->u.disable.event);
3489 break;
3490 }
3491 case LTTNG_ENABLE_CHANNEL:
3492 {
3493 ret = cmd_enable_channel(cmd_ctx->session, &cmd_ctx->lsm->domain,
3494 &cmd_ctx->lsm->u.channel.chan, kernel_poll_pipe[1]);
3495 break;
3496 }
3497 case LTTNG_TRACK_PID:
3498 {
3499 ret = cmd_track_pid(cmd_ctx->session,
3500 cmd_ctx->lsm->domain.type,
3501 cmd_ctx->lsm->u.pid_tracker.pid);
3502 break;
3503 }
3504 case LTTNG_UNTRACK_PID:
3505 {
3506 ret = cmd_untrack_pid(cmd_ctx->session,
3507 cmd_ctx->lsm->domain.type,
3508 cmd_ctx->lsm->u.pid_tracker.pid);
3509 break;
3510 }
3511 case LTTNG_ENABLE_EVENT:
3512 {
3513 struct lttng_event_exclusion *exclusion = NULL;
3514 struct lttng_filter_bytecode *bytecode = NULL;
3515 char *filter_expression = NULL;
3516
3517 /* Handle exclusion events and receive it from the client. */
3518 if (cmd_ctx->lsm->u.enable.exclusion_count > 0) {
3519 size_t count = cmd_ctx->lsm->u.enable.exclusion_count;
3520
3521 exclusion = zmalloc(sizeof(struct lttng_event_exclusion) +
3522 (count * LTTNG_SYMBOL_NAME_LEN));
3523 if (!exclusion) {
3524 ret = LTTNG_ERR_EXCLUSION_NOMEM;
3525 goto error;
3526 }
3527
3528 DBG("Receiving var len exclusion event list from client ...");
3529 exclusion->count = count;
3530 ret = lttcomm_recv_unix_sock(sock, exclusion->names,
3531 count * LTTNG_SYMBOL_NAME_LEN);
3532 if (ret <= 0) {
3533 DBG("Nothing recv() from client var len data... continuing");
3534 *sock_error = 1;
3535 free(exclusion);
3536 ret = LTTNG_ERR_EXCLUSION_INVAL;
3537 goto error;
3538 }
3539 }
3540
3541 /* Get filter expression from client. */
3542 if (cmd_ctx->lsm->u.enable.expression_len > 0) {
3543 size_t expression_len =
3544 cmd_ctx->lsm->u.enable.expression_len;
3545
3546 if (expression_len > LTTNG_FILTER_MAX_LEN) {
3547 ret = LTTNG_ERR_FILTER_INVAL;
3548 free(exclusion);
3549 goto error;
3550 }
3551
3552 filter_expression = zmalloc(expression_len);
3553 if (!filter_expression) {
3554 free(exclusion);
3555 ret = LTTNG_ERR_FILTER_NOMEM;
3556 goto error;
3557 }
3558
3559 /* Receive var. len. data */
3560 DBG("Receiving var len filter's expression from client ...");
3561 ret = lttcomm_recv_unix_sock(sock, filter_expression,
3562 expression_len);
3563 if (ret <= 0) {
3564 DBG("Nothing recv() from client car len data... continuing");
3565 *sock_error = 1;
3566 free(filter_expression);
3567 free(exclusion);
3568 ret = LTTNG_ERR_FILTER_INVAL;
3569 goto error;
3570 }
3571 }
3572
3573 /* Handle filter and get bytecode from client. */
3574 if (cmd_ctx->lsm->u.enable.bytecode_len > 0) {
3575 size_t bytecode_len = cmd_ctx->lsm->u.enable.bytecode_len;
3576
3577 if (bytecode_len > LTTNG_FILTER_MAX_LEN) {
3578 ret = LTTNG_ERR_FILTER_INVAL;
3579 free(filter_expression);
3580 free(exclusion);
3581 goto error;
3582 }
3583
3584 bytecode = zmalloc(bytecode_len);
3585 if (!bytecode) {
3586 free(filter_expression);
3587 free(exclusion);
3588 ret = LTTNG_ERR_FILTER_NOMEM;
3589 goto error;
3590 }
3591
3592 /* Receive var. len. data */
3593 DBG("Receiving var len filter's bytecode from client ...");
3594 ret = lttcomm_recv_unix_sock(sock, bytecode, bytecode_len);
3595 if (ret <= 0) {
3596 DBG("Nothing recv() from client car len data... continuing");
3597 *sock_error = 1;
3598 free(filter_expression);
3599 free(bytecode);
3600 free(exclusion);
3601 ret = LTTNG_ERR_FILTER_INVAL;
3602 goto error;
3603 }
3604
3605 if ((bytecode->len + sizeof(*bytecode)) != bytecode_len) {
3606 free(filter_expression);
3607 free(bytecode);
3608 free(exclusion);
3609 ret = LTTNG_ERR_FILTER_INVAL;
3610 goto error;
3611 }
3612 }
3613
3614 ret = cmd_enable_event(cmd_ctx->session, &cmd_ctx->lsm->domain,
3615 cmd_ctx->lsm->u.enable.channel_name,
3616 &cmd_ctx->lsm->u.enable.event,
3617 filter_expression, bytecode, exclusion,
3618 kernel_poll_pipe[1]);
3619 break;
3620 }
3621 case LTTNG_LIST_TRACEPOINTS:
3622 {
3623 struct lttng_event *events;
3624 ssize_t nb_events;
3625
3626 session_lock_list();
3627 nb_events = cmd_list_tracepoints(cmd_ctx->lsm->domain.type, &events);
3628 session_unlock_list();
3629 if (nb_events < 0) {
3630 /* Return value is a negative lttng_error_code. */
3631 ret = -nb_events;
3632 goto error;
3633 }
3634
3635 /*
3636 * Setup lttng message with payload size set to the event list size in
3637 * bytes and then copy list into the llm payload.
3638 */
3639 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, events,
3640 sizeof(struct lttng_event) * nb_events);
3641 free(events);
3642
3643 if (ret < 0) {
3644 goto setup_error;
3645 }
3646
3647 ret = LTTNG_OK;
3648 break;
3649 }
3650 case LTTNG_LIST_TRACEPOINT_FIELDS:
3651 {
3652 struct lttng_event_field *fields;
3653 ssize_t nb_fields;
3654
3655 session_lock_list();
3656 nb_fields = cmd_list_tracepoint_fields(cmd_ctx->lsm->domain.type,
3657 &fields);
3658 session_unlock_list();
3659 if (nb_fields < 0) {
3660 /* Return value is a negative lttng_error_code. */
3661 ret = -nb_fields;
3662 goto error;
3663 }
3664
3665 /*
3666 * Setup lttng message with payload size set to the event list size in
3667 * bytes and then copy list into the llm payload.
3668 */
3669 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, fields,
3670 sizeof(struct lttng_event_field) * nb_fields);
3671 free(fields);
3672
3673 if (ret < 0) {
3674 goto setup_error;
3675 }
3676
3677 ret = LTTNG_OK;
3678 break;
3679 }
3680 case LTTNG_LIST_SYSCALLS:
3681 {
3682 struct lttng_event *events;
3683 ssize_t nb_events;
3684
3685 nb_events = cmd_list_syscalls(&events);
3686 if (nb_events < 0) {
3687 /* Return value is a negative lttng_error_code. */
3688 ret = -nb_events;
3689 goto error;
3690 }
3691
3692 /*
3693 * Setup lttng message with payload size set to the event list size in
3694 * bytes and then copy list into the llm payload.
3695 */
3696 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, events,
3697 sizeof(struct lttng_event) * nb_events);
3698 free(events);
3699
3700 if (ret < 0) {
3701 goto setup_error;
3702 }
3703
3704 ret = LTTNG_OK;
3705 break;
3706 }
3707 case LTTNG_LIST_TRACKER_PIDS:
3708 {
3709 int32_t *pids = NULL;
3710 ssize_t nr_pids;
3711
3712 nr_pids = cmd_list_tracker_pids(cmd_ctx->session,
3713 cmd_ctx->lsm->domain.type, &pids);
3714 if (nr_pids < 0) {
3715 /* Return value is a negative lttng_error_code. */
3716 ret = -nr_pids;
3717 goto error;
3718 }
3719
3720 /*
3721 * Setup lttng message with payload size set to the event list size in
3722 * bytes and then copy list into the llm payload.
3723 */
3724 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, pids,
3725 sizeof(int32_t) * nr_pids);
3726 free(pids);
3727
3728 if (ret < 0) {
3729 goto setup_error;
3730 }
3731
3732 ret = LTTNG_OK;
3733 break;
3734 }
3735 case LTTNG_SET_CONSUMER_URI:
3736 {
3737 size_t nb_uri, len;
3738 struct lttng_uri *uris;
3739
3740 nb_uri = cmd_ctx->lsm->u.uri.size;
3741 len = nb_uri * sizeof(struct lttng_uri);
3742
3743 if (nb_uri == 0) {
3744 ret = LTTNG_ERR_INVALID;
3745 goto error;
3746 }
3747
3748 uris = zmalloc(len);
3749 if (uris == NULL) {
3750 ret = LTTNG_ERR_FATAL;
3751 goto error;
3752 }
3753
3754 /* Receive variable len data */
3755 DBG("Receiving %zu URI(s) from client ...", nb_uri);
3756 ret = lttcomm_recv_unix_sock(sock, uris, len);
3757 if (ret <= 0) {
3758 DBG("No URIs received from client... continuing");
3759 *sock_error = 1;
3760 ret = LTTNG_ERR_SESSION_FAIL;
3761 free(uris);
3762 goto error;
3763 }
3764
3765 ret = cmd_set_consumer_uri(cmd_ctx->session, nb_uri, uris);
3766 free(uris);
3767 if (ret != LTTNG_OK) {
3768 goto error;
3769 }
3770
3771
3772 break;
3773 }
3774 case LTTNG_START_TRACE:
3775 {
3776 ret = cmd_start_trace(cmd_ctx->session);
3777 break;
3778 }
3779 case LTTNG_STOP_TRACE:
3780 {
3781 ret = cmd_stop_trace(cmd_ctx->session);
3782 break;
3783 }
3784 case LTTNG_CREATE_SESSION:
3785 {
3786 size_t nb_uri, len;
3787 struct lttng_uri *uris = NULL;
3788
3789 nb_uri = cmd_ctx->lsm->u.uri.size;
3790 len = nb_uri * sizeof(struct lttng_uri);
3791
3792 if (nb_uri > 0) {
3793 uris = zmalloc(len);
3794 if (uris == NULL) {
3795 ret = LTTNG_ERR_FATAL;
3796 goto error;
3797 }
3798
3799 /* Receive variable len data */
3800 DBG("Waiting for %zu URIs from client ...", nb_uri);
3801 ret = lttcomm_recv_unix_sock(sock, uris, len);
3802 if (ret <= 0) {
3803 DBG("No URIs received from client... continuing");
3804 *sock_error = 1;
3805 ret = LTTNG_ERR_SESSION_FAIL;
3806 free(uris);
3807 goto error;
3808 }
3809
3810 if (nb_uri == 1 && uris[0].dtype != LTTNG_DST_PATH) {
3811 DBG("Creating session with ONE network URI is a bad call");
3812 ret = LTTNG_ERR_SESSION_FAIL;
3813 free(uris);
3814 goto error;
3815 }
3816 }
3817
3818 ret = cmd_create_session_uri(cmd_ctx->lsm->session.name, uris, nb_uri,
3819 &cmd_ctx->creds, 0);
3820
3821 free(uris);
3822
3823 break;
3824 }
3825 case LTTNG_DESTROY_SESSION:
3826 {
3827 ret = cmd_destroy_session(cmd_ctx->session, kernel_poll_pipe[1]);
3828
3829 /* Set session to NULL so we do not unlock it after free. */
3830 cmd_ctx->session = NULL;
3831 break;
3832 }
3833 case LTTNG_LIST_DOMAINS:
3834 {
3835 ssize_t nb_dom;
3836 struct lttng_domain *domains = NULL;
3837
3838 nb_dom = cmd_list_domains(cmd_ctx->session, &domains);
3839 if (nb_dom < 0) {
3840 /* Return value is a negative lttng_error_code. */
3841 ret = -nb_dom;
3842 goto error;
3843 }
3844
3845 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, domains,
3846 nb_dom * sizeof(struct lttng_domain));
3847 free(domains);
3848
3849 if (ret < 0) {
3850 goto setup_error;
3851 }
3852
3853 ret = LTTNG_OK;
3854 break;
3855 }
3856 case LTTNG_LIST_CHANNELS:
3857 {
3858 ssize_t payload_size;
3859 struct lttng_channel *channels = NULL;
3860
3861 payload_size = cmd_list_channels(cmd_ctx->lsm->domain.type,
3862 cmd_ctx->session, &channels);
3863 if (payload_size < 0) {
3864 /* Return value is a negative lttng_error_code. */
3865 ret = -payload_size;
3866 goto error;
3867 }
3868
3869 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, channels,
3870 payload_size);
3871 free(channels);
3872
3873 if (ret < 0) {
3874 goto setup_error;
3875 }
3876
3877 ret = LTTNG_OK;
3878 break;
3879 }
3880 case LTTNG_LIST_EVENTS:
3881 {
3882 ssize_t nb_event;
3883 struct lttng_event *events = NULL;
3884 struct lttcomm_event_command_header cmd_header;
3885 size_t total_size;
3886
3887 memset(&cmd_header, 0, sizeof(cmd_header));
3888 /* Extended infos are included at the end of events */
3889 nb_event = cmd_list_events(cmd_ctx->lsm->domain.type,
3890 cmd_ctx->session, cmd_ctx->lsm->u.list.channel_name,
3891 &events, &total_size);
3892
3893 if (nb_event < 0) {
3894 /* Return value is a negative lttng_error_code. */
3895 ret = -nb_event;
3896 goto error;
3897 }
3898
3899 cmd_header.nb_events = nb_event;
3900 ret = setup_lttng_msg(cmd_ctx, events, total_size,
3901 &cmd_header, sizeof(cmd_header));
3902 free(events);
3903
3904 if (ret < 0) {
3905 goto setup_error;
3906 }
3907
3908 ret = LTTNG_OK;
3909 break;
3910 }
3911 case LTTNG_LIST_SESSIONS:
3912 {
3913 unsigned int nr_sessions;
3914 void *sessions_payload;
3915 size_t payload_len;
3916
3917 session_lock_list();
3918 nr_sessions = lttng_sessions_count(
3919 LTTNG_SOCK_GET_UID_CRED(&cmd_ctx->creds),
3920 LTTNG_SOCK_GET_GID_CRED(&cmd_ctx->creds));
3921 payload_len = sizeof(struct lttng_session) * nr_sessions;
3922 sessions_payload = zmalloc(payload_len);
3923
3924 if (!sessions_payload) {
3925 session_unlock_list();
3926 ret = -ENOMEM;
3927 goto setup_error;
3928 }
3929
3930 cmd_list_lttng_sessions(sessions_payload,
3931 LTTNG_SOCK_GET_UID_CRED(&cmd_ctx->creds),
3932 LTTNG_SOCK_GET_GID_CRED(&cmd_ctx->creds));
3933 session_unlock_list();
3934
3935 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, sessions_payload,
3936 payload_len);
3937 free(sessions_payload);
3938
3939 if (ret < 0) {
3940 goto setup_error;
3941 }
3942
3943 ret = LTTNG_OK;
3944 break;
3945 }
3946 case LTTNG_CALIBRATE:
3947 {
3948 ret = cmd_calibrate(cmd_ctx->lsm->domain.type,
3949 &cmd_ctx->lsm->u.calibrate);
3950 break;
3951 }
3952 case LTTNG_REGISTER_CONSUMER:
3953 {
3954 struct consumer_data *cdata;
3955
3956 switch (cmd_ctx->lsm->domain.type) {
3957 case LTTNG_DOMAIN_KERNEL:
3958 cdata = &kconsumer_data;
3959 break;
3960 default:
3961 ret = LTTNG_ERR_UND;
3962 goto error;
3963 }
3964
3965 ret = cmd_register_consumer(cmd_ctx->session, cmd_ctx->lsm->domain.type,
3966 cmd_ctx->lsm->u.reg.path, cdata);
3967 break;
3968 }
3969 case LTTNG_DATA_PENDING:
3970 {
3971 int pending_ret;
3972 uint8_t pending_ret_byte;
3973
3974 pending_ret = cmd_data_pending(cmd_ctx->session);
3975
3976 /*
3977 * FIXME
3978 *
3979 * This function may returns 0 or 1 to indicate whether or not
3980 * there is data pending. In case of error, it should return an
3981 * LTTNG_ERR code. However, some code paths may still return
3982 * a nondescript error code, which we handle by returning an
3983 * "unknown" error.
3984 */
3985 if (pending_ret == 0 || pending_ret == 1) {
3986 /*
3987 * ret will be set to LTTNG_OK at the end of
3988 * this function.
3989 */
3990 } else if (pending_ret < 0) {
3991 ret = LTTNG_ERR_UNK;
3992 goto setup_error;
3993 } else {
3994 ret = pending_ret;
3995 goto setup_error;
3996 }
3997
3998 pending_ret_byte = (uint8_t) pending_ret;
3999
4000 /* 1 byte to return whether or not data is pending */
4001 ret = setup_lttng_msg_no_cmd_header(cmd_ctx,
4002 &pending_ret_byte, 1);
4003
4004 if (ret < 0) {
4005 goto setup_error;
4006 }
4007
4008 ret = LTTNG_OK;
4009 break;
4010 }
4011 case LTTNG_SNAPSHOT_ADD_OUTPUT:
4012 {
4013 struct lttcomm_lttng_output_id reply;
4014
4015 ret = cmd_snapshot_add_output(cmd_ctx->session,
4016 &cmd_ctx->lsm->u.snapshot_output.output, &reply.id);
4017 if (ret != LTTNG_OK) {
4018 goto error;
4019 }
4020
4021 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, &reply,
4022 sizeof(reply));
4023 if (ret < 0) {
4024 goto setup_error;
4025 }
4026
4027 /* Copy output list into message payload */
4028 ret = LTTNG_OK;
4029 break;
4030 }
4031 case LTTNG_SNAPSHOT_DEL_OUTPUT:
4032 {
4033 ret = cmd_snapshot_del_output(cmd_ctx->session,
4034 &cmd_ctx->lsm->u.snapshot_output.output);
4035 break;
4036 }
4037 case LTTNG_SNAPSHOT_LIST_OUTPUT:
4038 {
4039 ssize_t nb_output;
4040 struct lttng_snapshot_output *outputs = NULL;
4041
4042 nb_output = cmd_snapshot_list_outputs(cmd_ctx->session, &outputs);
4043 if (nb_output < 0) {
4044 ret = -nb_output;
4045 goto error;
4046 }
4047
4048 assert((nb_output > 0 && outputs) || nb_output == 0);
4049 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, outputs,
4050 nb_output * sizeof(struct lttng_snapshot_output));
4051 free(outputs);
4052
4053 if (ret < 0) {
4054 goto setup_error;
4055 }
4056
4057 ret = LTTNG_OK;
4058 break;
4059 }
4060 case LTTNG_SNAPSHOT_RECORD:
4061 {
4062 ret = cmd_snapshot_record(cmd_ctx->session,
4063 &cmd_ctx->lsm->u.snapshot_record.output,
4064 cmd_ctx->lsm->u.snapshot_record.wait);
4065 break;
4066 }
4067 case LTTNG_CREATE_SESSION_SNAPSHOT:
4068 {
4069 size_t nb_uri, len;
4070 struct lttng_uri *uris = NULL;
4071
4072 nb_uri = cmd_ctx->lsm->u.uri.size;
4073 len = nb_uri * sizeof(struct lttng_uri);
4074
4075 if (nb_uri > 0) {
4076 uris = zmalloc(len);
4077 if (uris == NULL) {
4078 ret = LTTNG_ERR_FATAL;
4079 goto error;
4080 }
4081
4082 /* Receive variable len data */
4083 DBG("Waiting for %zu URIs from client ...", nb_uri);
4084 ret = lttcomm_recv_unix_sock(sock, uris, len);
4085 if (ret <= 0) {
4086 DBG("No URIs received from client... continuing");
4087 *sock_error = 1;
4088 ret = LTTNG_ERR_SESSION_FAIL;
4089 free(uris);
4090 goto error;
4091 }
4092
4093 if (nb_uri == 1 && uris[0].dtype != LTTNG_DST_PATH) {
4094 DBG("Creating session with ONE network URI is a bad call");
4095 ret = LTTNG_ERR_SESSION_FAIL;
4096 free(uris);
4097 goto error;
4098 }
4099 }
4100
4101 ret = cmd_create_session_snapshot(cmd_ctx->lsm->session.name, uris,
4102 nb_uri, &cmd_ctx->creds);
4103 free(uris);
4104 break;
4105 }
4106 case LTTNG_CREATE_SESSION_LIVE:
4107 {
4108 size_t nb_uri, len;
4109 struct lttng_uri *uris = NULL;
4110
4111 nb_uri = cmd_ctx->lsm->u.uri.size;
4112 len = nb_uri * sizeof(struct lttng_uri);
4113
4114 if (nb_uri > 0) {
4115 uris = zmalloc(len);
4116 if (uris == NULL) {
4117 ret = LTTNG_ERR_FATAL;
4118 goto error;
4119 }
4120
4121 /* Receive variable len data */
4122 DBG("Waiting for %zu URIs from client ...", nb_uri);
4123 ret = lttcomm_recv_unix_sock(sock, uris, len);
4124 if (ret <= 0) {
4125 DBG("No URIs received from client... continuing");
4126 *sock_error = 1;
4127 ret = LTTNG_ERR_SESSION_FAIL;
4128 free(uris);
4129 goto error;
4130 }
4131
4132 if (nb_uri == 1 && uris[0].dtype != LTTNG_DST_PATH) {
4133 DBG("Creating session with ONE network URI is a bad call");
4134 ret = LTTNG_ERR_SESSION_FAIL;
4135 free(uris);
4136 goto error;
4137 }
4138 }
4139
4140 ret = cmd_create_session_uri(cmd_ctx->lsm->session.name, uris,
4141 nb_uri, &cmd_ctx->creds, cmd_ctx->lsm->u.session_live.timer_interval);
4142 free(uris);
4143 break;
4144 }
4145 case LTTNG_SAVE_SESSION:
4146 {
4147 ret = cmd_save_sessions(&cmd_ctx->lsm->u.save_session.attr,
4148 &cmd_ctx->creds);
4149 break;
4150 }
4151 case LTTNG_SET_SESSION_SHM_PATH:
4152 {
4153 ret = cmd_set_session_shm_path(cmd_ctx->session,
4154 cmd_ctx->lsm->u.set_shm_path.shm_path);
4155 break;
4156 }
4157 case LTTNG_METADATA_REGENERATE:
4158 {
4159 ret = cmd_metadata_regenerate(cmd_ctx->session);
4160 break;
4161 }
4162 default:
4163 ret = LTTNG_ERR_UND;
4164 break;
4165 }
4166
4167 error:
4168 if (cmd_ctx->llm == NULL) {
4169 DBG("Missing llm structure. Allocating one.");
4170 if (setup_lttng_msg_no_cmd_header(cmd_ctx, NULL, 0) < 0) {
4171 goto setup_error;
4172 }
4173 }
4174 /* Set return code */
4175 cmd_ctx->llm->ret_code = ret;
4176 setup_error:
4177 if (cmd_ctx->session) {
4178 session_unlock(cmd_ctx->session);
4179 }
4180 if (need_tracing_session) {
4181 session_unlock_list();
4182 }
4183 init_setup_error:
4184 assert(!rcu_read_ongoing());
4185 return ret;
4186 }
4187
4188 /*
4189 * Thread managing health check socket.
4190 */
4191 static void *thread_manage_health(void *data)
4192 {
4193 int sock = -1, new_sock = -1, ret, i, pollfd, err = -1;
4194 uint32_t revents, nb_fd;
4195 struct lttng_poll_event events;
4196 struct health_comm_msg msg;
4197 struct health_comm_reply reply;
4198
4199 DBG("[thread] Manage health check started");
4200
4201 rcu_register_thread();
4202
4203 /* We might hit an error path before this is created. */
4204 lttng_poll_init(&events);
4205
4206 /* Create unix socket */
4207 sock = lttcomm_create_unix_sock(health_unix_sock_path);
4208 if (sock < 0) {
4209 ERR("Unable to create health check Unix socket");
4210 goto error;
4211 }
4212
4213 if (is_root) {
4214 /* lttng health client socket path permissions */
4215 ret = chown(health_unix_sock_path, 0,
4216 utils_get_group_id(tracing_group_name));
4217 if (ret < 0) {
4218 ERR("Unable to set group on %s", health_unix_sock_path);
4219 PERROR("chown");
4220 goto error;
4221 }
4222
4223 ret = chmod(health_unix_sock_path,
4224 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
4225 if (ret < 0) {
4226 ERR("Unable to set permissions on %s", health_unix_sock_path);
4227 PERROR("chmod");
4228 goto error;
4229 }
4230 }
4231
4232 /*
4233 * Set the CLOEXEC flag. Return code is useless because either way, the
4234 * show must go on.
4235 */
4236 (void) utils_set_fd_cloexec(sock);
4237
4238 ret = lttcomm_listen_unix_sock(sock);
4239 if (ret < 0) {
4240 goto error;
4241 }
4242
4243 /*
4244 * Pass 2 as size here for the thread quit pipe and client_sock. Nothing
4245 * more will be added to this poll set.
4246 */
4247 ret = sessiond_set_thread_pollset(&events, 2);
4248 if (ret < 0) {
4249 goto error;
4250 }
4251
4252 /* Add the application registration socket */
4253 ret = lttng_poll_add(&events, sock, LPOLLIN | LPOLLPRI);
4254 if (ret < 0) {
4255 goto error;
4256 }
4257
4258 sessiond_notify_ready();
4259
4260 while (1) {
4261 DBG("Health check ready");
4262
4263 /* Inifinite blocking call, waiting for transmission */
4264 restart:
4265 ret = lttng_poll_wait(&events, -1);
4266 if (ret < 0) {
4267 /*
4268 * Restart interrupted system call.
4269 */
4270 if (errno == EINTR) {
4271 goto restart;
4272 }
4273 goto error;
4274 }
4275
4276 nb_fd = ret;
4277
4278 for (i = 0; i < nb_fd; i++) {
4279 /* Fetch once the poll data */
4280 revents = LTTNG_POLL_GETEV(&events, i);
4281 pollfd = LTTNG_POLL_GETFD(&events, i);
4282
4283 if (!revents) {
4284 /* No activity for this FD (poll implementation). */
4285 continue;
4286 }
4287
4288 /* Thread quit pipe has been closed. Killing thread. */
4289 ret = sessiond_check_thread_quit_pipe(pollfd, revents);
4290 if (ret) {
4291 err = 0;
4292 goto exit;
4293 }
4294
4295 /* Event on the registration socket */
4296 if (pollfd == sock) {
4297 if (revents & LPOLLIN) {
4298 continue;
4299 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
4300 ERR("Health socket poll error");
4301 goto error;
4302 } else {
4303 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
4304 goto error;
4305 }
4306 }
4307 }
4308
4309 new_sock = lttcomm_accept_unix_sock(sock);
4310 if (new_sock < 0) {
4311 goto error;
4312 }
4313
4314 /*
4315 * Set the CLOEXEC flag. Return code is useless because either way, the
4316 * show must go on.
4317 */
4318 (void) utils_set_fd_cloexec(new_sock);
4319
4320 DBG("Receiving data from client for health...");
4321 ret = lttcomm_recv_unix_sock(new_sock, (void *)&msg, sizeof(msg));
4322 if (ret <= 0) {
4323 DBG("Nothing recv() from client... continuing");
4324 ret = close(new_sock);
4325 if (ret) {
4326 PERROR("close");
4327 }
4328 new_sock = -1;
4329 continue;
4330 }
4331
4332 rcu_thread_online();
4333
4334 memset(&reply, 0, sizeof(reply));
4335 for (i = 0; i < NR_HEALTH_SESSIOND_TYPES; i++) {
4336 /*
4337 * health_check_state returns 0 if health is
4338 * bad.
4339 */
4340 if (!health_check_state(health_sessiond, i)) {
4341 reply.ret_code |= 1ULL << i;
4342 }
4343 }
4344
4345 DBG2("Health check return value %" PRIx64, reply.ret_code);
4346
4347 ret = send_unix_sock(new_sock, (void *) &reply, sizeof(reply));
4348 if (ret < 0) {
4349 ERR("Failed to send health data back to client");
4350 }
4351
4352 /* End of transmission */
4353 ret = close(new_sock);
4354 if (ret) {
4355 PERROR("close");
4356 }
4357 new_sock = -1;
4358 }
4359
4360 exit:
4361 error:
4362 if (err) {
4363 ERR("Health error occurred in %s", __func__);
4364 }
4365 DBG("Health check thread dying");
4366 unlink(health_unix_sock_path);
4367 if (sock >= 0) {
4368 ret = close(sock);
4369 if (ret) {
4370 PERROR("close");
4371 }
4372 }
4373
4374 lttng_poll_clean(&events);
4375
4376 rcu_unregister_thread();
4377 return NULL;
4378 }
4379
4380 /*
4381 * This thread manage all clients request using the unix client socket for
4382 * communication.
4383 */
4384 static void *thread_manage_clients(void *data)
4385 {
4386 int sock = -1, ret, i, pollfd, err = -1;
4387 int sock_error;
4388 uint32_t revents, nb_fd;
4389 struct command_ctx *cmd_ctx = NULL;
4390 struct lttng_poll_event events;
4391
4392 DBG("[thread] Manage client started");
4393
4394 rcu_register_thread();
4395
4396 health_register(health_sessiond, HEALTH_SESSIOND_TYPE_CMD);
4397
4398 health_code_update();
4399
4400 ret = lttcomm_listen_unix_sock(client_sock);
4401 if (ret < 0) {
4402 goto error_listen;
4403 }
4404
4405 /*
4406 * Pass 2 as size here for the thread quit pipe and client_sock. Nothing
4407 * more will be added to this poll set.
4408 */
4409 ret = sessiond_set_thread_pollset(&events, 2);
4410 if (ret < 0) {
4411 goto error_create_poll;
4412 }
4413
4414 /* Add the application registration socket */
4415 ret = lttng_poll_add(&events, client_sock, LPOLLIN | LPOLLPRI);
4416 if (ret < 0) {
4417 goto error;
4418 }
4419
4420 sessiond_notify_ready();
4421 ret = sem_post(&load_info->message_thread_ready);
4422 if (ret) {
4423 PERROR("sem_post message_thread_ready");
4424 goto error;
4425 }
4426
4427 /* This testpoint is after we signal readiness to the parent. */
4428 if (testpoint(sessiond_thread_manage_clients)) {
4429 goto error;
4430 }
4431
4432 if (testpoint(sessiond_thread_manage_clients_before_loop)) {
4433 goto error;
4434 }
4435
4436 health_code_update();
4437
4438 while (1) {
4439 DBG("Accepting client command ...");
4440
4441 /* Inifinite blocking call, waiting for transmission */
4442 restart:
4443 health_poll_entry();
4444 ret = lttng_poll_wait(&events, -1);
4445 health_poll_exit();
4446 if (ret < 0) {
4447 /*
4448 * Restart interrupted system call.
4449 */
4450 if (errno == EINTR) {
4451 goto restart;
4452 }
4453 goto error;
4454 }
4455
4456 nb_fd = ret;
4457
4458 for (i = 0; i < nb_fd; i++) {
4459 /* Fetch once the poll data */
4460 revents = LTTNG_POLL_GETEV(&events, i);
4461 pollfd = LTTNG_POLL_GETFD(&events, i);
4462
4463 health_code_update();
4464
4465 if (!revents) {
4466 /* No activity for this FD (poll implementation). */
4467 continue;
4468 }
4469
4470 /* Thread quit pipe has been closed. Killing thread. */
4471 ret = sessiond_check_thread_quit_pipe(pollfd, revents);
4472 if (ret) {
4473 err = 0;
4474 goto exit;
4475 }
4476
4477 /* Event on the registration socket */
4478 if (pollfd == client_sock) {
4479 if (revents & LPOLLIN) {
4480 continue;
4481 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
4482 ERR("Client socket poll error");
4483 goto error;
4484 } else {
4485 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
4486 goto error;
4487 }
4488 }
4489 }
4490
4491 DBG("Wait for client response");
4492
4493 health_code_update();
4494
4495 sock = lttcomm_accept_unix_sock(client_sock);
4496 if (sock < 0) {
4497 goto error;
4498 }
4499
4500 /*
4501 * Set the CLOEXEC flag. Return code is useless because either way, the
4502 * show must go on.
4503 */
4504 (void) utils_set_fd_cloexec(sock);
4505
4506 /* Set socket option for credentials retrieval */
4507 ret = lttcomm_setsockopt_creds_unix_sock(sock);
4508 if (ret < 0) {
4509 goto error;
4510 }
4511
4512 /* Allocate context command to process the client request */
4513 cmd_ctx = zmalloc(sizeof(struct command_ctx));
4514 if (cmd_ctx == NULL) {
4515 PERROR("zmalloc cmd_ctx");
4516 goto error;
4517 }
4518
4519 /* Allocate data buffer for reception */
4520 cmd_ctx->lsm = zmalloc(sizeof(struct lttcomm_session_msg));
4521 if (cmd_ctx->lsm == NULL) {
4522 PERROR("zmalloc cmd_ctx->lsm");
4523 goto error;
4524 }
4525
4526 cmd_ctx->llm = NULL;
4527 cmd_ctx->session = NULL;
4528
4529 health_code_update();
4530
4531 /*
4532 * Data is received from the lttng client. The struct
4533 * lttcomm_session_msg (lsm) contains the command and data request of
4534 * the client.
4535 */
4536 DBG("Receiving data from client ...");
4537 ret = lttcomm_recv_creds_unix_sock(sock, cmd_ctx->lsm,
4538 sizeof(struct lttcomm_session_msg), &cmd_ctx->creds);
4539 if (ret <= 0) {
4540 DBG("Nothing recv() from client... continuing");
4541 ret = close(sock);
4542 if (ret) {
4543 PERROR("close");
4544 }
4545 sock = -1;
4546 clean_command_ctx(&cmd_ctx);
4547 continue;
4548 }
4549
4550 health_code_update();
4551
4552 // TODO: Validate cmd_ctx including sanity check for
4553 // security purpose.
4554
4555 rcu_thread_online();
4556 /*
4557 * This function dispatch the work to the kernel or userspace tracer
4558 * libs and fill the lttcomm_lttng_msg data structure of all the needed
4559 * informations for the client. The command context struct contains
4560 * everything this function may needs.
4561 */
4562 ret = process_client_msg(cmd_ctx, sock, &sock_error);
4563 rcu_thread_offline();
4564 if (ret < 0) {
4565 ret = close(sock);
4566 if (ret) {
4567 PERROR("close");
4568 }
4569 sock = -1;
4570 /*
4571 * TODO: Inform client somehow of the fatal error. At
4572 * this point, ret < 0 means that a zmalloc failed
4573 * (ENOMEM). Error detected but still accept
4574 * command, unless a socket error has been
4575 * detected.
4576 */
4577 clean_command_ctx(&cmd_ctx);
4578 continue;
4579 }
4580
4581 health_code_update();
4582
4583 DBG("Sending response (size: %d, retcode: %s (%d))",
4584 cmd_ctx->lttng_msg_size,
4585 lttng_strerror(-cmd_ctx->llm->ret_code),
4586 cmd_ctx->llm->ret_code);
4587 ret = send_unix_sock(sock, cmd_ctx->llm, cmd_ctx->lttng_msg_size);
4588 if (ret < 0) {
4589 ERR("Failed to send data back to client");
4590 }
4591
4592 /* End of transmission */
4593 ret = close(sock);
4594 if (ret) {
4595 PERROR("close");
4596 }
4597 sock = -1;
4598
4599 clean_command_ctx(&cmd_ctx);
4600
4601 health_code_update();
4602 }
4603
4604 exit:
4605 error:
4606 if (sock >= 0) {
4607 ret = close(sock);
4608 if (ret) {
4609 PERROR("close");
4610 }
4611 }
4612
4613 lttng_poll_clean(&events);
4614 clean_command_ctx(&cmd_ctx);
4615
4616 error_listen:
4617 error_create_poll:
4618 unlink(client_unix_sock_path);
4619 if (client_sock >= 0) {
4620 ret = close(client_sock);
4621 if (ret) {
4622 PERROR("close");
4623 }
4624 }
4625
4626 if (err) {
4627 health_error();
4628 ERR("Health error occurred in %s", __func__);
4629 }
4630
4631 health_unregister(health_sessiond);
4632
4633 DBG("Client thread dying");
4634
4635 rcu_unregister_thread();
4636
4637 /*
4638 * Since we are creating the consumer threads, we own them, so we need
4639 * to join them before our thread exits.
4640 */
4641 ret = join_consumer_thread(&kconsumer_data);
4642 if (ret) {
4643 errno = ret;
4644 PERROR("join_consumer");
4645 }
4646
4647 ret = join_consumer_thread(&ustconsumer32_data);
4648 if (ret) {
4649 errno = ret;
4650 PERROR("join_consumer ust32");
4651 }
4652
4653 ret = join_consumer_thread(&ustconsumer64_data);
4654 if (ret) {
4655 errno = ret;
4656 PERROR("join_consumer ust64");
4657 }
4658 return NULL;
4659 }
4660
4661 static int string_match(const char *str1, const char *str2)
4662 {
4663 return (str1 && str2) && !strcmp(str1, str2);
4664 }
4665
4666 /*
4667 * Take an option from the getopt output and set it in the right variable to be
4668 * used later.
4669 *
4670 * Return 0 on success else a negative value.
4671 */
4672 static int set_option(int opt, const char *arg, const char *optname)
4673 {
4674 int ret = 0;
4675
4676 if (string_match(optname, "client-sock") || opt == 'c') {
4677 if (!arg || *arg == '\0') {
4678 ret = -EINVAL;
4679 goto end;
4680 }
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 (!arg || *arg == '\0') {
4689 ret = -EINVAL;
4690 goto end;
4691 }
4692 if (lttng_is_setuid_setgid()) {
4693 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4694 "-a, --apps-sock");
4695 } else {
4696 snprintf(apps_unix_sock_path, PATH_MAX, "%s", arg);
4697 }
4698 } else if (string_match(optname, "daemonize") || opt == 'd') {
4699 opt_daemon = 1;
4700 } else if (string_match(optname, "background") || opt == 'b') {
4701 opt_background = 1;
4702 } else if (string_match(optname, "group") || opt == 'g') {
4703 if (!arg || *arg == '\0') {
4704 ret = -EINVAL;
4705 goto end;
4706 }
4707 if (lttng_is_setuid_setgid()) {
4708 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4709 "-g, --group");
4710 } else {
4711 /*
4712 * If the override option is set, the pointer points to a
4713 * *non* const thus freeing it even though the variable type is
4714 * set to const.
4715 */
4716 if (tracing_group_name_override) {
4717 free((void *) tracing_group_name);
4718 }
4719 tracing_group_name = strdup(arg);
4720 if (!tracing_group_name) {
4721 PERROR("strdup");
4722 ret = -ENOMEM;
4723 }
4724 tracing_group_name_override = 1;
4725 }
4726 } else if (string_match(optname, "help") || opt == 'h') {
4727 ret = utils_show_man_page(8, "lttng-sessiond");
4728 if (ret) {
4729 ERR("Cannot view man page lttng-sessiond(8)");
4730 perror("exec");
4731 }
4732 exit(ret ? EXIT_FAILURE : EXIT_SUCCESS);
4733 } else if (string_match(optname, "version") || opt == 'V') {
4734 fprintf(stdout, "%s\n", VERSION);
4735 exit(EXIT_SUCCESS);
4736 } else if (string_match(optname, "sig-parent") || opt == 'S') {
4737 opt_sig_parent = 1;
4738 } else if (string_match(optname, "kconsumerd-err-sock")) {
4739 if (!arg || *arg == '\0') {
4740 ret = -EINVAL;
4741 goto end;
4742 }
4743 if (lttng_is_setuid_setgid()) {
4744 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4745 "--kconsumerd-err-sock");
4746 } else {
4747 snprintf(kconsumer_data.err_unix_sock_path, PATH_MAX, "%s", arg);
4748 }
4749 } else if (string_match(optname, "kconsumerd-cmd-sock")) {
4750 if (!arg || *arg == '\0') {
4751 ret = -EINVAL;
4752 goto end;
4753 }
4754 if (lttng_is_setuid_setgid()) {
4755 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4756 "--kconsumerd-cmd-sock");
4757 } else {
4758 snprintf(kconsumer_data.cmd_unix_sock_path, PATH_MAX, "%s", arg);
4759 }
4760 } else if (string_match(optname, "ustconsumerd64-err-sock")) {
4761 if (!arg || *arg == '\0') {
4762 ret = -EINVAL;
4763 goto end;
4764 }
4765 if (lttng_is_setuid_setgid()) {
4766 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4767 "--ustconsumerd64-err-sock");
4768 } else {
4769 snprintf(ustconsumer64_data.err_unix_sock_path, PATH_MAX, "%s", arg);
4770 }
4771 } else if (string_match(optname, "ustconsumerd64-cmd-sock")) {
4772 if (!arg || *arg == '\0') {
4773 ret = -EINVAL;
4774 goto end;
4775 }
4776 if (lttng_is_setuid_setgid()) {
4777 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4778 "--ustconsumerd64-cmd-sock");
4779 } else {
4780 snprintf(ustconsumer64_data.cmd_unix_sock_path, PATH_MAX, "%s", arg);
4781 }
4782 } else if (string_match(optname, "ustconsumerd32-err-sock")) {
4783 if (!arg || *arg == '\0') {
4784 ret = -EINVAL;
4785 goto end;
4786 }
4787 if (lttng_is_setuid_setgid()) {
4788 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4789 "--ustconsumerd32-err-sock");
4790 } else {
4791 snprintf(ustconsumer32_data.err_unix_sock_path, PATH_MAX, "%s", arg);
4792 }
4793 } else if (string_match(optname, "ustconsumerd32-cmd-sock")) {
4794 if (!arg || *arg == '\0') {
4795 ret = -EINVAL;
4796 goto end;
4797 }
4798 if (lttng_is_setuid_setgid()) {
4799 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4800 "--ustconsumerd32-cmd-sock");
4801 } else {
4802 snprintf(ustconsumer32_data.cmd_unix_sock_path, PATH_MAX, "%s", arg);
4803 }
4804 } else if (string_match(optname, "no-kernel")) {
4805 opt_no_kernel = 1;
4806 } else if (string_match(optname, "quiet") || opt == 'q') {
4807 lttng_opt_quiet = 1;
4808 } else if (string_match(optname, "verbose") || opt == 'v') {
4809 /* Verbose level can increase using multiple -v */
4810 if (arg) {
4811 /* Value obtained from config file */
4812 lttng_opt_verbose = config_parse_value(arg);
4813 } else {
4814 /* -v used on command line */
4815 lttng_opt_verbose++;
4816 }
4817 /* Clamp value to [0, 3] */
4818 lttng_opt_verbose = lttng_opt_verbose < 0 ? 0 :
4819 (lttng_opt_verbose <= 3 ? lttng_opt_verbose : 3);
4820 } else if (string_match(optname, "verbose-consumer")) {
4821 if (arg) {
4822 opt_verbose_consumer = config_parse_value(arg);
4823 } else {
4824 opt_verbose_consumer++;
4825 }
4826 } else if (string_match(optname, "consumerd32-path")) {
4827 if (!arg || *arg == '\0') {
4828 ret = -EINVAL;
4829 goto end;
4830 }
4831 if (lttng_is_setuid_setgid()) {
4832 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4833 "--consumerd32-path");
4834 } else {
4835 if (consumerd32_bin_override) {
4836 free((void *) consumerd32_bin);
4837 }
4838 consumerd32_bin = strdup(arg);
4839 if (!consumerd32_bin) {
4840 PERROR("strdup");
4841 ret = -ENOMEM;
4842 }
4843 consumerd32_bin_override = 1;
4844 }
4845 } else if (string_match(optname, "consumerd32-libdir")) {
4846 if (!arg || *arg == '\0') {
4847 ret = -EINVAL;
4848 goto end;
4849 }
4850 if (lttng_is_setuid_setgid()) {
4851 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4852 "--consumerd32-libdir");
4853 } else {
4854 if (consumerd32_libdir_override) {
4855 free((void *) consumerd32_libdir);
4856 }
4857 consumerd32_libdir = strdup(arg);
4858 if (!consumerd32_libdir) {
4859 PERROR("strdup");
4860 ret = -ENOMEM;
4861 }
4862 consumerd32_libdir_override = 1;
4863 }
4864 } else if (string_match(optname, "consumerd64-path")) {
4865 if (!arg || *arg == '\0') {
4866 ret = -EINVAL;
4867 goto end;
4868 }
4869 if (lttng_is_setuid_setgid()) {
4870 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4871 "--consumerd64-path");
4872 } else {
4873 if (consumerd64_bin_override) {
4874 free((void *) consumerd64_bin);
4875 }
4876 consumerd64_bin = strdup(arg);
4877 if (!consumerd64_bin) {
4878 PERROR("strdup");
4879 ret = -ENOMEM;
4880 }
4881 consumerd64_bin_override = 1;
4882 }
4883 } else if (string_match(optname, "consumerd64-libdir")) {
4884 if (!arg || *arg == '\0') {
4885 ret = -EINVAL;
4886 goto end;
4887 }
4888 if (lttng_is_setuid_setgid()) {
4889 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4890 "--consumerd64-libdir");
4891 } else {
4892 if (consumerd64_libdir_override) {
4893 free((void *) consumerd64_libdir);
4894 }
4895 consumerd64_libdir = strdup(arg);
4896 if (!consumerd64_libdir) {
4897 PERROR("strdup");
4898 ret = -ENOMEM;
4899 }
4900 consumerd64_libdir_override = 1;
4901 }
4902 } else if (string_match(optname, "pidfile") || opt == 'p') {
4903 if (!arg || *arg == '\0') {
4904 ret = -EINVAL;
4905 goto end;
4906 }
4907 if (lttng_is_setuid_setgid()) {
4908 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4909 "-p, --pidfile");
4910 } else {
4911 free(opt_pidfile);
4912 opt_pidfile = strdup(arg);
4913 if (!opt_pidfile) {
4914 PERROR("strdup");
4915 ret = -ENOMEM;
4916 }
4917 }
4918 } else if (string_match(optname, "agent-tcp-port")) {
4919 if (!arg || *arg == '\0') {
4920 ret = -EINVAL;
4921 goto end;
4922 }
4923 if (lttng_is_setuid_setgid()) {
4924 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4925 "--agent-tcp-port");
4926 } else {
4927 unsigned long v;
4928
4929 errno = 0;
4930 v = strtoul(arg, NULL, 0);
4931 if (errno != 0 || !isdigit(arg[0])) {
4932 ERR("Wrong value in --agent-tcp-port parameter: %s", arg);
4933 return -1;
4934 }
4935 if (v == 0 || v >= 65535) {
4936 ERR("Port overflow in --agent-tcp-port parameter: %s", arg);
4937 return -1;
4938 }
4939 agent_tcp_port = (uint32_t) v;
4940 DBG3("Agent TCP port set to non default: %u", agent_tcp_port);
4941 }
4942 } else if (string_match(optname, "load") || opt == 'l') {
4943 if (!arg || *arg == '\0') {
4944 ret = -EINVAL;
4945 goto end;
4946 }
4947 if (lttng_is_setuid_setgid()) {
4948 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4949 "-l, --load");
4950 } else {
4951 free(opt_load_session_path);
4952 opt_load_session_path = strdup(arg);
4953 if (!opt_load_session_path) {
4954 PERROR("strdup");
4955 ret = -ENOMEM;
4956 }
4957 }
4958 } else if (string_match(optname, "kmod-probes")) {
4959 if (!arg || *arg == '\0') {
4960 ret = -EINVAL;
4961 goto end;
4962 }
4963 if (lttng_is_setuid_setgid()) {
4964 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4965 "--kmod-probes");
4966 } else {
4967 free(kmod_probes_list);
4968 kmod_probes_list = strdup(arg);
4969 if (!kmod_probes_list) {
4970 PERROR("strdup");
4971 ret = -ENOMEM;
4972 }
4973 }
4974 } else if (string_match(optname, "extra-kmod-probes")) {
4975 if (!arg || *arg == '\0') {
4976 ret = -EINVAL;
4977 goto end;
4978 }
4979 if (lttng_is_setuid_setgid()) {
4980 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4981 "--extra-kmod-probes");
4982 } else {
4983 free(kmod_extra_probes_list);
4984 kmod_extra_probes_list = strdup(arg);
4985 if (!kmod_extra_probes_list) {
4986 PERROR("strdup");
4987 ret = -ENOMEM;
4988 }
4989 }
4990 } else if (string_match(optname, "config") || opt == 'f') {
4991 /* This is handled in set_options() thus silent skip. */
4992 goto end;
4993 } else {
4994 /* Unknown option or other error.
4995 * Error is printed by getopt, just return */
4996 ret = -1;
4997 }
4998
4999 end:
5000 if (ret == -EINVAL) {
5001 const char *opt_name = "unknown";
5002 int i;
5003
5004 for (i = 0; i < sizeof(long_options) / sizeof(struct option);
5005 i++) {
5006 if (opt == long_options[i].val) {
5007 opt_name = long_options[i].name;
5008 break;
5009 }
5010 }
5011
5012 WARN("Invalid argument provided for option \"%s\", using default value.",
5013 opt_name);
5014 }
5015
5016 return ret;
5017 }
5018
5019 /*
5020 * config_entry_handler_cb used to handle options read from a config file.
5021 * See config_entry_handler_cb comment in common/config/session-config.h for the
5022 * return value conventions.
5023 */
5024 static int config_entry_handler(const struct config_entry *entry, void *unused)
5025 {
5026 int ret = 0, i;
5027
5028 if (!entry || !entry->name || !entry->value) {
5029 ret = -EINVAL;
5030 goto end;
5031 }
5032
5033 /* Check if the option is to be ignored */
5034 for (i = 0; i < sizeof(config_ignore_options) / sizeof(char *); i++) {
5035 if (!strcmp(entry->name, config_ignore_options[i])) {
5036 goto end;
5037 }
5038 }
5039
5040 for (i = 0; i < (sizeof(long_options) / sizeof(struct option)) - 1;
5041 i++) {
5042
5043 /* Ignore if not fully matched. */
5044 if (strcmp(entry->name, long_options[i].name)) {
5045 continue;
5046 }
5047
5048 /*
5049 * If the option takes no argument on the command line, we have to
5050 * check if the value is "true". We support non-zero numeric values,
5051 * true, on and yes.
5052 */
5053 if (!long_options[i].has_arg) {
5054 ret = config_parse_value(entry->value);
5055 if (ret <= 0) {
5056 if (ret) {
5057 WARN("Invalid configuration value \"%s\" for option %s",
5058 entry->value, entry->name);
5059 }
5060 /* False, skip boolean config option. */
5061 goto end;
5062 }
5063 }
5064
5065 ret = set_option(long_options[i].val, entry->value, entry->name);
5066 goto end;
5067 }
5068
5069 WARN("Unrecognized option \"%s\" in daemon configuration file.", entry->name);
5070
5071 end:
5072 return ret;
5073 }
5074
5075 /*
5076 * daemon configuration loading and argument parsing
5077 */
5078 static int set_options(int argc, char **argv)
5079 {
5080 int ret = 0, c = 0, option_index = 0;
5081 int orig_optopt = optopt, orig_optind = optind;
5082 char *optstring;
5083 const char *config_path = NULL;
5084
5085 optstring = utils_generate_optstring(long_options,
5086 sizeof(long_options) / sizeof(struct option));
5087 if (!optstring) {
5088 ret = -ENOMEM;
5089 goto end;
5090 }
5091
5092 /* Check for the --config option */
5093 while ((c = getopt_long(argc, argv, optstring, long_options,
5094 &option_index)) != -1) {
5095 if (c == '?') {
5096 ret = -EINVAL;
5097 goto end;
5098 } else if (c != 'f') {
5099 /* if not equal to --config option. */
5100 continue;
5101 }
5102
5103 if (lttng_is_setuid_setgid()) {
5104 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
5105 "-f, --config");
5106 } else {
5107 config_path = utils_expand_path(optarg);
5108 if (!config_path) {
5109 ERR("Failed to resolve path: %s", optarg);
5110 }
5111 }
5112 }
5113
5114 ret = config_get_section_entries(config_path, config_section_name,
5115 config_entry_handler, NULL);
5116 if (ret) {
5117 if (ret > 0) {
5118 ERR("Invalid configuration option at line %i", ret);
5119 ret = -1;
5120 }
5121 goto end;
5122 }
5123
5124 /* Reset getopt's global state */
5125 optopt = orig_optopt;
5126 optind = orig_optind;
5127 while (1) {
5128 option_index = -1;
5129 /*
5130 * getopt_long() will not set option_index if it encounters a
5131 * short option.
5132 */
5133 c = getopt_long(argc, argv, optstring, long_options,
5134 &option_index);
5135 if (c == -1) {
5136 break;
5137 }
5138
5139 /*
5140 * Pass NULL as the long option name if popt left the index
5141 * unset.
5142 */
5143 ret = set_option(c, optarg,
5144 option_index < 0 ? NULL :
5145 long_options[option_index].name);
5146 if (ret < 0) {
5147 break;
5148 }
5149 }
5150
5151 end:
5152 free(optstring);
5153 return ret;
5154 }
5155
5156 /*
5157 * Creates the two needed socket by the daemon.
5158 * apps_sock - The communication socket for all UST apps.
5159 * client_sock - The communication of the cli tool (lttng).
5160 */
5161 static int init_daemon_socket(void)
5162 {
5163 int ret = 0;
5164 mode_t old_umask;
5165
5166 old_umask = umask(0);
5167
5168 /* Create client tool unix socket */
5169 client_sock = lttcomm_create_unix_sock(client_unix_sock_path);
5170 if (client_sock < 0) {
5171 ERR("Create unix sock failed: %s", client_unix_sock_path);
5172 ret = -1;
5173 goto end;
5174 }
5175
5176 /* Set the cloexec flag */
5177 ret = utils_set_fd_cloexec(client_sock);
5178 if (ret < 0) {
5179 ERR("Unable to set CLOEXEC flag to the client Unix socket (fd: %d). "
5180 "Continuing but note that the consumer daemon will have a "
5181 "reference to this socket on exec()", client_sock);
5182 }
5183
5184 /* File permission MUST be 660 */
5185 ret = chmod(client_unix_sock_path, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
5186 if (ret < 0) {
5187 ERR("Set file permissions failed: %s", client_unix_sock_path);
5188 PERROR("chmod");
5189 goto end;
5190 }
5191
5192 /* Create the application unix socket */
5193 apps_sock = lttcomm_create_unix_sock(apps_unix_sock_path);
5194 if (apps_sock < 0) {
5195 ERR("Create unix sock failed: %s", apps_unix_sock_path);
5196 ret = -1;
5197 goto end;
5198 }
5199
5200 /* Set the cloexec flag */
5201 ret = utils_set_fd_cloexec(apps_sock);
5202 if (ret < 0) {
5203 ERR("Unable to set CLOEXEC flag to the app Unix socket (fd: %d). "
5204 "Continuing but note that the consumer daemon will have a "
5205 "reference to this socket on exec()", apps_sock);
5206 }
5207
5208 /* File permission MUST be 666 */
5209 ret = chmod(apps_unix_sock_path,
5210 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
5211 if (ret < 0) {
5212 ERR("Set file permissions failed: %s", apps_unix_sock_path);
5213 PERROR("chmod");
5214 goto end;
5215 }
5216
5217 DBG3("Session daemon client socket %d and application socket %d created",
5218 client_sock, apps_sock);
5219
5220 end:
5221 umask(old_umask);
5222 return ret;
5223 }
5224
5225 /*
5226 * Check if the global socket is available, and if a daemon is answering at the
5227 * other side. If yes, error is returned.
5228 */
5229 static int check_existing_daemon(void)
5230 {
5231 /* Is there anybody out there ? */
5232 if (lttng_session_daemon_alive()) {
5233 return -EEXIST;
5234 }
5235
5236 return 0;
5237 }
5238
5239 /*
5240 * Set the tracing group gid onto the client socket.
5241 *
5242 * Race window between mkdir and chown is OK because we are going from more
5243 * permissive (root.root) to less permissive (root.tracing).
5244 */
5245 static int set_permissions(char *rundir)
5246 {
5247 int ret;
5248 gid_t gid;
5249
5250 gid = utils_get_group_id(tracing_group_name);
5251
5252 /* Set lttng run dir */
5253 ret = chown(rundir, 0, gid);
5254 if (ret < 0) {
5255 ERR("Unable to set group on %s", rundir);
5256 PERROR("chown");
5257 }
5258
5259 /*
5260 * Ensure all applications and tracing group can search the run
5261 * dir. Allow everyone to read the directory, since it does not
5262 * buy us anything to hide its content.
5263 */
5264 ret = chmod(rundir, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
5265 if (ret < 0) {
5266 ERR("Unable to set permissions on %s", rundir);
5267 PERROR("chmod");
5268 }
5269
5270 /* lttng client socket path */
5271 ret = chown(client_unix_sock_path, 0, gid);
5272 if (ret < 0) {
5273 ERR("Unable to set group on %s", client_unix_sock_path);
5274 PERROR("chown");
5275 }
5276
5277 /* kconsumer error socket path */
5278 ret = chown(kconsumer_data.err_unix_sock_path, 0, 0);
5279 if (ret < 0) {
5280 ERR("Unable to set group on %s", kconsumer_data.err_unix_sock_path);
5281 PERROR("chown");
5282 }
5283
5284 /* 64-bit ustconsumer error socket path */
5285 ret = chown(ustconsumer64_data.err_unix_sock_path, 0, 0);
5286 if (ret < 0) {
5287 ERR("Unable to set group on %s", ustconsumer64_data.err_unix_sock_path);
5288 PERROR("chown");
5289 }
5290
5291 /* 32-bit ustconsumer compat32 error socket path */
5292 ret = chown(ustconsumer32_data.err_unix_sock_path, 0, 0);
5293 if (ret < 0) {
5294 ERR("Unable to set group on %s", ustconsumer32_data.err_unix_sock_path);
5295 PERROR("chown");
5296 }
5297
5298 DBG("All permissions are set");
5299
5300 return ret;
5301 }
5302
5303 /*
5304 * Create the lttng run directory needed for all global sockets and pipe.
5305 */
5306 static int create_lttng_rundir(const char *rundir)
5307 {
5308 int ret;
5309
5310 DBG3("Creating LTTng run directory: %s", rundir);
5311
5312 ret = mkdir(rundir, S_IRWXU);
5313 if (ret < 0) {
5314 if (errno != EEXIST) {
5315 ERR("Unable to create %s", rundir);
5316 goto error;
5317 } else {
5318 ret = 0;
5319 }
5320 }
5321
5322 error:
5323 return ret;
5324 }
5325
5326 /*
5327 * Setup sockets and directory needed by the kconsumerd communication with the
5328 * session daemon.
5329 */
5330 static int set_consumer_sockets(struct consumer_data *consumer_data,
5331 const char *rundir)
5332 {
5333 int ret;
5334 char path[PATH_MAX];
5335
5336 switch (consumer_data->type) {
5337 case LTTNG_CONSUMER_KERNEL:
5338 snprintf(path, PATH_MAX, DEFAULT_KCONSUMERD_PATH, rundir);
5339 break;
5340 case LTTNG_CONSUMER64_UST:
5341 snprintf(path, PATH_MAX, DEFAULT_USTCONSUMERD64_PATH, rundir);
5342 break;
5343 case LTTNG_CONSUMER32_UST:
5344 snprintf(path, PATH_MAX, DEFAULT_USTCONSUMERD32_PATH, rundir);
5345 break;
5346 default:
5347 ERR("Consumer type unknown");
5348 ret = -EINVAL;
5349 goto error;
5350 }
5351
5352 DBG2("Creating consumer directory: %s", path);
5353
5354 ret = mkdir(path, S_IRWXU | S_IRGRP | S_IXGRP);
5355 if (ret < 0) {
5356 if (errno != EEXIST) {
5357 PERROR("mkdir");
5358 ERR("Failed to create %s", path);
5359 goto error;
5360 }
5361 ret = -1;
5362 }
5363 if (is_root) {
5364 ret = chown(path, 0, utils_get_group_id(tracing_group_name));
5365 if (ret < 0) {
5366 ERR("Unable to set group on %s", path);
5367 PERROR("chown");
5368 goto error;
5369 }
5370 }
5371
5372 /* Create the kconsumerd error unix socket */
5373 consumer_data->err_sock =
5374 lttcomm_create_unix_sock(consumer_data->err_unix_sock_path);
5375 if (consumer_data->err_sock < 0) {
5376 ERR("Create unix sock failed: %s", consumer_data->err_unix_sock_path);
5377 ret = -1;
5378 goto error;
5379 }
5380
5381 /*
5382 * Set the CLOEXEC flag. Return code is useless because either way, the
5383 * show must go on.
5384 */
5385 ret = utils_set_fd_cloexec(consumer_data->err_sock);
5386 if (ret < 0) {
5387 PERROR("utils_set_fd_cloexec");
5388 /* continue anyway */
5389 }
5390
5391 /* File permission MUST be 660 */
5392 ret = chmod(consumer_data->err_unix_sock_path,
5393 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
5394 if (ret < 0) {
5395 ERR("Set file permissions failed: %s", consumer_data->err_unix_sock_path);
5396 PERROR("chmod");
5397 goto error;
5398 }
5399
5400 error:
5401 return ret;
5402 }
5403
5404 /*
5405 * Signal handler for the daemon
5406 *
5407 * Simply stop all worker threads, leaving main() return gracefully after
5408 * joining all threads and calling cleanup().
5409 */
5410 static void sighandler(int sig)
5411 {
5412 switch (sig) {
5413 case SIGPIPE:
5414 DBG("SIGPIPE caught");
5415 return;
5416 case SIGINT:
5417 DBG("SIGINT caught");
5418 stop_threads();
5419 break;
5420 case SIGTERM:
5421 DBG("SIGTERM caught");
5422 stop_threads();
5423 break;
5424 case SIGUSR1:
5425 CMM_STORE_SHARED(recv_child_signal, 1);
5426 break;
5427 default:
5428 break;
5429 }
5430 }
5431
5432 /*
5433 * Setup signal handler for :
5434 * SIGINT, SIGTERM, SIGPIPE
5435 */
5436 static int set_signal_handler(void)
5437 {
5438 int ret = 0;
5439 struct sigaction sa;
5440 sigset_t sigset;
5441
5442 if ((ret = sigemptyset(&sigset)) < 0) {
5443 PERROR("sigemptyset");
5444 return ret;
5445 }
5446
5447 sa.sa_handler = sighandler;
5448 sa.sa_mask = sigset;
5449 sa.sa_flags = 0;
5450 if ((ret = sigaction(SIGTERM, &sa, NULL)) < 0) {
5451 PERROR("sigaction");
5452 return ret;
5453 }
5454
5455 if ((ret = sigaction(SIGINT, &sa, NULL)) < 0) {
5456 PERROR("sigaction");
5457 return ret;
5458 }
5459
5460 if ((ret = sigaction(SIGPIPE, &sa, NULL)) < 0) {
5461 PERROR("sigaction");
5462 return ret;
5463 }
5464
5465 if ((ret = sigaction(SIGUSR1, &sa, NULL)) < 0) {
5466 PERROR("sigaction");
5467 return ret;
5468 }
5469
5470 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
5471
5472 return ret;
5473 }
5474
5475 /*
5476 * Set open files limit to unlimited. This daemon can open a large number of
5477 * file descriptors in order to consumer multiple kernel traces.
5478 */
5479 static void set_ulimit(void)
5480 {
5481 int ret;
5482 struct rlimit lim;
5483
5484 /* The kernel does not allowed an infinite limit for open files */
5485 lim.rlim_cur = 65535;
5486 lim.rlim_max = 65535;
5487
5488 ret = setrlimit(RLIMIT_NOFILE, &lim);
5489 if (ret < 0) {
5490 PERROR("failed to set open files limit");
5491 }
5492 }
5493
5494 /*
5495 * Write pidfile using the rundir and opt_pidfile.
5496 */
5497 static int write_pidfile(void)
5498 {
5499 int ret;
5500 char pidfile_path[PATH_MAX];
5501
5502 assert(rundir);
5503
5504 if (opt_pidfile) {
5505 if (lttng_strncpy(pidfile_path, opt_pidfile, sizeof(pidfile_path))) {
5506 ret = -1;
5507 goto error;
5508 }
5509 } else {
5510 /* Build pidfile path from rundir and opt_pidfile. */
5511 ret = snprintf(pidfile_path, sizeof(pidfile_path), "%s/"
5512 DEFAULT_LTTNG_SESSIOND_PIDFILE, rundir);
5513 if (ret < 0) {
5514 PERROR("snprintf pidfile path");
5515 goto error;
5516 }
5517 }
5518
5519 /*
5520 * Create pid file in rundir.
5521 */
5522 ret = utils_create_pid_file(getpid(), pidfile_path);
5523 error:
5524 return ret;
5525 }
5526
5527 /*
5528 * Create lockfile using the rundir and return its fd.
5529 */
5530 static int create_lockfile(void)
5531 {
5532 int ret;
5533 char lockfile_path[PATH_MAX];
5534
5535 ret = generate_lock_file_path(lockfile_path, sizeof(lockfile_path));
5536 if (ret < 0) {
5537 goto error;
5538 }
5539
5540 ret = utils_create_lock_file(lockfile_path);
5541 error:
5542 return ret;
5543 }
5544
5545 /*
5546 * Write agent TCP port using the rundir.
5547 */
5548 static int write_agent_port(void)
5549 {
5550 int ret;
5551 char path[PATH_MAX];
5552
5553 assert(rundir);
5554
5555 ret = snprintf(path, sizeof(path), "%s/"
5556 DEFAULT_LTTNG_SESSIOND_AGENTPORT_FILE, rundir);
5557 if (ret < 0) {
5558 PERROR("snprintf agent port path");
5559 goto error;
5560 }
5561
5562 /*
5563 * Create TCP agent port file in rundir.
5564 */
5565 ret = utils_create_pid_file(agent_tcp_port, path);
5566
5567 error:
5568 return ret;
5569 }
5570
5571 /*
5572 * main
5573 */
5574 int main(int argc, char **argv)
5575 {
5576 int ret = 0, retval = 0;
5577 void *status;
5578 const char *home_path, *env_app_timeout;
5579
5580 init_kernel_workarounds();
5581
5582 rcu_register_thread();
5583
5584 if (set_signal_handler()) {
5585 retval = -1;
5586 goto exit_set_signal_handler;
5587 }
5588
5589 setup_consumerd_path();
5590
5591 page_size = sysconf(_SC_PAGESIZE);
5592 if (page_size < 0) {
5593 PERROR("sysconf _SC_PAGESIZE");
5594 page_size = LONG_MAX;
5595 WARN("Fallback page size to %ld", page_size);
5596 }
5597
5598 /*
5599 * Parse arguments and load the daemon configuration file.
5600 *
5601 * We have an exit_options exit path to free memory reserved by
5602 * set_options. This is needed because the rest of sessiond_cleanup()
5603 * depends on ht_cleanup_thread, which depends on lttng_daemonize, which
5604 * depends on set_options.
5605 */
5606 progname = argv[0];
5607 if (set_options(argc, argv)) {
5608 retval = -1;
5609 goto exit_options;
5610 }
5611
5612 /* Daemonize */
5613 if (opt_daemon || opt_background) {
5614 int i;
5615
5616 ret = lttng_daemonize(&child_ppid, &recv_child_signal,
5617 !opt_background);
5618 if (ret < 0) {
5619 retval = -1;
5620 goto exit_options;
5621 }
5622
5623 /*
5624 * We are in the child. Make sure all other file descriptors are
5625 * closed, in case we are called with more opened file
5626 * descriptors than the standard ones.
5627 */
5628 for (i = 3; i < sysconf(_SC_OPEN_MAX); i++) {
5629 (void) close(i);
5630 }
5631 }
5632
5633 if (run_as_create_worker(argv[0]) < 0) {
5634 goto exit_create_run_as_worker_cleanup;
5635 }
5636
5637 /*
5638 * Starting from here, we can create threads. This needs to be after
5639 * lttng_daemonize due to RCU.
5640 */
5641
5642 /*
5643 * Initialize the health check subsystem. This call should set the
5644 * appropriate time values.
5645 */
5646 health_sessiond = health_app_create(NR_HEALTH_SESSIOND_TYPES);
5647 if (!health_sessiond) {
5648 PERROR("health_app_create error");
5649 retval = -1;
5650 goto exit_health_sessiond_cleanup;
5651 }
5652
5653 if (init_ht_cleanup_quit_pipe()) {
5654 retval = -1;
5655 goto exit_ht_cleanup_quit_pipe;
5656 }
5657
5658 /* Setup the thread ht_cleanup communication pipe. */
5659 if (utils_create_pipe_cloexec(ht_cleanup_pipe)) {
5660 retval = -1;
5661 goto exit_ht_cleanup_pipe;
5662 }
5663
5664 /* Set up max poll set size */
5665 if (lttng_poll_set_max_size()) {
5666 retval = -1;
5667 goto exit_set_max_size;
5668 }
5669
5670 /* Create thread to clean up RCU hash tables */
5671 ret = pthread_create(&ht_cleanup_thread, NULL,
5672 thread_ht_cleanup, (void *) NULL);
5673 if (ret) {
5674 errno = ret;
5675 PERROR("pthread_create ht_cleanup");
5676 retval = -1;
5677 goto exit_ht_cleanup;
5678 }
5679
5680 /* Create thread quit pipe */
5681 if (init_thread_quit_pipe()) {
5682 retval = -1;
5683 goto exit_init_data;
5684 }
5685
5686 /* Check if daemon is UID = 0 */
5687 is_root = !getuid();
5688
5689 if (is_root) {
5690 rundir = strdup(DEFAULT_LTTNG_RUNDIR);
5691 if (!rundir) {
5692 retval = -1;
5693 goto exit_init_data;
5694 }
5695
5696 /* Create global run dir with root access */
5697 if (create_lttng_rundir(rundir)) {
5698 retval = -1;
5699 goto exit_init_data;
5700 }
5701
5702 if (strlen(apps_unix_sock_path) == 0) {
5703 ret = snprintf(apps_unix_sock_path, PATH_MAX,
5704 DEFAULT_GLOBAL_APPS_UNIX_SOCK);
5705 if (ret < 0) {
5706 retval = -1;
5707 goto exit_init_data;
5708 }
5709 }
5710
5711 if (strlen(client_unix_sock_path) == 0) {
5712 ret = snprintf(client_unix_sock_path, PATH_MAX,
5713 DEFAULT_GLOBAL_CLIENT_UNIX_SOCK);
5714 if (ret < 0) {
5715 retval = -1;
5716 goto exit_init_data;
5717 }
5718 }
5719
5720 /* Set global SHM for ust */
5721 if (strlen(wait_shm_path) == 0) {
5722 ret = snprintf(wait_shm_path, PATH_MAX,
5723 DEFAULT_GLOBAL_APPS_WAIT_SHM_PATH);
5724 if (ret < 0) {
5725 retval = -1;
5726 goto exit_init_data;
5727 }
5728 }
5729
5730 if (strlen(health_unix_sock_path) == 0) {
5731 ret = snprintf(health_unix_sock_path,
5732 sizeof(health_unix_sock_path),
5733 DEFAULT_GLOBAL_HEALTH_UNIX_SOCK);
5734 if (ret < 0) {
5735 retval = -1;
5736 goto exit_init_data;
5737 }
5738 }
5739
5740 /* Setup kernel consumerd path */
5741 ret = snprintf(kconsumer_data.err_unix_sock_path, PATH_MAX,
5742 DEFAULT_KCONSUMERD_ERR_SOCK_PATH, rundir);
5743 if (ret < 0) {
5744 retval = -1;
5745 goto exit_init_data;
5746 }
5747 ret = snprintf(kconsumer_data.cmd_unix_sock_path, PATH_MAX,
5748 DEFAULT_KCONSUMERD_CMD_SOCK_PATH, rundir);
5749 if (ret < 0) {
5750 retval = -1;
5751 goto exit_init_data;
5752 }
5753
5754 DBG2("Kernel consumer err path: %s",
5755 kconsumer_data.err_unix_sock_path);
5756 DBG2("Kernel consumer cmd path: %s",
5757 kconsumer_data.cmd_unix_sock_path);
5758 } else {
5759 home_path = utils_get_home_dir();
5760 if (home_path == NULL) {
5761 /* TODO: Add --socket PATH option */
5762 ERR("Can't get HOME directory for sockets creation.");
5763 retval = -1;
5764 goto exit_init_data;
5765 }
5766
5767 /*
5768 * Create rundir from home path. This will create something like
5769 * $HOME/.lttng
5770 */
5771 ret = asprintf(&rundir, DEFAULT_LTTNG_HOME_RUNDIR, home_path);
5772 if (ret < 0) {
5773 retval = -1;
5774 goto exit_init_data;
5775 }
5776
5777 if (create_lttng_rundir(rundir)) {
5778 retval = -1;
5779 goto exit_init_data;
5780 }
5781
5782 if (strlen(apps_unix_sock_path) == 0) {
5783 ret = snprintf(apps_unix_sock_path, PATH_MAX,
5784 DEFAULT_HOME_APPS_UNIX_SOCK,
5785 home_path);
5786 if (ret < 0) {
5787 retval = -1;
5788 goto exit_init_data;
5789 }
5790 }
5791
5792 /* Set the cli tool unix socket path */
5793 if (strlen(client_unix_sock_path) == 0) {
5794 ret = snprintf(client_unix_sock_path, PATH_MAX,
5795 DEFAULT_HOME_CLIENT_UNIX_SOCK,
5796 home_path);
5797 if (ret < 0) {
5798 retval = -1;
5799 goto exit_init_data;
5800 }
5801 }
5802
5803 /* Set global SHM for ust */
5804 if (strlen(wait_shm_path) == 0) {
5805 ret = snprintf(wait_shm_path, PATH_MAX,
5806 DEFAULT_HOME_APPS_WAIT_SHM_PATH,
5807 getuid());
5808 if (ret < 0) {
5809 retval = -1;
5810 goto exit_init_data;
5811 }
5812 }
5813
5814 /* Set health check Unix path */
5815 if (strlen(health_unix_sock_path) == 0) {
5816 ret = snprintf(health_unix_sock_path,
5817 sizeof(health_unix_sock_path),
5818 DEFAULT_HOME_HEALTH_UNIX_SOCK,
5819 home_path);
5820 if (ret < 0) {
5821 retval = -1;
5822 goto exit_init_data;
5823 }
5824 }
5825 }
5826
5827 lockfile_fd = create_lockfile();
5828 if (lockfile_fd < 0) {
5829 retval = -1;
5830 goto exit_init_data;
5831 }
5832
5833 /* Set consumer initial state */
5834 kernel_consumerd_state = CONSUMER_STOPPED;
5835 ust_consumerd_state = CONSUMER_STOPPED;
5836
5837 DBG("Client socket path %s", client_unix_sock_path);
5838 DBG("Application socket path %s", apps_unix_sock_path);
5839 DBG("Application wait path %s", wait_shm_path);
5840 DBG("LTTng run directory path: %s", rundir);
5841
5842 /* 32 bits consumerd path setup */
5843 ret = snprintf(ustconsumer32_data.err_unix_sock_path, PATH_MAX,
5844 DEFAULT_USTCONSUMERD32_ERR_SOCK_PATH, rundir);
5845 if (ret < 0) {
5846 PERROR("snprintf 32-bit consumer error socket path");
5847 retval = -1;
5848 goto exit_init_data;
5849 }
5850 ret = snprintf(ustconsumer32_data.cmd_unix_sock_path, PATH_MAX,
5851 DEFAULT_USTCONSUMERD32_CMD_SOCK_PATH, rundir);
5852 if (ret < 0) {
5853 PERROR("snprintf 32-bit consumer command socket path");
5854 retval = -1;
5855 goto exit_init_data;
5856 }
5857
5858 DBG2("UST consumer 32 bits err path: %s",
5859 ustconsumer32_data.err_unix_sock_path);
5860 DBG2("UST consumer 32 bits cmd path: %s",
5861 ustconsumer32_data.cmd_unix_sock_path);
5862
5863 /* 64 bits consumerd path setup */
5864 ret = snprintf(ustconsumer64_data.err_unix_sock_path, PATH_MAX,
5865 DEFAULT_USTCONSUMERD64_ERR_SOCK_PATH, rundir);
5866 if (ret < 0) {
5867 PERROR("snprintf 64-bit consumer error socket path");
5868 retval = -1;
5869 goto exit_init_data;
5870 }
5871 ret = snprintf(ustconsumer64_data.cmd_unix_sock_path, PATH_MAX,
5872 DEFAULT_USTCONSUMERD64_CMD_SOCK_PATH, rundir);
5873 if (ret < 0) {
5874 PERROR("snprintf 64-bit consumer command socket path");
5875 retval = -1;
5876 goto exit_init_data;
5877 }
5878
5879 DBG2("UST consumer 64 bits err path: %s",
5880 ustconsumer64_data.err_unix_sock_path);
5881 DBG2("UST consumer 64 bits cmd path: %s",
5882 ustconsumer64_data.cmd_unix_sock_path);
5883
5884 /*
5885 * See if daemon already exist.
5886 */
5887 if (check_existing_daemon()) {
5888 ERR("Already running daemon.\n");
5889 /*
5890 * We do not goto exit because we must not cleanup()
5891 * because a daemon is already running.
5892 */
5893 retval = -1;
5894 goto exit_init_data;
5895 }
5896
5897 /*
5898 * Init UST app hash table. Alloc hash table before this point since
5899 * cleanup() can get called after that point.
5900 */
5901 if (ust_app_ht_alloc()) {
5902 ERR("Failed to allocate UST app hash table");
5903 retval = -1;
5904 goto exit_init_data;
5905 }
5906
5907 /*
5908 * Initialize agent app hash table. We allocate the hash table here
5909 * since cleanup() can get called after this point.
5910 */
5911 if (agent_app_ht_alloc()) {
5912 ERR("Failed to allocate Agent app hash table");
5913 retval = -1;
5914 goto exit_init_data;
5915 }
5916
5917 /*
5918 * These actions must be executed as root. We do that *after* setting up
5919 * the sockets path because we MUST make the check for another daemon using
5920 * those paths *before* trying to set the kernel consumer sockets and init
5921 * kernel tracer.
5922 */
5923 if (is_root) {
5924 if (set_consumer_sockets(&kconsumer_data, rundir)) {
5925 retval = -1;
5926 goto exit_init_data;
5927 }
5928
5929 /* Setup kernel tracer */
5930 if (!opt_no_kernel) {
5931 init_kernel_tracer();
5932 if (kernel_tracer_fd >= 0) {
5933 ret = syscall_init_table();
5934 if (ret < 0) {
5935 ERR("Unable to populate syscall table. "
5936 "Syscall tracing won't work "
5937 "for this session daemon.");
5938 }
5939 }
5940 }
5941
5942 /* Set ulimit for open files */
5943 set_ulimit();
5944 }
5945 /* init lttng_fd tracking must be done after set_ulimit. */
5946 lttng_fd_init();
5947
5948 if (set_consumer_sockets(&ustconsumer64_data, rundir)) {
5949 retval = -1;
5950 goto exit_init_data;
5951 }
5952
5953 if (set_consumer_sockets(&ustconsumer32_data, rundir)) {
5954 retval = -1;
5955 goto exit_init_data;
5956 }
5957
5958 /* Setup the needed unix socket */
5959 if (init_daemon_socket()) {
5960 retval = -1;
5961 goto exit_init_data;
5962 }
5963
5964 /* Set credentials to socket */
5965 if (is_root && set_permissions(rundir)) {
5966 retval = -1;
5967 goto exit_init_data;
5968 }
5969
5970 /* Get parent pid if -S, --sig-parent is specified. */
5971 if (opt_sig_parent) {
5972 ppid = getppid();
5973 }
5974
5975 /* Setup the kernel pipe for waking up the kernel thread */
5976 if (is_root && !opt_no_kernel) {
5977 if (utils_create_pipe_cloexec(kernel_poll_pipe)) {
5978 retval = -1;
5979 goto exit_init_data;
5980 }
5981 }
5982
5983 /* Setup the thread apps communication pipe. */
5984 if (utils_create_pipe_cloexec(apps_cmd_pipe)) {
5985 retval = -1;
5986 goto exit_init_data;
5987 }
5988
5989 /* Setup the thread apps notify communication pipe. */
5990 if (utils_create_pipe_cloexec(apps_cmd_notify_pipe)) {
5991 retval = -1;
5992 goto exit_init_data;
5993 }
5994
5995 /* Initialize global buffer per UID and PID registry. */
5996 buffer_reg_init_uid_registry();
5997 buffer_reg_init_pid_registry();
5998
5999 /* Init UST command queue. */
6000 cds_wfcq_init(&ust_cmd_queue.head, &ust_cmd_queue.tail);
6001
6002 /*
6003 * Get session list pointer. This pointer MUST NOT be free'd. This list
6004 * is statically declared in session.c
6005 */
6006 session_list_ptr = session_get_list();
6007
6008 cmd_init();
6009
6010 /* Check for the application socket timeout env variable. */
6011 env_app_timeout = getenv(DEFAULT_APP_SOCKET_TIMEOUT_ENV);
6012 if (env_app_timeout) {
6013 app_socket_timeout = atoi(env_app_timeout);
6014 } else {
6015 app_socket_timeout = DEFAULT_APP_SOCKET_RW_TIMEOUT;
6016 }
6017
6018 ret = write_pidfile();
6019 if (ret) {
6020 ERR("Error in write_pidfile");
6021 retval = -1;
6022 goto exit_init_data;
6023 }
6024 ret = write_agent_port();
6025 if (ret) {
6026 ERR("Error in write_agent_port");
6027 retval = -1;
6028 goto exit_init_data;
6029 }
6030
6031 /* Initialize communication library */
6032 lttcomm_init();
6033 /* Initialize TCP timeout values */
6034 lttcomm_inet_init();
6035
6036 if (load_session_init_data(&load_info) < 0) {
6037 retval = -1;
6038 goto exit_init_data;
6039 }
6040 load_info->path = opt_load_session_path;
6041
6042 /* Create health-check thread */
6043 ret = pthread_create(&health_thread, NULL,
6044 thread_manage_health, (void *) NULL);
6045 if (ret) {
6046 errno = ret;
6047 PERROR("pthread_create health");
6048 retval = -1;
6049 goto exit_health;
6050 }
6051
6052 /* Create thread to manage the client socket */
6053 ret = pthread_create(&client_thread, NULL,
6054 thread_manage_clients, (void *) NULL);
6055 if (ret) {
6056 errno = ret;
6057 PERROR("pthread_create clients");
6058 retval = -1;
6059 goto exit_client;
6060 }
6061
6062 /* Create thread to dispatch registration */
6063 ret = pthread_create(&dispatch_thread, NULL,
6064 thread_dispatch_ust_registration, (void *) NULL);
6065 if (ret) {
6066 errno = ret;
6067 PERROR("pthread_create dispatch");
6068 retval = -1;
6069 goto exit_dispatch;
6070 }
6071
6072 /* Create thread to manage application registration. */
6073 ret = pthread_create(&reg_apps_thread, NULL,
6074 thread_registration_apps, (void *) NULL);
6075 if (ret) {
6076 errno = ret;
6077 PERROR("pthread_create registration");
6078 retval = -1;
6079 goto exit_reg_apps;
6080 }
6081
6082 /* Create thread to manage application socket */
6083 ret = pthread_create(&apps_thread, NULL,
6084 thread_manage_apps, (void *) NULL);
6085 if (ret) {
6086 errno = ret;
6087 PERROR("pthread_create apps");
6088 retval = -1;
6089 goto exit_apps;
6090 }
6091
6092 /* Create thread to manage application notify socket */
6093 ret = pthread_create(&apps_notify_thread, NULL,
6094 ust_thread_manage_notify, (void *) NULL);
6095 if (ret) {
6096 errno = ret;
6097 PERROR("pthread_create notify");
6098 retval = -1;
6099 goto exit_apps_notify;
6100 }
6101
6102 /* Create agent registration thread. */
6103 ret = pthread_create(&agent_reg_thread, NULL,
6104 agent_thread_manage_registration, (void *) NULL);
6105 if (ret) {
6106 errno = ret;
6107 PERROR("pthread_create agent");
6108 retval = -1;
6109 goto exit_agent_reg;
6110 }
6111
6112 /* Don't start this thread if kernel tracing is not requested nor root */
6113 if (is_root && !opt_no_kernel) {
6114 /* Create kernel thread to manage kernel event */
6115 ret = pthread_create(&kernel_thread, NULL,
6116 thread_manage_kernel, (void *) NULL);
6117 if (ret) {
6118 errno = ret;
6119 PERROR("pthread_create kernel");
6120 retval = -1;
6121 goto exit_kernel;
6122 }
6123 }
6124
6125 /* Create session loading thread. */
6126 ret = pthread_create(&load_session_thread, NULL, thread_load_session,
6127 load_info);
6128 if (ret) {
6129 errno = ret;
6130 PERROR("pthread_create load_session_thread");
6131 retval = -1;
6132 goto exit_load_session;
6133 }
6134
6135 /*
6136 * This is where we start awaiting program completion (e.g. through
6137 * signal that asks threads to teardown).
6138 */
6139
6140 ret = pthread_join(load_session_thread, &status);
6141 if (ret) {
6142 errno = ret;
6143 PERROR("pthread_join load_session_thread");
6144 retval = -1;
6145 }
6146 exit_load_session:
6147
6148 if (is_root && !opt_no_kernel) {
6149 ret = pthread_join(kernel_thread, &status);
6150 if (ret) {
6151 errno = ret;
6152 PERROR("pthread_join");
6153 retval = -1;
6154 }
6155 }
6156 exit_kernel:
6157
6158 ret = pthread_join(agent_reg_thread, &status);
6159 if (ret) {
6160 errno = ret;
6161 PERROR("pthread_join agent");
6162 retval = -1;
6163 }
6164 exit_agent_reg:
6165
6166 ret = pthread_join(apps_notify_thread, &status);
6167 if (ret) {
6168 errno = ret;
6169 PERROR("pthread_join apps notify");
6170 retval = -1;
6171 }
6172 exit_apps_notify:
6173
6174 ret = pthread_join(apps_thread, &status);
6175 if (ret) {
6176 errno = ret;
6177 PERROR("pthread_join apps");
6178 retval = -1;
6179 }
6180 exit_apps:
6181
6182 ret = pthread_join(reg_apps_thread, &status);
6183 if (ret) {
6184 errno = ret;
6185 PERROR("pthread_join");
6186 retval = -1;
6187 }
6188 exit_reg_apps:
6189
6190 /*
6191 * Join dispatch thread after joining reg_apps_thread to ensure
6192 * we don't leak applications in the queue.
6193 */
6194 ret = pthread_join(dispatch_thread, &status);
6195 if (ret) {
6196 errno = ret;
6197 PERROR("pthread_join");
6198 retval = -1;
6199 }
6200 exit_dispatch:
6201
6202 ret = pthread_join(client_thread, &status);
6203 if (ret) {
6204 errno = ret;
6205 PERROR("pthread_join");
6206 retval = -1;
6207 }
6208 exit_client:
6209
6210 ret = pthread_join(health_thread, &status);
6211 if (ret) {
6212 errno = ret;
6213 PERROR("pthread_join health thread");
6214 retval = -1;
6215 }
6216 exit_health:
6217
6218 exit_init_data:
6219 /*
6220 * sessiond_cleanup() is called when no other thread is running, except
6221 * the ht_cleanup thread, which is needed to destroy the hash tables.
6222 */
6223 rcu_thread_online();
6224 sessiond_cleanup();
6225 rcu_thread_offline();
6226 rcu_unregister_thread();
6227
6228 ret = notify_thread_pipe(ht_cleanup_quit_pipe[1]);
6229 if (ret < 0) {
6230 ERR("write error on ht_cleanup quit pipe");
6231 retval = -1;
6232 }
6233
6234 ret = pthread_join(ht_cleanup_thread, &status);
6235 if (ret) {
6236 errno = ret;
6237 PERROR("pthread_join ht cleanup thread");
6238 retval = -1;
6239 }
6240 exit_ht_cleanup:
6241 exit_set_max_size:
6242
6243 utils_close_pipe(ht_cleanup_pipe);
6244 exit_ht_cleanup_pipe:
6245
6246 /*
6247 * Close the ht_cleanup quit pipe.
6248 */
6249 utils_close_pipe(ht_cleanup_quit_pipe);
6250 exit_ht_cleanup_quit_pipe:
6251
6252 health_app_destroy(health_sessiond);
6253 exit_health_sessiond_cleanup:
6254 exit_create_run_as_worker_cleanup:
6255
6256 exit_options:
6257 /* Ensure all prior call_rcu are done. */
6258 rcu_barrier();
6259
6260 sessiond_cleanup_options();
6261
6262 exit_set_signal_handler:
6263
6264 if (!retval) {
6265 exit(EXIT_SUCCESS);
6266 } else {
6267 exit(EXIT_FAILURE);
6268 }
6269 }
This page took 0.214995 seconds and 6 git commands to generate.