Fix: thread exit vs futex wait/wakeup race
[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 #include <ctype.h>
41
42 #include <common/common.h>
43 #include <common/compat/socket.h>
44 #include <common/compat/getenv.h>
45 #include <common/defaults.h>
46 #include <common/kernel-consumer/kernel-consumer.h>
47 #include <common/futex.h>
48 #include <common/relayd/relayd.h>
49 #include <common/utils.h>
50 #include <common/daemonize.h>
51 #include <common/config/session-config.h>
52
53 #include "lttng-sessiond.h"
54 #include "buffer-registry.h"
55 #include "channel.h"
56 #include "cmd.h"
57 #include "consumer.h"
58 #include "context.h"
59 #include "event.h"
60 #include "kernel.h"
61 #include "kernel-consumer.h"
62 #include "modprobe.h"
63 #include "shm.h"
64 #include "ust-ctl.h"
65 #include "ust-consumer.h"
66 #include "utils.h"
67 #include "fd-limit.h"
68 #include "health-sessiond.h"
69 #include "testpoint.h"
70 #include "ust-thread.h"
71 #include "agent-thread.h"
72 #include "save.h"
73 #include "load-session-thread.h"
74 #include "syscall.h"
75 #include "agent.h"
76
77 #define CONSUMERD_FILE "lttng-consumerd"
78
79 const char *progname;
80 static const char *tracing_group_name = DEFAULT_TRACING_GROUP;
81 static int tracing_group_name_override;
82 static char *opt_pidfile;
83 static int opt_sig_parent;
84 static int opt_verbose_consumer;
85 static int opt_daemon, opt_background;
86 static int opt_no_kernel;
87 static char *opt_load_session_path;
88 static pid_t ppid; /* Parent PID for --sig-parent option */
89 static pid_t child_ppid; /* Internal parent PID use with daemonize. */
90 static char *rundir;
91 static int lockfile_fd = -1;
92
93 /* Set to 1 when a SIGUSR1 signal is received. */
94 static int recv_child_signal;
95
96 /*
97 * Consumer daemon specific control data. Every value not initialized here is
98 * set to 0 by the static definition.
99 */
100 static struct consumer_data kconsumer_data = {
101 .type = LTTNG_CONSUMER_KERNEL,
102 .err_unix_sock_path = DEFAULT_KCONSUMERD_ERR_SOCK_PATH,
103 .cmd_unix_sock_path = DEFAULT_KCONSUMERD_CMD_SOCK_PATH,
104 .err_sock = -1,
105 .cmd_sock = -1,
106 .pid_mutex = PTHREAD_MUTEX_INITIALIZER,
107 .lock = PTHREAD_MUTEX_INITIALIZER,
108 .cond = PTHREAD_COND_INITIALIZER,
109 .cond_mutex = PTHREAD_MUTEX_INITIALIZER,
110 };
111 static struct consumer_data ustconsumer64_data = {
112 .type = LTTNG_CONSUMER64_UST,
113 .err_unix_sock_path = DEFAULT_USTCONSUMERD64_ERR_SOCK_PATH,
114 .cmd_unix_sock_path = DEFAULT_USTCONSUMERD64_CMD_SOCK_PATH,
115 .err_sock = -1,
116 .cmd_sock = -1,
117 .pid_mutex = PTHREAD_MUTEX_INITIALIZER,
118 .lock = PTHREAD_MUTEX_INITIALIZER,
119 .cond = PTHREAD_COND_INITIALIZER,
120 .cond_mutex = PTHREAD_MUTEX_INITIALIZER,
121 };
122 static struct consumer_data ustconsumer32_data = {
123 .type = LTTNG_CONSUMER32_UST,
124 .err_unix_sock_path = DEFAULT_USTCONSUMERD32_ERR_SOCK_PATH,
125 .cmd_unix_sock_path = DEFAULT_USTCONSUMERD32_CMD_SOCK_PATH,
126 .err_sock = -1,
127 .cmd_sock = -1,
128 .pid_mutex = PTHREAD_MUTEX_INITIALIZER,
129 .lock = PTHREAD_MUTEX_INITIALIZER,
130 .cond = PTHREAD_COND_INITIALIZER,
131 .cond_mutex = PTHREAD_MUTEX_INITIALIZER,
132 };
133
134 /* Command line options */
135 static const struct option long_options[] = {
136 { "client-sock", required_argument, 0, 'c' },
137 { "apps-sock", required_argument, 0, 'a' },
138 { "kconsumerd-cmd-sock", required_argument, 0, '\0' },
139 { "kconsumerd-err-sock", required_argument, 0, '\0' },
140 { "ustconsumerd32-cmd-sock", required_argument, 0, '\0' },
141 { "ustconsumerd32-err-sock", required_argument, 0, '\0' },
142 { "ustconsumerd64-cmd-sock", required_argument, 0, '\0' },
143 { "ustconsumerd64-err-sock", required_argument, 0, '\0' },
144 { "consumerd32-path", required_argument, 0, '\0' },
145 { "consumerd32-libdir", required_argument, 0, '\0' },
146 { "consumerd64-path", required_argument, 0, '\0' },
147 { "consumerd64-libdir", required_argument, 0, '\0' },
148 { "daemonize", no_argument, 0, 'd' },
149 { "background", no_argument, 0, 'b' },
150 { "sig-parent", no_argument, 0, 'S' },
151 { "help", no_argument, 0, 'h' },
152 { "group", required_argument, 0, 'g' },
153 { "version", no_argument, 0, 'V' },
154 { "quiet", no_argument, 0, 'q' },
155 { "verbose", no_argument, 0, 'v' },
156 { "verbose-consumer", no_argument, 0, '\0' },
157 { "no-kernel", no_argument, 0, '\0' },
158 { "pidfile", required_argument, 0, 'p' },
159 { "agent-tcp-port", required_argument, 0, '\0' },
160 { "config", required_argument, 0, 'f' },
161 { "load", required_argument, 0, 'l' },
162 { "kmod-probes", required_argument, 0, '\0' },
163 { "extra-kmod-probes", required_argument, 0, '\0' },
164 { NULL, 0, 0, 0 }
165 };
166
167 /* Command line options to ignore from configuration file */
168 static const char *config_ignore_options[] = { "help", "version", "config" };
169
170 /* Shared between threads */
171 static int dispatch_thread_exit;
172
173 /* Global application Unix socket path */
174 static char apps_unix_sock_path[PATH_MAX];
175 /* Global client Unix socket path */
176 static char client_unix_sock_path[PATH_MAX];
177 /* global wait shm path for UST */
178 static char wait_shm_path[PATH_MAX];
179 /* Global health check unix path */
180 static char health_unix_sock_path[PATH_MAX];
181
182 /* Sockets and FDs */
183 static int client_sock = -1;
184 static int apps_sock = -1;
185 int kernel_tracer_fd = -1;
186 static int kernel_poll_pipe[2] = { -1, -1 };
187
188 /*
189 * Quit pipe for all threads. This permits a single cancellation point
190 * for all threads when receiving an event on the pipe.
191 */
192 static int thread_quit_pipe[2] = { -1, -1 };
193 static int ht_cleanup_quit_pipe[2] = { -1, -1 };
194
195 /*
196 * This pipe is used to inform the thread managing application communication
197 * that a command is queued and ready to be processed.
198 */
199 static int apps_cmd_pipe[2] = { -1, -1 };
200
201 int apps_cmd_notify_pipe[2] = { -1, -1 };
202
203 /* Pthread, Mutexes and Semaphores */
204 static pthread_t apps_thread;
205 static pthread_t apps_notify_thread;
206 static pthread_t reg_apps_thread;
207 static pthread_t client_thread;
208 static pthread_t kernel_thread;
209 static pthread_t dispatch_thread;
210 static pthread_t health_thread;
211 static pthread_t ht_cleanup_thread;
212 static pthread_t agent_reg_thread;
213 static pthread_t load_session_thread;
214
215 /*
216 * UST registration command queue. This queue is tied with a futex and uses a N
217 * wakers / 1 waiter implemented and detailed in futex.c/.h
218 *
219 * The thread_registration_apps and thread_dispatch_ust_registration uses this
220 * queue along with the wait/wake scheme. The thread_manage_apps receives down
221 * the line new application socket and monitors it for any I/O error or clean
222 * close that triggers an unregistration of the application.
223 */
224 static struct ust_cmd_queue ust_cmd_queue;
225
226 /*
227 * Pointer initialized before thread creation.
228 *
229 * This points to the tracing session list containing the session count and a
230 * mutex lock. The lock MUST be taken if you iterate over the list. The lock
231 * MUST NOT be taken if you call a public function in session.c.
232 *
233 * The lock is nested inside the structure: session_list_ptr->lock. Please use
234 * session_lock_list and session_unlock_list for lock acquisition.
235 */
236 static struct ltt_session_list *session_list_ptr;
237
238 int ust_consumerd64_fd = -1;
239 int ust_consumerd32_fd = -1;
240
241 static const char *consumerd32_bin = CONFIG_CONSUMERD32_BIN;
242 static const char *consumerd64_bin = CONFIG_CONSUMERD64_BIN;
243 static const char *consumerd32_libdir = CONFIG_CONSUMERD32_LIBDIR;
244 static const char *consumerd64_libdir = CONFIG_CONSUMERD64_LIBDIR;
245 static int consumerd32_bin_override;
246 static int consumerd64_bin_override;
247 static int consumerd32_libdir_override;
248 static int consumerd64_libdir_override;
249
250 static const char *module_proc_lttng = "/proc/lttng";
251
252 /*
253 * Consumer daemon state which is changed when spawning it, killing it or in
254 * case of a fatal error.
255 */
256 enum consumerd_state {
257 CONSUMER_STARTED = 1,
258 CONSUMER_STOPPED = 2,
259 CONSUMER_ERROR = 3,
260 };
261
262 /*
263 * This consumer daemon state is used to validate if a client command will be
264 * able to reach the consumer. If not, the client is informed. For instance,
265 * doing a "lttng start" when the consumer state is set to ERROR will return an
266 * error to the client.
267 *
268 * The following example shows a possible race condition of this scheme:
269 *
270 * consumer thread error happens
271 * client cmd arrives
272 * client cmd checks state -> still OK
273 * consumer thread exit, sets error
274 * client cmd try to talk to consumer
275 * ...
276 *
277 * However, since the consumer is a different daemon, we have no way of making
278 * sure the command will reach it safely even with this state flag. This is why
279 * we consider that up to the state validation during command processing, the
280 * command is safe. After that, we can not guarantee the correctness of the
281 * client request vis-a-vis the consumer.
282 */
283 static enum consumerd_state ust_consumerd_state;
284 static enum consumerd_state kernel_consumerd_state;
285
286 /*
287 * Socket timeout for receiving and sending in seconds.
288 */
289 static int app_socket_timeout;
290
291 /* Set in main() with the current page size. */
292 long page_size;
293
294 /* Application health monitoring */
295 struct health_app *health_sessiond;
296
297 /* Agent TCP port for registration. Used by the agent thread. */
298 unsigned int agent_tcp_port = DEFAULT_AGENT_TCP_PORT;
299
300 /* Am I root or not. */
301 int is_root; /* Set to 1 if the daemon is running as root */
302
303 const char * const config_section_name = "sessiond";
304
305 /* Load session thread information to operate. */
306 struct load_session_thread_data *load_info;
307
308 /* Global hash tables */
309 struct lttng_ht *agent_apps_ht_by_sock = NULL;
310
311 /*
312 * Whether sessiond is ready for commands/health check requests.
313 * NR_LTTNG_SESSIOND_READY must match the number of calls to
314 * sessiond_notify_ready().
315 */
316 #define NR_LTTNG_SESSIOND_READY 3
317 int lttng_sessiond_ready = NR_LTTNG_SESSIOND_READY;
318
319 /* Notify parents that we are ready for cmd and health check */
320 LTTNG_HIDDEN
321 void sessiond_notify_ready(void)
322 {
323 if (uatomic_sub_return(&lttng_sessiond_ready, 1) == 0) {
324 /*
325 * Notify parent pid that we are ready to accept command
326 * for client side. This ppid is the one from the
327 * external process that spawned us.
328 */
329 if (opt_sig_parent) {
330 kill(ppid, SIGUSR1);
331 }
332
333 /*
334 * Notify the parent of the fork() process that we are
335 * ready.
336 */
337 if (opt_daemon || opt_background) {
338 kill(child_ppid, SIGUSR1);
339 }
340 }
341 }
342
343 static
344 void setup_consumerd_path(void)
345 {
346 const char *bin, *libdir;
347
348 /*
349 * Allow INSTALL_BIN_PATH to be used as a target path for the
350 * native architecture size consumer if CONFIG_CONSUMER*_PATH
351 * has not been defined.
352 */
353 #if (CAA_BITS_PER_LONG == 32)
354 if (!consumerd32_bin[0]) {
355 consumerd32_bin = INSTALL_BIN_PATH "/" CONSUMERD_FILE;
356 }
357 if (!consumerd32_libdir[0]) {
358 consumerd32_libdir = INSTALL_LIB_PATH;
359 }
360 #elif (CAA_BITS_PER_LONG == 64)
361 if (!consumerd64_bin[0]) {
362 consumerd64_bin = INSTALL_BIN_PATH "/" CONSUMERD_FILE;
363 }
364 if (!consumerd64_libdir[0]) {
365 consumerd64_libdir = INSTALL_LIB_PATH;
366 }
367 #else
368 #error "Unknown bitness"
369 #endif
370
371 /*
372 * runtime env. var. overrides the build default.
373 */
374 bin = lttng_secure_getenv("LTTNG_CONSUMERD32_BIN");
375 if (bin) {
376 consumerd32_bin = bin;
377 }
378 bin = lttng_secure_getenv("LTTNG_CONSUMERD64_BIN");
379 if (bin) {
380 consumerd64_bin = bin;
381 }
382 libdir = lttng_secure_getenv("LTTNG_CONSUMERD32_LIBDIR");
383 if (libdir) {
384 consumerd32_libdir = libdir;
385 }
386 libdir = lttng_secure_getenv("LTTNG_CONSUMERD64_LIBDIR");
387 if (libdir) {
388 consumerd64_libdir = libdir;
389 }
390 }
391
392 static
393 int __sessiond_set_thread_pollset(struct lttng_poll_event *events, size_t size,
394 int *a_pipe)
395 {
396 int ret;
397
398 assert(events);
399
400 ret = lttng_poll_create(events, size, LTTNG_CLOEXEC);
401 if (ret < 0) {
402 goto error;
403 }
404
405 /* Add quit pipe */
406 ret = lttng_poll_add(events, a_pipe[0], LPOLLIN | LPOLLERR);
407 if (ret < 0) {
408 goto error;
409 }
410
411 return 0;
412
413 error:
414 return ret;
415 }
416
417 /*
418 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
419 */
420 int sessiond_set_thread_pollset(struct lttng_poll_event *events, size_t size)
421 {
422 return __sessiond_set_thread_pollset(events, size, thread_quit_pipe);
423 }
424
425 /*
426 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
427 */
428 int sessiond_set_ht_cleanup_thread_pollset(struct lttng_poll_event *events,
429 size_t size)
430 {
431 return __sessiond_set_thread_pollset(events, size,
432 ht_cleanup_quit_pipe);
433 }
434
435 static
436 int __sessiond_check_thread_quit_pipe(int fd, uint32_t events, int a_pipe)
437 {
438 if (fd == a_pipe && (events & LPOLLIN)) {
439 return 1;
440 }
441 return 0;
442 }
443
444 /*
445 * Check if the thread quit pipe was triggered.
446 *
447 * Return 1 if it was triggered else 0;
448 */
449 int sessiond_check_thread_quit_pipe(int fd, uint32_t events)
450 {
451 return __sessiond_check_thread_quit_pipe(fd, events,
452 thread_quit_pipe[0]);
453 }
454
455 /*
456 * Check if the ht_cleanup thread quit pipe was triggered.
457 *
458 * Return 1 if it was triggered else 0;
459 */
460 int sessiond_check_ht_cleanup_quit(int fd, uint32_t events)
461 {
462 return __sessiond_check_thread_quit_pipe(fd, events,
463 ht_cleanup_quit_pipe[0]);
464 }
465
466 /*
467 * Init thread quit pipe.
468 *
469 * Return -1 on error or 0 if all pipes are created.
470 */
471 static int __init_thread_quit_pipe(int *a_pipe)
472 {
473 int ret, i;
474
475 ret = pipe(a_pipe);
476 if (ret < 0) {
477 PERROR("thread quit pipe");
478 goto error;
479 }
480
481 for (i = 0; i < 2; i++) {
482 ret = fcntl(a_pipe[i], F_SETFD, FD_CLOEXEC);
483 if (ret < 0) {
484 PERROR("fcntl");
485 goto error;
486 }
487 }
488
489 error:
490 return ret;
491 }
492
493 static int init_thread_quit_pipe(void)
494 {
495 return __init_thread_quit_pipe(thread_quit_pipe);
496 }
497
498 static int init_ht_cleanup_quit_pipe(void)
499 {
500 return __init_thread_quit_pipe(ht_cleanup_quit_pipe);
501 }
502
503 /*
504 * Stop all threads by closing the thread quit pipe.
505 */
506 static void stop_threads(void)
507 {
508 int ret;
509
510 /* Stopping all threads */
511 DBG("Terminating all threads");
512 ret = notify_thread_pipe(thread_quit_pipe[1]);
513 if (ret < 0) {
514 ERR("write error on thread quit pipe");
515 }
516
517 /* Dispatch thread */
518 CMM_STORE_SHARED(dispatch_thread_exit, 1);
519 futex_nto1_wake(&ust_cmd_queue.futex);
520 }
521
522 /*
523 * Close every consumer sockets.
524 */
525 static void close_consumer_sockets(void)
526 {
527 int ret;
528
529 if (kconsumer_data.err_sock >= 0) {
530 ret = close(kconsumer_data.err_sock);
531 if (ret < 0) {
532 PERROR("kernel consumer err_sock close");
533 }
534 }
535 if (ustconsumer32_data.err_sock >= 0) {
536 ret = close(ustconsumer32_data.err_sock);
537 if (ret < 0) {
538 PERROR("UST consumerd32 err_sock close");
539 }
540 }
541 if (ustconsumer64_data.err_sock >= 0) {
542 ret = close(ustconsumer64_data.err_sock);
543 if (ret < 0) {
544 PERROR("UST consumerd64 err_sock close");
545 }
546 }
547 if (kconsumer_data.cmd_sock >= 0) {
548 ret = close(kconsumer_data.cmd_sock);
549 if (ret < 0) {
550 PERROR("kernel consumer cmd_sock close");
551 }
552 }
553 if (ustconsumer32_data.cmd_sock >= 0) {
554 ret = close(ustconsumer32_data.cmd_sock);
555 if (ret < 0) {
556 PERROR("UST consumerd32 cmd_sock close");
557 }
558 }
559 if (ustconsumer64_data.cmd_sock >= 0) {
560 ret = close(ustconsumer64_data.cmd_sock);
561 if (ret < 0) {
562 PERROR("UST consumerd64 cmd_sock close");
563 }
564 }
565 }
566
567 /*
568 * Generate the full lock file path using the rundir.
569 *
570 * Return the snprintf() return value thus a negative value is an error.
571 */
572 static int generate_lock_file_path(char *path, size_t len)
573 {
574 int ret;
575
576 assert(path);
577 assert(rundir);
578
579 /* Build lockfile path from rundir. */
580 ret = snprintf(path, len, "%s/" DEFAULT_LTTNG_SESSIOND_LOCKFILE, rundir);
581 if (ret < 0) {
582 PERROR("snprintf lockfile path");
583 }
584
585 return ret;
586 }
587
588 /*
589 * Wait on consumer process termination.
590 *
591 * Need to be called with the consumer data lock held or from a context
592 * ensuring no concurrent access to data (e.g: cleanup).
593 */
594 static void wait_consumer(struct consumer_data *consumer_data)
595 {
596 pid_t ret;
597 int status;
598
599 if (consumer_data->pid <= 0) {
600 return;
601 }
602
603 DBG("Waiting for complete teardown of consumerd (PID: %d)",
604 consumer_data->pid);
605 ret = waitpid(consumer_data->pid, &status, 0);
606 if (ret == -1) {
607 PERROR("consumerd waitpid pid: %d", consumer_data->pid)
608 } else 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 rcu_register_thread();
1906
1907 health_register(health_sessiond, HEALTH_SESSIOND_TYPE_APP_REG_DISPATCH);
1908
1909 if (testpoint(sessiond_thread_app_reg_dispatch)) {
1910 goto error_testpoint;
1911 }
1912
1913 health_code_update();
1914
1915 CDS_INIT_LIST_HEAD(&wait_queue.head);
1916
1917 DBG("[thread] Dispatch UST command started");
1918
1919 for (;;) {
1920 health_code_update();
1921
1922 /* Atomically prepare the queue futex */
1923 futex_nto1_prepare(&ust_cmd_queue.futex);
1924
1925 if (CMM_LOAD_SHARED(dispatch_thread_exit)) {
1926 break;
1927 }
1928
1929 do {
1930 struct ust_app *app = NULL;
1931 ust_cmd = NULL;
1932
1933 /*
1934 * Make sure we don't have node(s) that have hung up before receiving
1935 * the notify socket. This is to clean the list in order to avoid
1936 * memory leaks from notify socket that are never seen.
1937 */
1938 sanitize_wait_queue(&wait_queue);
1939
1940 health_code_update();
1941 /* Dequeue command for registration */
1942 node = cds_wfcq_dequeue_blocking(&ust_cmd_queue.head, &ust_cmd_queue.tail);
1943 if (node == NULL) {
1944 DBG("Woken up but nothing in the UST command queue");
1945 /* Continue thread execution */
1946 break;
1947 }
1948
1949 ust_cmd = caa_container_of(node, struct ust_command, node);
1950
1951 DBG("Dispatching UST registration pid:%d ppid:%d uid:%d"
1952 " gid:%d sock:%d name:%s (version %d.%d)",
1953 ust_cmd->reg_msg.pid, ust_cmd->reg_msg.ppid,
1954 ust_cmd->reg_msg.uid, ust_cmd->reg_msg.gid,
1955 ust_cmd->sock, ust_cmd->reg_msg.name,
1956 ust_cmd->reg_msg.major, ust_cmd->reg_msg.minor);
1957
1958 if (ust_cmd->reg_msg.type == USTCTL_SOCKET_CMD) {
1959 wait_node = zmalloc(sizeof(*wait_node));
1960 if (!wait_node) {
1961 PERROR("zmalloc wait_node dispatch");
1962 ret = close(ust_cmd->sock);
1963 if (ret < 0) {
1964 PERROR("close ust sock dispatch %d", ust_cmd->sock);
1965 }
1966 lttng_fd_put(LTTNG_FD_APPS, 1);
1967 free(ust_cmd);
1968 goto error;
1969 }
1970 CDS_INIT_LIST_HEAD(&wait_node->head);
1971
1972 /* Create application object if socket is CMD. */
1973 wait_node->app = ust_app_create(&ust_cmd->reg_msg,
1974 ust_cmd->sock);
1975 if (!wait_node->app) {
1976 ret = close(ust_cmd->sock);
1977 if (ret < 0) {
1978 PERROR("close ust sock dispatch %d", ust_cmd->sock);
1979 }
1980 lttng_fd_put(LTTNG_FD_APPS, 1);
1981 free(wait_node);
1982 free(ust_cmd);
1983 continue;
1984 }
1985 /*
1986 * Add application to the wait queue so we can set the notify
1987 * socket before putting this object in the global ht.
1988 */
1989 cds_list_add(&wait_node->head, &wait_queue.head);
1990 wait_queue.count++;
1991
1992 free(ust_cmd);
1993 /*
1994 * We have to continue here since we don't have the notify
1995 * socket and the application MUST be added to the hash table
1996 * only at that moment.
1997 */
1998 continue;
1999 } else {
2000 /*
2001 * Look for the application in the local wait queue and set the
2002 * notify socket if found.
2003 */
2004 cds_list_for_each_entry_safe(wait_node, tmp_wait_node,
2005 &wait_queue.head, head) {
2006 health_code_update();
2007 if (wait_node->app->pid == ust_cmd->reg_msg.pid) {
2008 wait_node->app->notify_sock = ust_cmd->sock;
2009 cds_list_del(&wait_node->head);
2010 wait_queue.count--;
2011 app = wait_node->app;
2012 free(wait_node);
2013 DBG3("UST app notify socket %d is set", ust_cmd->sock);
2014 break;
2015 }
2016 }
2017
2018 /*
2019 * With no application at this stage the received socket is
2020 * basically useless so close it before we free the cmd data
2021 * structure for good.
2022 */
2023 if (!app) {
2024 ret = close(ust_cmd->sock);
2025 if (ret < 0) {
2026 PERROR("close ust sock dispatch %d", ust_cmd->sock);
2027 }
2028 lttng_fd_put(LTTNG_FD_APPS, 1);
2029 }
2030 free(ust_cmd);
2031 }
2032
2033 if (app) {
2034 /*
2035 * @session_lock_list
2036 *
2037 * Lock the global session list so from the register up to the
2038 * registration done message, no thread can see the application
2039 * and change its state.
2040 */
2041 session_lock_list();
2042 rcu_read_lock();
2043
2044 /*
2045 * Add application to the global hash table. This needs to be
2046 * done before the update to the UST registry can locate the
2047 * application.
2048 */
2049 ust_app_add(app);
2050
2051 /* Set app version. This call will print an error if needed. */
2052 (void) ust_app_version(app);
2053
2054 /* Send notify socket through the notify pipe. */
2055 ret = send_socket_to_thread(apps_cmd_notify_pipe[1],
2056 app->notify_sock);
2057 if (ret < 0) {
2058 rcu_read_unlock();
2059 session_unlock_list();
2060 /*
2061 * No notify thread, stop the UST tracing. However, this is
2062 * not an internal error of the this thread thus setting
2063 * the health error code to a normal exit.
2064 */
2065 err = 0;
2066 goto error;
2067 }
2068
2069 /*
2070 * Update newly registered application with the tracing
2071 * registry info already enabled information.
2072 */
2073 update_ust_app(app->sock);
2074
2075 /*
2076 * Don't care about return value. Let the manage apps threads
2077 * handle app unregistration upon socket close.
2078 */
2079 (void) ust_app_register_done(app);
2080
2081 /*
2082 * Even if the application socket has been closed, send the app
2083 * to the thread and unregistration will take place at that
2084 * place.
2085 */
2086 ret = send_socket_to_thread(apps_cmd_pipe[1], app->sock);
2087 if (ret < 0) {
2088 rcu_read_unlock();
2089 session_unlock_list();
2090 /*
2091 * No apps. thread, stop the UST tracing. However, this is
2092 * not an internal error of the this thread thus setting
2093 * the health error code to a normal exit.
2094 */
2095 err = 0;
2096 goto error;
2097 }
2098
2099 rcu_read_unlock();
2100 session_unlock_list();
2101 }
2102 } while (node != NULL);
2103
2104 health_poll_entry();
2105 /* Futex wait on queue. Blocking call on futex() */
2106 futex_nto1_wait(&ust_cmd_queue.futex);
2107 health_poll_exit();
2108 }
2109 /* Normal exit, no error */
2110 err = 0;
2111
2112 error:
2113 /* Clean up wait queue. */
2114 cds_list_for_each_entry_safe(wait_node, tmp_wait_node,
2115 &wait_queue.head, head) {
2116 cds_list_del(&wait_node->head);
2117 wait_queue.count--;
2118 free(wait_node);
2119 }
2120
2121 /* Empty command queue. */
2122 for (;;) {
2123 /* Dequeue command for registration */
2124 node = cds_wfcq_dequeue_blocking(&ust_cmd_queue.head, &ust_cmd_queue.tail);
2125 if (node == NULL) {
2126 break;
2127 }
2128 ust_cmd = caa_container_of(node, struct ust_command, node);
2129 ret = close(ust_cmd->sock);
2130 if (ret < 0) {
2131 PERROR("close ust sock exit dispatch %d", ust_cmd->sock);
2132 }
2133 lttng_fd_put(LTTNG_FD_APPS, 1);
2134 free(ust_cmd);
2135 }
2136
2137 error_testpoint:
2138 DBG("Dispatch thread dying");
2139 if (err) {
2140 health_error();
2141 ERR("Health error occurred in %s", __func__);
2142 }
2143 health_unregister(health_sessiond);
2144 rcu_unregister_thread();
2145 return NULL;
2146 }
2147
2148 /*
2149 * This thread manage application registration.
2150 */
2151 static void *thread_registration_apps(void *data)
2152 {
2153 int sock = -1, i, ret, pollfd, err = -1;
2154 uint32_t revents, nb_fd;
2155 struct lttng_poll_event events;
2156 /*
2157 * Get allocated in this thread, enqueued to a global queue, dequeued and
2158 * freed in the manage apps thread.
2159 */
2160 struct ust_command *ust_cmd = NULL;
2161
2162 DBG("[thread] Manage application registration started");
2163
2164 health_register(health_sessiond, HEALTH_SESSIOND_TYPE_APP_REG);
2165
2166 if (testpoint(sessiond_thread_registration_apps)) {
2167 goto error_testpoint;
2168 }
2169
2170 ret = lttcomm_listen_unix_sock(apps_sock);
2171 if (ret < 0) {
2172 goto error_listen;
2173 }
2174
2175 /*
2176 * Pass 2 as size here for the thread quit pipe and apps socket. Nothing
2177 * more will be added to this poll set.
2178 */
2179 ret = sessiond_set_thread_pollset(&events, 2);
2180 if (ret < 0) {
2181 goto error_create_poll;
2182 }
2183
2184 /* Add the application registration socket */
2185 ret = lttng_poll_add(&events, apps_sock, LPOLLIN | LPOLLRDHUP);
2186 if (ret < 0) {
2187 goto error_poll_add;
2188 }
2189
2190 /* Notify all applications to register */
2191 ret = notify_ust_apps(1);
2192 if (ret < 0) {
2193 ERR("Failed to notify applications or create the wait shared memory.\n"
2194 "Execution continues but there might be problem for already\n"
2195 "running applications that wishes to register.");
2196 }
2197
2198 while (1) {
2199 DBG("Accepting application registration");
2200
2201 /* Inifinite blocking call, waiting for transmission */
2202 restart:
2203 health_poll_entry();
2204 ret = lttng_poll_wait(&events, -1);
2205 health_poll_exit();
2206 if (ret < 0) {
2207 /*
2208 * Restart interrupted system call.
2209 */
2210 if (errno == EINTR) {
2211 goto restart;
2212 }
2213 goto error;
2214 }
2215
2216 nb_fd = ret;
2217
2218 for (i = 0; i < nb_fd; i++) {
2219 health_code_update();
2220
2221 /* Fetch once the poll data */
2222 revents = LTTNG_POLL_GETEV(&events, i);
2223 pollfd = LTTNG_POLL_GETFD(&events, i);
2224
2225 if (!revents) {
2226 /* No activity for this FD (poll implementation). */
2227 continue;
2228 }
2229
2230 /* Thread quit pipe has been closed. Killing thread. */
2231 ret = sessiond_check_thread_quit_pipe(pollfd, revents);
2232 if (ret) {
2233 err = 0;
2234 goto exit;
2235 }
2236
2237 /* Event on the registration socket */
2238 if (pollfd == apps_sock) {
2239 if (revents & LPOLLIN) {
2240 sock = lttcomm_accept_unix_sock(apps_sock);
2241 if (sock < 0) {
2242 goto error;
2243 }
2244
2245 /*
2246 * Set socket timeout for both receiving and ending.
2247 * app_socket_timeout is in seconds, whereas
2248 * lttcomm_setsockopt_rcv_timeout and
2249 * lttcomm_setsockopt_snd_timeout expect msec as
2250 * parameter.
2251 */
2252 if (app_socket_timeout >= 0) {
2253 (void) lttcomm_setsockopt_rcv_timeout(sock,
2254 app_socket_timeout * 1000);
2255 (void) lttcomm_setsockopt_snd_timeout(sock,
2256 app_socket_timeout * 1000);
2257 }
2258
2259 /*
2260 * Set the CLOEXEC flag. Return code is useless because
2261 * either way, the show must go on.
2262 */
2263 (void) utils_set_fd_cloexec(sock);
2264
2265 /* Create UST registration command for enqueuing */
2266 ust_cmd = zmalloc(sizeof(struct ust_command));
2267 if (ust_cmd == NULL) {
2268 PERROR("ust command zmalloc");
2269 ret = close(sock);
2270 if (ret) {
2271 PERROR("close");
2272 }
2273 goto error;
2274 }
2275
2276 /*
2277 * Using message-based transmissions to ensure we don't
2278 * have to deal with partially received messages.
2279 */
2280 ret = lttng_fd_get(LTTNG_FD_APPS, 1);
2281 if (ret < 0) {
2282 ERR("Exhausted file descriptors allowed for applications.");
2283 free(ust_cmd);
2284 ret = close(sock);
2285 if (ret) {
2286 PERROR("close");
2287 }
2288 sock = -1;
2289 continue;
2290 }
2291
2292 health_code_update();
2293 ret = ust_app_recv_registration(sock, &ust_cmd->reg_msg);
2294 if (ret < 0) {
2295 free(ust_cmd);
2296 /* Close socket of the application. */
2297 ret = close(sock);
2298 if (ret) {
2299 PERROR("close");
2300 }
2301 lttng_fd_put(LTTNG_FD_APPS, 1);
2302 sock = -1;
2303 continue;
2304 }
2305 health_code_update();
2306
2307 ust_cmd->sock = sock;
2308 sock = -1;
2309
2310 DBG("UST registration received with pid:%d ppid:%d uid:%d"
2311 " gid:%d sock:%d name:%s (version %d.%d)",
2312 ust_cmd->reg_msg.pid, ust_cmd->reg_msg.ppid,
2313 ust_cmd->reg_msg.uid, ust_cmd->reg_msg.gid,
2314 ust_cmd->sock, ust_cmd->reg_msg.name,
2315 ust_cmd->reg_msg.major, ust_cmd->reg_msg.minor);
2316
2317 /*
2318 * Lock free enqueue the registration request. The red pill
2319 * has been taken! This apps will be part of the *system*.
2320 */
2321 cds_wfcq_enqueue(&ust_cmd_queue.head, &ust_cmd_queue.tail, &ust_cmd->node);
2322
2323 /*
2324 * Wake the registration queue futex. Implicit memory
2325 * barrier with the exchange in cds_wfcq_enqueue.
2326 */
2327 futex_nto1_wake(&ust_cmd_queue.futex);
2328 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2329 ERR("Register apps socket poll error");
2330 goto error;
2331 } else {
2332 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
2333 goto error;
2334 }
2335 }
2336 }
2337 }
2338
2339 exit:
2340 error:
2341 /* Notify that the registration thread is gone */
2342 notify_ust_apps(0);
2343
2344 if (apps_sock >= 0) {
2345 ret = close(apps_sock);
2346 if (ret) {
2347 PERROR("close");
2348 }
2349 }
2350 if (sock >= 0) {
2351 ret = close(sock);
2352 if (ret) {
2353 PERROR("close");
2354 }
2355 lttng_fd_put(LTTNG_FD_APPS, 1);
2356 }
2357 unlink(apps_unix_sock_path);
2358
2359 error_poll_add:
2360 lttng_poll_clean(&events);
2361 error_listen:
2362 error_create_poll:
2363 error_testpoint:
2364 DBG("UST Registration thread cleanup complete");
2365 if (err) {
2366 health_error();
2367 ERR("Health error occurred in %s", __func__);
2368 }
2369 health_unregister(health_sessiond);
2370
2371 return NULL;
2372 }
2373
2374 /*
2375 * Start the thread_manage_consumer. This must be done after a lttng-consumerd
2376 * exec or it will fails.
2377 */
2378 static int spawn_consumer_thread(struct consumer_data *consumer_data)
2379 {
2380 int ret, clock_ret;
2381 struct timespec timeout;
2382
2383 /* Make sure we set the readiness flag to 0 because we are NOT ready */
2384 consumer_data->consumer_thread_is_ready = 0;
2385
2386 /* Setup pthread condition */
2387 ret = pthread_condattr_init(&consumer_data->condattr);
2388 if (ret) {
2389 errno = ret;
2390 PERROR("pthread_condattr_init consumer data");
2391 goto error;
2392 }
2393
2394 /*
2395 * Set the monotonic clock in order to make sure we DO NOT jump in time
2396 * between the clock_gettime() call and the timedwait call. See bug #324
2397 * for a more details and how we noticed it.
2398 */
2399 ret = pthread_condattr_setclock(&consumer_data->condattr, CLOCK_MONOTONIC);
2400 if (ret) {
2401 errno = ret;
2402 PERROR("pthread_condattr_setclock consumer data");
2403 goto error;
2404 }
2405
2406 ret = pthread_cond_init(&consumer_data->cond, &consumer_data->condattr);
2407 if (ret) {
2408 errno = ret;
2409 PERROR("pthread_cond_init consumer data");
2410 goto error;
2411 }
2412
2413 ret = pthread_create(&consumer_data->thread, NULL, thread_manage_consumer,
2414 consumer_data);
2415 if (ret) {
2416 errno = ret;
2417 PERROR("pthread_create consumer");
2418 ret = -1;
2419 goto error;
2420 }
2421
2422 /* We are about to wait on a pthread condition */
2423 pthread_mutex_lock(&consumer_data->cond_mutex);
2424
2425 /* Get time for sem_timedwait absolute timeout */
2426 clock_ret = clock_gettime(CLOCK_MONOTONIC, &timeout);
2427 /*
2428 * Set the timeout for the condition timed wait even if the clock gettime
2429 * call fails since we might loop on that call and we want to avoid to
2430 * increment the timeout too many times.
2431 */
2432 timeout.tv_sec += DEFAULT_SEM_WAIT_TIMEOUT;
2433
2434 /*
2435 * The following loop COULD be skipped in some conditions so this is why we
2436 * set ret to 0 in order to make sure at least one round of the loop is
2437 * done.
2438 */
2439 ret = 0;
2440
2441 /*
2442 * Loop until the condition is reached or when a timeout is reached. Note
2443 * that the pthread_cond_timedwait(P) man page specifies that EINTR can NOT
2444 * be returned but the pthread_cond(3), from the glibc-doc, says that it is
2445 * possible. This loop does not take any chances and works with both of
2446 * them.
2447 */
2448 while (!consumer_data->consumer_thread_is_ready && ret != ETIMEDOUT) {
2449 if (clock_ret < 0) {
2450 PERROR("clock_gettime spawn consumer");
2451 /* Infinite wait for the consumerd thread to be ready */
2452 ret = pthread_cond_wait(&consumer_data->cond,
2453 &consumer_data->cond_mutex);
2454 } else {
2455 ret = pthread_cond_timedwait(&consumer_data->cond,
2456 &consumer_data->cond_mutex, &timeout);
2457 }
2458 }
2459
2460 /* Release the pthread condition */
2461 pthread_mutex_unlock(&consumer_data->cond_mutex);
2462
2463 if (ret != 0) {
2464 errno = ret;
2465 if (ret == ETIMEDOUT) {
2466 int pth_ret;
2467
2468 /*
2469 * Call has timed out so we kill the kconsumerd_thread and return
2470 * an error.
2471 */
2472 ERR("Condition timed out. The consumer thread was never ready."
2473 " Killing it");
2474 pth_ret = pthread_cancel(consumer_data->thread);
2475 if (pth_ret < 0) {
2476 PERROR("pthread_cancel consumer thread");
2477 }
2478 } else {
2479 PERROR("pthread_cond_wait failed consumer thread");
2480 }
2481 /* Caller is expecting a negative value on failure. */
2482 ret = -1;
2483 goto error;
2484 }
2485
2486 pthread_mutex_lock(&consumer_data->pid_mutex);
2487 if (consumer_data->pid == 0) {
2488 ERR("Consumerd did not start");
2489 pthread_mutex_unlock(&consumer_data->pid_mutex);
2490 goto error;
2491 }
2492 pthread_mutex_unlock(&consumer_data->pid_mutex);
2493
2494 return 0;
2495
2496 error:
2497 return ret;
2498 }
2499
2500 /*
2501 * Join consumer thread
2502 */
2503 static int join_consumer_thread(struct consumer_data *consumer_data)
2504 {
2505 void *status;
2506
2507 /* Consumer pid must be a real one. */
2508 if (consumer_data->pid > 0) {
2509 int ret;
2510 ret = kill(consumer_data->pid, SIGTERM);
2511 if (ret) {
2512 PERROR("Error killing consumer daemon");
2513 return ret;
2514 }
2515 return pthread_join(consumer_data->thread, &status);
2516 } else {
2517 return 0;
2518 }
2519 }
2520
2521 /*
2522 * Fork and exec a consumer daemon (consumerd).
2523 *
2524 * Return pid if successful else -1.
2525 */
2526 static pid_t spawn_consumerd(struct consumer_data *consumer_data)
2527 {
2528 int ret;
2529 pid_t pid;
2530 const char *consumer_to_use;
2531 const char *verbosity;
2532 struct stat st;
2533
2534 DBG("Spawning consumerd");
2535
2536 pid = fork();
2537 if (pid == 0) {
2538 /*
2539 * Exec consumerd.
2540 */
2541 if (opt_verbose_consumer) {
2542 verbosity = "--verbose";
2543 } else if (lttng_opt_quiet) {
2544 verbosity = "--quiet";
2545 } else {
2546 verbosity = "";
2547 }
2548
2549 switch (consumer_data->type) {
2550 case LTTNG_CONSUMER_KERNEL:
2551 /*
2552 * Find out which consumerd to execute. We will first try the
2553 * 64-bit path, then the sessiond's installation directory, and
2554 * fallback on the 32-bit one,
2555 */
2556 DBG3("Looking for a kernel consumer at these locations:");
2557 DBG3(" 1) %s", consumerd64_bin);
2558 DBG3(" 2) %s/%s", INSTALL_BIN_PATH, CONSUMERD_FILE);
2559 DBG3(" 3) %s", consumerd32_bin);
2560 if (stat(consumerd64_bin, &st) == 0) {
2561 DBG3("Found location #1");
2562 consumer_to_use = consumerd64_bin;
2563 } else if (stat(INSTALL_BIN_PATH "/" CONSUMERD_FILE, &st) == 0) {
2564 DBG3("Found location #2");
2565 consumer_to_use = INSTALL_BIN_PATH "/" CONSUMERD_FILE;
2566 } else if (stat(consumerd32_bin, &st) == 0) {
2567 DBG3("Found location #3");
2568 consumer_to_use = consumerd32_bin;
2569 } else {
2570 DBG("Could not find any valid consumerd executable");
2571 ret = -EINVAL;
2572 break;
2573 }
2574 DBG("Using kernel consumer at: %s", consumer_to_use);
2575 ret = execl(consumer_to_use,
2576 "lttng-consumerd", verbosity, "-k",
2577 "--consumerd-cmd-sock", consumer_data->cmd_unix_sock_path,
2578 "--consumerd-err-sock", consumer_data->err_unix_sock_path,
2579 "--group", tracing_group_name,
2580 NULL);
2581 break;
2582 case LTTNG_CONSUMER64_UST:
2583 {
2584 char *tmpnew = NULL;
2585
2586 if (consumerd64_libdir[0] != '\0') {
2587 char *tmp;
2588 size_t tmplen;
2589
2590 tmp = lttng_secure_getenv("LD_LIBRARY_PATH");
2591 if (!tmp) {
2592 tmp = "";
2593 }
2594 tmplen = strlen("LD_LIBRARY_PATH=")
2595 + strlen(consumerd64_libdir) + 1 /* : */ + strlen(tmp);
2596 tmpnew = zmalloc(tmplen + 1 /* \0 */);
2597 if (!tmpnew) {
2598 ret = -ENOMEM;
2599 goto error;
2600 }
2601 strcpy(tmpnew, "LD_LIBRARY_PATH=");
2602 strcat(tmpnew, consumerd64_libdir);
2603 if (tmp[0] != '\0') {
2604 strcat(tmpnew, ":");
2605 strcat(tmpnew, tmp);
2606 }
2607 ret = putenv(tmpnew);
2608 if (ret) {
2609 ret = -errno;
2610 free(tmpnew);
2611 goto error;
2612 }
2613 }
2614 DBG("Using 64-bit UST consumer at: %s", consumerd64_bin);
2615 ret = execl(consumerd64_bin, "lttng-consumerd", verbosity, "-u",
2616 "--consumerd-cmd-sock", consumer_data->cmd_unix_sock_path,
2617 "--consumerd-err-sock", consumer_data->err_unix_sock_path,
2618 "--group", tracing_group_name,
2619 NULL);
2620 if (consumerd64_libdir[0] != '\0') {
2621 free(tmpnew);
2622 }
2623 break;
2624 }
2625 case LTTNG_CONSUMER32_UST:
2626 {
2627 char *tmpnew = NULL;
2628
2629 if (consumerd32_libdir[0] != '\0') {
2630 char *tmp;
2631 size_t tmplen;
2632
2633 tmp = lttng_secure_getenv("LD_LIBRARY_PATH");
2634 if (!tmp) {
2635 tmp = "";
2636 }
2637 tmplen = strlen("LD_LIBRARY_PATH=")
2638 + strlen(consumerd32_libdir) + 1 /* : */ + strlen(tmp);
2639 tmpnew = zmalloc(tmplen + 1 /* \0 */);
2640 if (!tmpnew) {
2641 ret = -ENOMEM;
2642 goto error;
2643 }
2644 strcpy(tmpnew, "LD_LIBRARY_PATH=");
2645 strcat(tmpnew, consumerd32_libdir);
2646 if (tmp[0] != '\0') {
2647 strcat(tmpnew, ":");
2648 strcat(tmpnew, tmp);
2649 }
2650 ret = putenv(tmpnew);
2651 if (ret) {
2652 ret = -errno;
2653 free(tmpnew);
2654 goto error;
2655 }
2656 }
2657 DBG("Using 32-bit UST consumer at: %s", consumerd32_bin);
2658 ret = execl(consumerd32_bin, "lttng-consumerd", verbosity, "-u",
2659 "--consumerd-cmd-sock", consumer_data->cmd_unix_sock_path,
2660 "--consumerd-err-sock", consumer_data->err_unix_sock_path,
2661 "--group", tracing_group_name,
2662 NULL);
2663 if (consumerd32_libdir[0] != '\0') {
2664 free(tmpnew);
2665 }
2666 break;
2667 }
2668 default:
2669 PERROR("unknown consumer type");
2670 exit(EXIT_FAILURE);
2671 }
2672 if (errno != 0) {
2673 PERROR("Consumer execl()");
2674 }
2675 /* Reaching this point, we got a failure on our execl(). */
2676 exit(EXIT_FAILURE);
2677 } else if (pid > 0) {
2678 ret = pid;
2679 } else {
2680 PERROR("start consumer fork");
2681 ret = -errno;
2682 }
2683 error:
2684 return ret;
2685 }
2686
2687 /*
2688 * Spawn the consumerd daemon and session daemon thread.
2689 */
2690 static int start_consumerd(struct consumer_data *consumer_data)
2691 {
2692 int ret;
2693
2694 /*
2695 * Set the listen() state on the socket since there is a possible race
2696 * between the exec() of the consumer daemon and this call if place in the
2697 * consumer thread. See bug #366 for more details.
2698 */
2699 ret = lttcomm_listen_unix_sock(consumer_data->err_sock);
2700 if (ret < 0) {
2701 goto error;
2702 }
2703
2704 pthread_mutex_lock(&consumer_data->pid_mutex);
2705 if (consumer_data->pid != 0) {
2706 pthread_mutex_unlock(&consumer_data->pid_mutex);
2707 goto end;
2708 }
2709
2710 ret = spawn_consumerd(consumer_data);
2711 if (ret < 0) {
2712 ERR("Spawning consumerd failed");
2713 pthread_mutex_unlock(&consumer_data->pid_mutex);
2714 goto error;
2715 }
2716
2717 /* Setting up the consumer_data pid */
2718 consumer_data->pid = ret;
2719 DBG2("Consumer pid %d", consumer_data->pid);
2720 pthread_mutex_unlock(&consumer_data->pid_mutex);
2721
2722 DBG2("Spawning consumer control thread");
2723 ret = spawn_consumer_thread(consumer_data);
2724 if (ret < 0) {
2725 ERR("Fatal error spawning consumer control thread");
2726 goto error;
2727 }
2728
2729 end:
2730 return 0;
2731
2732 error:
2733 /* Cleanup already created sockets on error. */
2734 if (consumer_data->err_sock >= 0) {
2735 int err;
2736
2737 err = close(consumer_data->err_sock);
2738 if (err < 0) {
2739 PERROR("close consumer data error socket");
2740 }
2741 }
2742 return ret;
2743 }
2744
2745 /*
2746 * Setup necessary data for kernel tracer action.
2747 */
2748 static int init_kernel_tracer(void)
2749 {
2750 int ret;
2751
2752 /* Modprobe lttng kernel modules */
2753 ret = modprobe_lttng_control();
2754 if (ret < 0) {
2755 goto error;
2756 }
2757
2758 /* Open debugfs lttng */
2759 kernel_tracer_fd = open(module_proc_lttng, O_RDWR);
2760 if (kernel_tracer_fd < 0) {
2761 DBG("Failed to open %s", module_proc_lttng);
2762 ret = -1;
2763 goto error_open;
2764 }
2765
2766 /* Validate kernel version */
2767 ret = kernel_validate_version(kernel_tracer_fd);
2768 if (ret < 0) {
2769 goto error_version;
2770 }
2771
2772 ret = modprobe_lttng_data();
2773 if (ret < 0) {
2774 goto error_modules;
2775 }
2776
2777 DBG("Kernel tracer fd %d", kernel_tracer_fd);
2778 return 0;
2779
2780 error_version:
2781 modprobe_remove_lttng_control();
2782 ret = close(kernel_tracer_fd);
2783 if (ret) {
2784 PERROR("close");
2785 }
2786 kernel_tracer_fd = -1;
2787 return LTTNG_ERR_KERN_VERSION;
2788
2789 error_modules:
2790 ret = close(kernel_tracer_fd);
2791 if (ret) {
2792 PERROR("close");
2793 }
2794
2795 error_open:
2796 modprobe_remove_lttng_control();
2797
2798 error:
2799 WARN("No kernel tracer available");
2800 kernel_tracer_fd = -1;
2801 if (!is_root) {
2802 return LTTNG_ERR_NEED_ROOT_SESSIOND;
2803 } else {
2804 return LTTNG_ERR_KERN_NA;
2805 }
2806 }
2807
2808
2809 /*
2810 * Copy consumer output from the tracing session to the domain session. The
2811 * function also applies the right modification on a per domain basis for the
2812 * trace files destination directory.
2813 *
2814 * Should *NOT* be called with RCU read-side lock held.
2815 */
2816 static int copy_session_consumer(int domain, struct ltt_session *session)
2817 {
2818 int ret;
2819 const char *dir_name;
2820 struct consumer_output *consumer;
2821
2822 assert(session);
2823 assert(session->consumer);
2824
2825 switch (domain) {
2826 case LTTNG_DOMAIN_KERNEL:
2827 DBG3("Copying tracing session consumer output in kernel session");
2828 /*
2829 * XXX: We should audit the session creation and what this function
2830 * does "extra" in order to avoid a destroy since this function is used
2831 * in the domain session creation (kernel and ust) only. Same for UST
2832 * domain.
2833 */
2834 if (session->kernel_session->consumer) {
2835 consumer_output_put(session->kernel_session->consumer);
2836 }
2837 session->kernel_session->consumer =
2838 consumer_copy_output(session->consumer);
2839 /* Ease our life a bit for the next part */
2840 consumer = session->kernel_session->consumer;
2841 dir_name = DEFAULT_KERNEL_TRACE_DIR;
2842 break;
2843 case LTTNG_DOMAIN_JUL:
2844 case LTTNG_DOMAIN_LOG4J:
2845 case LTTNG_DOMAIN_PYTHON:
2846 case LTTNG_DOMAIN_UST:
2847 DBG3("Copying tracing session consumer output in UST session");
2848 if (session->ust_session->consumer) {
2849 consumer_output_put(session->ust_session->consumer);
2850 }
2851 session->ust_session->consumer =
2852 consumer_copy_output(session->consumer);
2853 /* Ease our life a bit for the next part */
2854 consumer = session->ust_session->consumer;
2855 dir_name = DEFAULT_UST_TRACE_DIR;
2856 break;
2857 default:
2858 ret = LTTNG_ERR_UNKNOWN_DOMAIN;
2859 goto error;
2860 }
2861
2862 /* Append correct directory to subdir */
2863 strncat(consumer->subdir, dir_name,
2864 sizeof(consumer->subdir) - strlen(consumer->subdir) - 1);
2865 DBG3("Copy session consumer subdir %s", consumer->subdir);
2866
2867 ret = LTTNG_OK;
2868
2869 error:
2870 return ret;
2871 }
2872
2873 /*
2874 * Create an UST session and add it to the session ust list.
2875 *
2876 * Should *NOT* be called with RCU read-side lock held.
2877 */
2878 static int create_ust_session(struct ltt_session *session,
2879 struct lttng_domain *domain)
2880 {
2881 int ret;
2882 struct ltt_ust_session *lus = NULL;
2883
2884 assert(session);
2885 assert(domain);
2886 assert(session->consumer);
2887
2888 switch (domain->type) {
2889 case LTTNG_DOMAIN_JUL:
2890 case LTTNG_DOMAIN_LOG4J:
2891 case LTTNG_DOMAIN_PYTHON:
2892 case LTTNG_DOMAIN_UST:
2893 break;
2894 default:
2895 ERR("Unknown UST domain on create session %d", domain->type);
2896 ret = LTTNG_ERR_UNKNOWN_DOMAIN;
2897 goto error;
2898 }
2899
2900 DBG("Creating UST session");
2901
2902 lus = trace_ust_create_session(session->id);
2903 if (lus == NULL) {
2904 ret = LTTNG_ERR_UST_SESS_FAIL;
2905 goto error;
2906 }
2907
2908 lus->uid = session->uid;
2909 lus->gid = session->gid;
2910 lus->output_traces = session->output_traces;
2911 lus->snapshot_mode = session->snapshot_mode;
2912 lus->live_timer_interval = session->live_timer;
2913 session->ust_session = lus;
2914 if (session->shm_path[0]) {
2915 strncpy(lus->root_shm_path, session->shm_path,
2916 sizeof(lus->root_shm_path));
2917 lus->root_shm_path[sizeof(lus->root_shm_path) - 1] = '\0';
2918 strncpy(lus->shm_path, session->shm_path,
2919 sizeof(lus->shm_path));
2920 lus->shm_path[sizeof(lus->shm_path) - 1] = '\0';
2921 strncat(lus->shm_path, "/ust",
2922 sizeof(lus->shm_path) - strlen(lus->shm_path) - 1);
2923 }
2924 /* Copy session output to the newly created UST session */
2925 ret = copy_session_consumer(domain->type, session);
2926 if (ret != LTTNG_OK) {
2927 goto error;
2928 }
2929
2930 return LTTNG_OK;
2931
2932 error:
2933 free(lus);
2934 session->ust_session = NULL;
2935 return ret;
2936 }
2937
2938 /*
2939 * Create a kernel tracer session then create the default channel.
2940 */
2941 static int create_kernel_session(struct ltt_session *session)
2942 {
2943 int ret;
2944
2945 DBG("Creating kernel session");
2946
2947 ret = kernel_create_session(session, kernel_tracer_fd);
2948 if (ret < 0) {
2949 ret = LTTNG_ERR_KERN_SESS_FAIL;
2950 goto error;
2951 }
2952
2953 /* Code flow safety */
2954 assert(session->kernel_session);
2955
2956 /* Copy session output to the newly created Kernel session */
2957 ret = copy_session_consumer(LTTNG_DOMAIN_KERNEL, session);
2958 if (ret != LTTNG_OK) {
2959 goto error;
2960 }
2961
2962 /* Create directory(ies) on local filesystem. */
2963 if (session->kernel_session->consumer->type == CONSUMER_DST_LOCAL &&
2964 strlen(session->kernel_session->consumer->dst.trace_path) > 0) {
2965 ret = run_as_mkdir_recursive(
2966 session->kernel_session->consumer->dst.trace_path,
2967 S_IRWXU | S_IRWXG, session->uid, session->gid);
2968 if (ret < 0) {
2969 if (errno != EEXIST) {
2970 ERR("Trace directory creation error");
2971 goto error;
2972 }
2973 }
2974 }
2975
2976 session->kernel_session->uid = session->uid;
2977 session->kernel_session->gid = session->gid;
2978 session->kernel_session->output_traces = session->output_traces;
2979 session->kernel_session->snapshot_mode = session->snapshot_mode;
2980
2981 return LTTNG_OK;
2982
2983 error:
2984 trace_kernel_destroy_session(session->kernel_session);
2985 session->kernel_session = NULL;
2986 return ret;
2987 }
2988
2989 /*
2990 * Count number of session permitted by uid/gid.
2991 */
2992 static unsigned int lttng_sessions_count(uid_t uid, gid_t gid)
2993 {
2994 unsigned int i = 0;
2995 struct ltt_session *session;
2996
2997 DBG("Counting number of available session for UID %d GID %d",
2998 uid, gid);
2999 cds_list_for_each_entry(session, &session_list_ptr->head, list) {
3000 /*
3001 * Only list the sessions the user can control.
3002 */
3003 if (!session_access_ok(session, uid, gid)) {
3004 continue;
3005 }
3006 i++;
3007 }
3008 return i;
3009 }
3010
3011 /*
3012 * Process the command requested by the lttng client within the command
3013 * context structure. This function make sure that the return structure (llm)
3014 * is set and ready for transmission before returning.
3015 *
3016 * Return any error encountered or 0 for success.
3017 *
3018 * "sock" is only used for special-case var. len data.
3019 *
3020 * Should *NOT* be called with RCU read-side lock held.
3021 */
3022 static int process_client_msg(struct command_ctx *cmd_ctx, int sock,
3023 int *sock_error)
3024 {
3025 int ret = LTTNG_OK;
3026 int need_tracing_session = 1;
3027 int need_domain;
3028
3029 DBG("Processing client command %d", cmd_ctx->lsm->cmd_type);
3030
3031 assert(!rcu_read_ongoing());
3032
3033 *sock_error = 0;
3034
3035 switch (cmd_ctx->lsm->cmd_type) {
3036 case LTTNG_CREATE_SESSION:
3037 case LTTNG_CREATE_SESSION_SNAPSHOT:
3038 case LTTNG_CREATE_SESSION_LIVE:
3039 case LTTNG_DESTROY_SESSION:
3040 case LTTNG_LIST_SESSIONS:
3041 case LTTNG_LIST_DOMAINS:
3042 case LTTNG_START_TRACE:
3043 case LTTNG_STOP_TRACE:
3044 case LTTNG_DATA_PENDING:
3045 case LTTNG_SNAPSHOT_ADD_OUTPUT:
3046 case LTTNG_SNAPSHOT_DEL_OUTPUT:
3047 case LTTNG_SNAPSHOT_LIST_OUTPUT:
3048 case LTTNG_SNAPSHOT_RECORD:
3049 case LTTNG_SAVE_SESSION:
3050 case LTTNG_SET_SESSION_SHM_PATH:
3051 case LTTNG_METADATA_REGENERATE:
3052 need_domain = 0;
3053 break;
3054 default:
3055 need_domain = 1;
3056 }
3057
3058 if (opt_no_kernel && need_domain
3059 && cmd_ctx->lsm->domain.type == LTTNG_DOMAIN_KERNEL) {
3060 if (!is_root) {
3061 ret = LTTNG_ERR_NEED_ROOT_SESSIOND;
3062 } else {
3063 ret = LTTNG_ERR_KERN_NA;
3064 }
3065 goto error;
3066 }
3067
3068 /* Deny register consumer if we already have a spawned consumer. */
3069 if (cmd_ctx->lsm->cmd_type == LTTNG_REGISTER_CONSUMER) {
3070 pthread_mutex_lock(&kconsumer_data.pid_mutex);
3071 if (kconsumer_data.pid > 0) {
3072 ret = LTTNG_ERR_KERN_CONSUMER_FAIL;
3073 pthread_mutex_unlock(&kconsumer_data.pid_mutex);
3074 goto error;
3075 }
3076 pthread_mutex_unlock(&kconsumer_data.pid_mutex);
3077 }
3078
3079 /*
3080 * Check for command that don't needs to allocate a returned payload. We do
3081 * this here so we don't have to make the call for no payload at each
3082 * command.
3083 */
3084 switch(cmd_ctx->lsm->cmd_type) {
3085 case LTTNG_LIST_SESSIONS:
3086 case LTTNG_LIST_TRACEPOINTS:
3087 case LTTNG_LIST_TRACEPOINT_FIELDS:
3088 case LTTNG_LIST_DOMAINS:
3089 case LTTNG_LIST_CHANNELS:
3090 case LTTNG_LIST_EVENTS:
3091 case LTTNG_LIST_SYSCALLS:
3092 case LTTNG_LIST_TRACKER_PIDS:
3093 case LTTNG_DATA_PENDING:
3094 break;
3095 default:
3096 /* Setup lttng message with no payload */
3097 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, NULL, 0);
3098 if (ret < 0) {
3099 /* This label does not try to unlock the session */
3100 goto init_setup_error;
3101 }
3102 }
3103
3104 /* Commands that DO NOT need a session. */
3105 switch (cmd_ctx->lsm->cmd_type) {
3106 case LTTNG_CREATE_SESSION:
3107 case LTTNG_CREATE_SESSION_SNAPSHOT:
3108 case LTTNG_CREATE_SESSION_LIVE:
3109 case LTTNG_CALIBRATE:
3110 case LTTNG_LIST_SESSIONS:
3111 case LTTNG_LIST_TRACEPOINTS:
3112 case LTTNG_LIST_SYSCALLS:
3113 case LTTNG_LIST_TRACEPOINT_FIELDS:
3114 case LTTNG_SAVE_SESSION:
3115 need_tracing_session = 0;
3116 break;
3117 default:
3118 DBG("Getting session %s by name", cmd_ctx->lsm->session.name);
3119 /*
3120 * We keep the session list lock across _all_ commands
3121 * for now, because the per-session lock does not
3122 * handle teardown properly.
3123 */
3124 session_lock_list();
3125 cmd_ctx->session = session_find_by_name(cmd_ctx->lsm->session.name);
3126 if (cmd_ctx->session == NULL) {
3127 ret = LTTNG_ERR_SESS_NOT_FOUND;
3128 goto error;
3129 } else {
3130 /* Acquire lock for the session */
3131 session_lock(cmd_ctx->session);
3132 }
3133 break;
3134 }
3135
3136 /*
3137 * Commands that need a valid session but should NOT create one if none
3138 * exists. Instead of creating one and destroying it when the command is
3139 * handled, process that right before so we save some round trip in useless
3140 * code path.
3141 */
3142 switch (cmd_ctx->lsm->cmd_type) {
3143 case LTTNG_DISABLE_CHANNEL:
3144 case LTTNG_DISABLE_EVENT:
3145 switch (cmd_ctx->lsm->domain.type) {
3146 case LTTNG_DOMAIN_KERNEL:
3147 if (!cmd_ctx->session->kernel_session) {
3148 ret = LTTNG_ERR_NO_CHANNEL;
3149 goto error;
3150 }
3151 break;
3152 case LTTNG_DOMAIN_JUL:
3153 case LTTNG_DOMAIN_LOG4J:
3154 case LTTNG_DOMAIN_PYTHON:
3155 case LTTNG_DOMAIN_UST:
3156 if (!cmd_ctx->session->ust_session) {
3157 ret = LTTNG_ERR_NO_CHANNEL;
3158 goto error;
3159 }
3160 break;
3161 default:
3162 ret = LTTNG_ERR_UNKNOWN_DOMAIN;
3163 goto error;
3164 }
3165 default:
3166 break;
3167 }
3168
3169 if (!need_domain) {
3170 goto skip_domain;
3171 }
3172
3173 /*
3174 * Check domain type for specific "pre-action".
3175 */
3176 switch (cmd_ctx->lsm->domain.type) {
3177 case LTTNG_DOMAIN_KERNEL:
3178 if (!is_root) {
3179 ret = LTTNG_ERR_NEED_ROOT_SESSIOND;
3180 goto error;
3181 }
3182
3183 /* Kernel tracer check */
3184 if (kernel_tracer_fd == -1) {
3185 /* Basically, load kernel tracer modules */
3186 ret = init_kernel_tracer();
3187 if (ret != 0) {
3188 goto error;
3189 }
3190 }
3191
3192 /* Consumer is in an ERROR state. Report back to client */
3193 if (uatomic_read(&kernel_consumerd_state) == CONSUMER_ERROR) {
3194 ret = LTTNG_ERR_NO_KERNCONSUMERD;
3195 goto error;
3196 }
3197
3198 /* Need a session for kernel command */
3199 if (need_tracing_session) {
3200 if (cmd_ctx->session->kernel_session == NULL) {
3201 ret = create_kernel_session(cmd_ctx->session);
3202 if (ret < 0) {
3203 ret = LTTNG_ERR_KERN_SESS_FAIL;
3204 goto error;
3205 }
3206 }
3207
3208 /* Start the kernel consumer daemon */
3209 pthread_mutex_lock(&kconsumer_data.pid_mutex);
3210 if (kconsumer_data.pid == 0 &&
3211 cmd_ctx->lsm->cmd_type != LTTNG_REGISTER_CONSUMER) {
3212 pthread_mutex_unlock(&kconsumer_data.pid_mutex);
3213 ret = start_consumerd(&kconsumer_data);
3214 if (ret < 0) {
3215 ret = LTTNG_ERR_KERN_CONSUMER_FAIL;
3216 goto error;
3217 }
3218 uatomic_set(&kernel_consumerd_state, CONSUMER_STARTED);
3219 } else {
3220 pthread_mutex_unlock(&kconsumer_data.pid_mutex);
3221 }
3222
3223 /*
3224 * The consumer was just spawned so we need to add the socket to
3225 * the consumer output of the session if exist.
3226 */
3227 ret = consumer_create_socket(&kconsumer_data,
3228 cmd_ctx->session->kernel_session->consumer);
3229 if (ret < 0) {
3230 goto error;
3231 }
3232 }
3233
3234 break;
3235 case LTTNG_DOMAIN_JUL:
3236 case LTTNG_DOMAIN_LOG4J:
3237 case LTTNG_DOMAIN_PYTHON:
3238 case LTTNG_DOMAIN_UST:
3239 {
3240 if (!ust_app_supported()) {
3241 ret = LTTNG_ERR_NO_UST;
3242 goto error;
3243 }
3244 /* Consumer is in an ERROR state. Report back to client */
3245 if (uatomic_read(&ust_consumerd_state) == CONSUMER_ERROR) {
3246 ret = LTTNG_ERR_NO_USTCONSUMERD;
3247 goto error;
3248 }
3249
3250 if (need_tracing_session) {
3251 /* Create UST session if none exist. */
3252 if (cmd_ctx->session->ust_session == NULL) {
3253 ret = create_ust_session(cmd_ctx->session,
3254 &cmd_ctx->lsm->domain);
3255 if (ret != LTTNG_OK) {
3256 goto error;
3257 }
3258 }
3259
3260 /* Start the UST consumer daemons */
3261 /* 64-bit */
3262 pthread_mutex_lock(&ustconsumer64_data.pid_mutex);
3263 if (consumerd64_bin[0] != '\0' &&
3264 ustconsumer64_data.pid == 0 &&
3265 cmd_ctx->lsm->cmd_type != LTTNG_REGISTER_CONSUMER) {
3266 pthread_mutex_unlock(&ustconsumer64_data.pid_mutex);
3267 ret = start_consumerd(&ustconsumer64_data);
3268 if (ret < 0) {
3269 ret = LTTNG_ERR_UST_CONSUMER64_FAIL;
3270 uatomic_set(&ust_consumerd64_fd, -EINVAL);
3271 goto error;
3272 }
3273
3274 uatomic_set(&ust_consumerd64_fd, ustconsumer64_data.cmd_sock);
3275 uatomic_set(&ust_consumerd_state, CONSUMER_STARTED);
3276 } else {
3277 pthread_mutex_unlock(&ustconsumer64_data.pid_mutex);
3278 }
3279
3280 /*
3281 * Setup socket for consumer 64 bit. No need for atomic access
3282 * since it was set above and can ONLY be set in this thread.
3283 */
3284 ret = consumer_create_socket(&ustconsumer64_data,
3285 cmd_ctx->session->ust_session->consumer);
3286 if (ret < 0) {
3287 goto error;
3288 }
3289
3290 /* 32-bit */
3291 pthread_mutex_lock(&ustconsumer32_data.pid_mutex);
3292 if (consumerd32_bin[0] != '\0' &&
3293 ustconsumer32_data.pid == 0 &&
3294 cmd_ctx->lsm->cmd_type != LTTNG_REGISTER_CONSUMER) {
3295 pthread_mutex_unlock(&ustconsumer32_data.pid_mutex);
3296 ret = start_consumerd(&ustconsumer32_data);
3297 if (ret < 0) {
3298 ret = LTTNG_ERR_UST_CONSUMER32_FAIL;
3299 uatomic_set(&ust_consumerd32_fd, -EINVAL);
3300 goto error;
3301 }
3302
3303 uatomic_set(&ust_consumerd32_fd, ustconsumer32_data.cmd_sock);
3304 uatomic_set(&ust_consumerd_state, CONSUMER_STARTED);
3305 } else {
3306 pthread_mutex_unlock(&ustconsumer32_data.pid_mutex);
3307 }
3308
3309 /*
3310 * Setup socket for consumer 64 bit. No need for atomic access
3311 * since it was set above and can ONLY be set in this thread.
3312 */
3313 ret = consumer_create_socket(&ustconsumer32_data,
3314 cmd_ctx->session->ust_session->consumer);
3315 if (ret < 0) {
3316 goto error;
3317 }
3318 }
3319 break;
3320 }
3321 default:
3322 break;
3323 }
3324 skip_domain:
3325
3326 /* Validate consumer daemon state when start/stop trace command */
3327 if (cmd_ctx->lsm->cmd_type == LTTNG_START_TRACE ||
3328 cmd_ctx->lsm->cmd_type == LTTNG_STOP_TRACE) {
3329 switch (cmd_ctx->lsm->domain.type) {
3330 case LTTNG_DOMAIN_NONE:
3331 break;
3332 case LTTNG_DOMAIN_JUL:
3333 case LTTNG_DOMAIN_LOG4J:
3334 case LTTNG_DOMAIN_PYTHON:
3335 case LTTNG_DOMAIN_UST:
3336 if (uatomic_read(&ust_consumerd_state) != CONSUMER_STARTED) {
3337 ret = LTTNG_ERR_NO_USTCONSUMERD;
3338 goto error;
3339 }
3340 break;
3341 case LTTNG_DOMAIN_KERNEL:
3342 if (uatomic_read(&kernel_consumerd_state) != CONSUMER_STARTED) {
3343 ret = LTTNG_ERR_NO_KERNCONSUMERD;
3344 goto error;
3345 }
3346 break;
3347 default:
3348 ret = LTTNG_ERR_UNKNOWN_DOMAIN;
3349 goto error;
3350 }
3351 }
3352
3353 /*
3354 * Check that the UID or GID match that of the tracing session.
3355 * The root user can interact with all sessions.
3356 */
3357 if (need_tracing_session) {
3358 if (!session_access_ok(cmd_ctx->session,
3359 LTTNG_SOCK_GET_UID_CRED(&cmd_ctx->creds),
3360 LTTNG_SOCK_GET_GID_CRED(&cmd_ctx->creds))) {
3361 ret = LTTNG_ERR_EPERM;
3362 goto error;
3363 }
3364 }
3365
3366 /*
3367 * Send relayd information to consumer as soon as we have a domain and a
3368 * session defined.
3369 */
3370 if (cmd_ctx->session && need_domain) {
3371 /*
3372 * Setup relayd if not done yet. If the relayd information was already
3373 * sent to the consumer, this call will gracefully return.
3374 */
3375 ret = cmd_setup_relayd(cmd_ctx->session);
3376 if (ret != LTTNG_OK) {
3377 goto error;
3378 }
3379 }
3380
3381 /* Process by command type */
3382 switch (cmd_ctx->lsm->cmd_type) {
3383 case LTTNG_ADD_CONTEXT:
3384 {
3385 /*
3386 * An LTTNG_ADD_CONTEXT command might have a supplementary
3387 * payload if the context being added is an application context.
3388 */
3389 if (cmd_ctx->lsm->u.context.ctx.ctx ==
3390 LTTNG_EVENT_CONTEXT_APP_CONTEXT) {
3391 char *provider_name = NULL, *context_name = NULL;
3392 size_t provider_name_len =
3393 cmd_ctx->lsm->u.context.provider_name_len;
3394 size_t context_name_len =
3395 cmd_ctx->lsm->u.context.context_name_len;
3396
3397 if (provider_name_len == 0 || context_name_len == 0) {
3398 /*
3399 * Application provider and context names MUST
3400 * be provided.
3401 */
3402 ret = -LTTNG_ERR_INVALID;
3403 goto error;
3404 }
3405
3406 provider_name = zmalloc(provider_name_len + 1);
3407 if (!provider_name) {
3408 ret = -LTTNG_ERR_NOMEM;
3409 goto error;
3410 }
3411 cmd_ctx->lsm->u.context.ctx.u.app_ctx.provider_name =
3412 provider_name;
3413
3414 context_name = zmalloc(context_name_len + 1);
3415 if (!context_name) {
3416 ret = -LTTNG_ERR_NOMEM;
3417 goto error_add_context;
3418 }
3419 cmd_ctx->lsm->u.context.ctx.u.app_ctx.ctx_name =
3420 context_name;
3421
3422 ret = lttcomm_recv_unix_sock(sock, provider_name,
3423 provider_name_len);
3424 if (ret < 0) {
3425 goto error_add_context;
3426 }
3427
3428 ret = lttcomm_recv_unix_sock(sock, context_name,
3429 context_name_len);
3430 if (ret < 0) {
3431 goto error_add_context;
3432 }
3433 }
3434
3435 /*
3436 * cmd_add_context assumes ownership of the provider and context
3437 * names.
3438 */
3439 ret = cmd_add_context(cmd_ctx->session,
3440 cmd_ctx->lsm->domain.type,
3441 cmd_ctx->lsm->u.context.channel_name,
3442 &cmd_ctx->lsm->u.context.ctx,
3443 kernel_poll_pipe[1]);
3444
3445 cmd_ctx->lsm->u.context.ctx.u.app_ctx.provider_name = NULL;
3446 cmd_ctx->lsm->u.context.ctx.u.app_ctx.ctx_name = NULL;
3447 error_add_context:
3448 free(cmd_ctx->lsm->u.context.ctx.u.app_ctx.provider_name);
3449 free(cmd_ctx->lsm->u.context.ctx.u.app_ctx.ctx_name);
3450 if (ret < 0) {
3451 goto error;
3452 }
3453 break;
3454 }
3455 case LTTNG_DISABLE_CHANNEL:
3456 {
3457 ret = cmd_disable_channel(cmd_ctx->session, cmd_ctx->lsm->domain.type,
3458 cmd_ctx->lsm->u.disable.channel_name);
3459 break;
3460 }
3461 case LTTNG_DISABLE_EVENT:
3462 {
3463
3464 /*
3465 * FIXME: handle filter; for now we just receive the filter's
3466 * bytecode along with the filter expression which are sent by
3467 * liblttng-ctl and discard them.
3468 *
3469 * This fixes an issue where the client may block while sending
3470 * the filter payload and encounter an error because the session
3471 * daemon closes the socket without ever handling this data.
3472 */
3473 size_t count = cmd_ctx->lsm->u.disable.expression_len +
3474 cmd_ctx->lsm->u.disable.bytecode_len;
3475
3476 if (count) {
3477 char data[LTTNG_FILTER_MAX_LEN];
3478
3479 DBG("Discarding disable event command payload of size %zu", count);
3480 while (count) {
3481 ret = lttcomm_recv_unix_sock(sock, data,
3482 count > sizeof(data) ? sizeof(data) : count);
3483 if (ret < 0) {
3484 goto error;
3485 }
3486
3487 count -= (size_t) ret;
3488 }
3489 }
3490 /* FIXME: passing packed structure to non-packed pointer */
3491 ret = cmd_disable_event(cmd_ctx->session, cmd_ctx->lsm->domain.type,
3492 cmd_ctx->lsm->u.disable.channel_name,
3493 &cmd_ctx->lsm->u.disable.event);
3494 break;
3495 }
3496 case LTTNG_ENABLE_CHANNEL:
3497 {
3498 ret = cmd_enable_channel(cmd_ctx->session, &cmd_ctx->lsm->domain,
3499 &cmd_ctx->lsm->u.channel.chan, kernel_poll_pipe[1]);
3500 break;
3501 }
3502 case LTTNG_TRACK_PID:
3503 {
3504 ret = cmd_track_pid(cmd_ctx->session,
3505 cmd_ctx->lsm->domain.type,
3506 cmd_ctx->lsm->u.pid_tracker.pid);
3507 break;
3508 }
3509 case LTTNG_UNTRACK_PID:
3510 {
3511 ret = cmd_untrack_pid(cmd_ctx->session,
3512 cmd_ctx->lsm->domain.type,
3513 cmd_ctx->lsm->u.pid_tracker.pid);
3514 break;
3515 }
3516 case LTTNG_ENABLE_EVENT:
3517 {
3518 struct lttng_event_exclusion *exclusion = NULL;
3519 struct lttng_filter_bytecode *bytecode = NULL;
3520 char *filter_expression = NULL;
3521
3522 /* Handle exclusion events and receive it from the client. */
3523 if (cmd_ctx->lsm->u.enable.exclusion_count > 0) {
3524 size_t count = cmd_ctx->lsm->u.enable.exclusion_count;
3525
3526 exclusion = zmalloc(sizeof(struct lttng_event_exclusion) +
3527 (count * LTTNG_SYMBOL_NAME_LEN));
3528 if (!exclusion) {
3529 ret = LTTNG_ERR_EXCLUSION_NOMEM;
3530 goto error;
3531 }
3532
3533 DBG("Receiving var len exclusion event list from client ...");
3534 exclusion->count = count;
3535 ret = lttcomm_recv_unix_sock(sock, exclusion->names,
3536 count * LTTNG_SYMBOL_NAME_LEN);
3537 if (ret <= 0) {
3538 DBG("Nothing recv() from client var len data... continuing");
3539 *sock_error = 1;
3540 free(exclusion);
3541 ret = LTTNG_ERR_EXCLUSION_INVAL;
3542 goto error;
3543 }
3544 }
3545
3546 /* Get filter expression from client. */
3547 if (cmd_ctx->lsm->u.enable.expression_len > 0) {
3548 size_t expression_len =
3549 cmd_ctx->lsm->u.enable.expression_len;
3550
3551 if (expression_len > LTTNG_FILTER_MAX_LEN) {
3552 ret = LTTNG_ERR_FILTER_INVAL;
3553 free(exclusion);
3554 goto error;
3555 }
3556
3557 filter_expression = zmalloc(expression_len);
3558 if (!filter_expression) {
3559 free(exclusion);
3560 ret = LTTNG_ERR_FILTER_NOMEM;
3561 goto error;
3562 }
3563
3564 /* Receive var. len. data */
3565 DBG("Receiving var len filter's expression from client ...");
3566 ret = lttcomm_recv_unix_sock(sock, filter_expression,
3567 expression_len);
3568 if (ret <= 0) {
3569 DBG("Nothing recv() from client car len data... continuing");
3570 *sock_error = 1;
3571 free(filter_expression);
3572 free(exclusion);
3573 ret = LTTNG_ERR_FILTER_INVAL;
3574 goto error;
3575 }
3576 }
3577
3578 /* Handle filter and get bytecode from client. */
3579 if (cmd_ctx->lsm->u.enable.bytecode_len > 0) {
3580 size_t bytecode_len = cmd_ctx->lsm->u.enable.bytecode_len;
3581
3582 if (bytecode_len > LTTNG_FILTER_MAX_LEN) {
3583 ret = LTTNG_ERR_FILTER_INVAL;
3584 free(filter_expression);
3585 free(exclusion);
3586 goto error;
3587 }
3588
3589 bytecode = zmalloc(bytecode_len);
3590 if (!bytecode) {
3591 free(filter_expression);
3592 free(exclusion);
3593 ret = LTTNG_ERR_FILTER_NOMEM;
3594 goto error;
3595 }
3596
3597 /* Receive var. len. data */
3598 DBG("Receiving var len filter's bytecode from client ...");
3599 ret = lttcomm_recv_unix_sock(sock, bytecode, bytecode_len);
3600 if (ret <= 0) {
3601 DBG("Nothing recv() from client car len data... continuing");
3602 *sock_error = 1;
3603 free(filter_expression);
3604 free(bytecode);
3605 free(exclusion);
3606 ret = LTTNG_ERR_FILTER_INVAL;
3607 goto error;
3608 }
3609
3610 if ((bytecode->len + sizeof(*bytecode)) != bytecode_len) {
3611 free(filter_expression);
3612 free(bytecode);
3613 free(exclusion);
3614 ret = LTTNG_ERR_FILTER_INVAL;
3615 goto error;
3616 }
3617 }
3618
3619 ret = cmd_enable_event(cmd_ctx->session, &cmd_ctx->lsm->domain,
3620 cmd_ctx->lsm->u.enable.channel_name,
3621 &cmd_ctx->lsm->u.enable.event,
3622 filter_expression, bytecode, exclusion,
3623 kernel_poll_pipe[1]);
3624 break;
3625 }
3626 case LTTNG_LIST_TRACEPOINTS:
3627 {
3628 struct lttng_event *events;
3629 ssize_t nb_events;
3630
3631 session_lock_list();
3632 nb_events = cmd_list_tracepoints(cmd_ctx->lsm->domain.type, &events);
3633 session_unlock_list();
3634 if (nb_events < 0) {
3635 /* Return value is a negative lttng_error_code. */
3636 ret = -nb_events;
3637 goto error;
3638 }
3639
3640 /*
3641 * Setup lttng message with payload size set to the event list size in
3642 * bytes and then copy list into the llm payload.
3643 */
3644 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, events,
3645 sizeof(struct lttng_event) * nb_events);
3646 free(events);
3647
3648 if (ret < 0) {
3649 goto setup_error;
3650 }
3651
3652 ret = LTTNG_OK;
3653 break;
3654 }
3655 case LTTNG_LIST_TRACEPOINT_FIELDS:
3656 {
3657 struct lttng_event_field *fields;
3658 ssize_t nb_fields;
3659
3660 session_lock_list();
3661 nb_fields = cmd_list_tracepoint_fields(cmd_ctx->lsm->domain.type,
3662 &fields);
3663 session_unlock_list();
3664 if (nb_fields < 0) {
3665 /* Return value is a negative lttng_error_code. */
3666 ret = -nb_fields;
3667 goto error;
3668 }
3669
3670 /*
3671 * Setup lttng message with payload size set to the event list size in
3672 * bytes and then copy list into the llm payload.
3673 */
3674 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, fields,
3675 sizeof(struct lttng_event_field) * nb_fields);
3676 free(fields);
3677
3678 if (ret < 0) {
3679 goto setup_error;
3680 }
3681
3682 ret = LTTNG_OK;
3683 break;
3684 }
3685 case LTTNG_LIST_SYSCALLS:
3686 {
3687 struct lttng_event *events;
3688 ssize_t nb_events;
3689
3690 nb_events = cmd_list_syscalls(&events);
3691 if (nb_events < 0) {
3692 /* Return value is a negative lttng_error_code. */
3693 ret = -nb_events;
3694 goto error;
3695 }
3696
3697 /*
3698 * Setup lttng message with payload size set to the event list size in
3699 * bytes and then copy list into the llm payload.
3700 */
3701 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, events,
3702 sizeof(struct lttng_event) * nb_events);
3703 free(events);
3704
3705 if (ret < 0) {
3706 goto setup_error;
3707 }
3708
3709 ret = LTTNG_OK;
3710 break;
3711 }
3712 case LTTNG_LIST_TRACKER_PIDS:
3713 {
3714 int32_t *pids = NULL;
3715 ssize_t nr_pids;
3716
3717 nr_pids = cmd_list_tracker_pids(cmd_ctx->session,
3718 cmd_ctx->lsm->domain.type, &pids);
3719 if (nr_pids < 0) {
3720 /* Return value is a negative lttng_error_code. */
3721 ret = -nr_pids;
3722 goto error;
3723 }
3724
3725 /*
3726 * Setup lttng message with payload size set to the event list size in
3727 * bytes and then copy list into the llm payload.
3728 */
3729 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, pids,
3730 sizeof(int32_t) * nr_pids);
3731 free(pids);
3732
3733 if (ret < 0) {
3734 goto setup_error;
3735 }
3736
3737 ret = LTTNG_OK;
3738 break;
3739 }
3740 case LTTNG_SET_CONSUMER_URI:
3741 {
3742 size_t nb_uri, len;
3743 struct lttng_uri *uris;
3744
3745 nb_uri = cmd_ctx->lsm->u.uri.size;
3746 len = nb_uri * sizeof(struct lttng_uri);
3747
3748 if (nb_uri == 0) {
3749 ret = LTTNG_ERR_INVALID;
3750 goto error;
3751 }
3752
3753 uris = zmalloc(len);
3754 if (uris == NULL) {
3755 ret = LTTNG_ERR_FATAL;
3756 goto error;
3757 }
3758
3759 /* Receive variable len data */
3760 DBG("Receiving %zu URI(s) from client ...", nb_uri);
3761 ret = lttcomm_recv_unix_sock(sock, uris, len);
3762 if (ret <= 0) {
3763 DBG("No URIs received from client... continuing");
3764 *sock_error = 1;
3765 ret = LTTNG_ERR_SESSION_FAIL;
3766 free(uris);
3767 goto error;
3768 }
3769
3770 ret = cmd_set_consumer_uri(cmd_ctx->session, nb_uri, uris);
3771 free(uris);
3772 if (ret != LTTNG_OK) {
3773 goto error;
3774 }
3775
3776
3777 break;
3778 }
3779 case LTTNG_START_TRACE:
3780 {
3781 ret = cmd_start_trace(cmd_ctx->session);
3782 break;
3783 }
3784 case LTTNG_STOP_TRACE:
3785 {
3786 ret = cmd_stop_trace(cmd_ctx->session);
3787 break;
3788 }
3789 case LTTNG_CREATE_SESSION:
3790 {
3791 size_t nb_uri, len;
3792 struct lttng_uri *uris = NULL;
3793
3794 nb_uri = cmd_ctx->lsm->u.uri.size;
3795 len = nb_uri * sizeof(struct lttng_uri);
3796
3797 if (nb_uri > 0) {
3798 uris = zmalloc(len);
3799 if (uris == NULL) {
3800 ret = LTTNG_ERR_FATAL;
3801 goto error;
3802 }
3803
3804 /* Receive variable len data */
3805 DBG("Waiting for %zu URIs from client ...", nb_uri);
3806 ret = lttcomm_recv_unix_sock(sock, uris, len);
3807 if (ret <= 0) {
3808 DBG("No URIs received from client... continuing");
3809 *sock_error = 1;
3810 ret = LTTNG_ERR_SESSION_FAIL;
3811 free(uris);
3812 goto error;
3813 }
3814
3815 if (nb_uri == 1 && uris[0].dtype != LTTNG_DST_PATH) {
3816 DBG("Creating session with ONE network URI is a bad call");
3817 ret = LTTNG_ERR_SESSION_FAIL;
3818 free(uris);
3819 goto error;
3820 }
3821 }
3822
3823 ret = cmd_create_session_uri(cmd_ctx->lsm->session.name, uris, nb_uri,
3824 &cmd_ctx->creds, 0);
3825
3826 free(uris);
3827
3828 break;
3829 }
3830 case LTTNG_DESTROY_SESSION:
3831 {
3832 ret = cmd_destroy_session(cmd_ctx->session, kernel_poll_pipe[1]);
3833
3834 /* Set session to NULL so we do not unlock it after free. */
3835 cmd_ctx->session = NULL;
3836 break;
3837 }
3838 case LTTNG_LIST_DOMAINS:
3839 {
3840 ssize_t nb_dom;
3841 struct lttng_domain *domains = NULL;
3842
3843 nb_dom = cmd_list_domains(cmd_ctx->session, &domains);
3844 if (nb_dom < 0) {
3845 /* Return value is a negative lttng_error_code. */
3846 ret = -nb_dom;
3847 goto error;
3848 }
3849
3850 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, domains,
3851 nb_dom * sizeof(struct lttng_domain));
3852 free(domains);
3853
3854 if (ret < 0) {
3855 goto setup_error;
3856 }
3857
3858 ret = LTTNG_OK;
3859 break;
3860 }
3861 case LTTNG_LIST_CHANNELS:
3862 {
3863 ssize_t payload_size;
3864 struct lttng_channel *channels = NULL;
3865
3866 payload_size = cmd_list_channels(cmd_ctx->lsm->domain.type,
3867 cmd_ctx->session, &channels);
3868 if (payload_size < 0) {
3869 /* Return value is a negative lttng_error_code. */
3870 ret = -payload_size;
3871 goto error;
3872 }
3873
3874 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, channels,
3875 payload_size);
3876 free(channels);
3877
3878 if (ret < 0) {
3879 goto setup_error;
3880 }
3881
3882 ret = LTTNG_OK;
3883 break;
3884 }
3885 case LTTNG_LIST_EVENTS:
3886 {
3887 ssize_t nb_event;
3888 struct lttng_event *events = NULL;
3889 struct lttcomm_event_command_header cmd_header;
3890 size_t total_size;
3891
3892 memset(&cmd_header, 0, sizeof(cmd_header));
3893 /* Extended infos are included at the end of events */
3894 nb_event = cmd_list_events(cmd_ctx->lsm->domain.type,
3895 cmd_ctx->session, cmd_ctx->lsm->u.list.channel_name,
3896 &events, &total_size);
3897
3898 if (nb_event < 0) {
3899 /* Return value is a negative lttng_error_code. */
3900 ret = -nb_event;
3901 goto error;
3902 }
3903
3904 cmd_header.nb_events = nb_event;
3905 ret = setup_lttng_msg(cmd_ctx, events, total_size,
3906 &cmd_header, sizeof(cmd_header));
3907 free(events);
3908
3909 if (ret < 0) {
3910 goto setup_error;
3911 }
3912
3913 ret = LTTNG_OK;
3914 break;
3915 }
3916 case LTTNG_LIST_SESSIONS:
3917 {
3918 unsigned int nr_sessions;
3919 void *sessions_payload;
3920 size_t payload_len;
3921
3922 session_lock_list();
3923 nr_sessions = lttng_sessions_count(
3924 LTTNG_SOCK_GET_UID_CRED(&cmd_ctx->creds),
3925 LTTNG_SOCK_GET_GID_CRED(&cmd_ctx->creds));
3926 payload_len = sizeof(struct lttng_session) * nr_sessions;
3927 sessions_payload = zmalloc(payload_len);
3928
3929 if (!sessions_payload) {
3930 session_unlock_list();
3931 ret = -ENOMEM;
3932 goto setup_error;
3933 }
3934
3935 cmd_list_lttng_sessions(sessions_payload,
3936 LTTNG_SOCK_GET_UID_CRED(&cmd_ctx->creds),
3937 LTTNG_SOCK_GET_GID_CRED(&cmd_ctx->creds));
3938 session_unlock_list();
3939
3940 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, sessions_payload,
3941 payload_len);
3942 free(sessions_payload);
3943
3944 if (ret < 0) {
3945 goto setup_error;
3946 }
3947
3948 ret = LTTNG_OK;
3949 break;
3950 }
3951 case LTTNG_CALIBRATE:
3952 {
3953 ret = cmd_calibrate(cmd_ctx->lsm->domain.type,
3954 &cmd_ctx->lsm->u.calibrate);
3955 break;
3956 }
3957 case LTTNG_REGISTER_CONSUMER:
3958 {
3959 struct consumer_data *cdata;
3960
3961 switch (cmd_ctx->lsm->domain.type) {
3962 case LTTNG_DOMAIN_KERNEL:
3963 cdata = &kconsumer_data;
3964 break;
3965 default:
3966 ret = LTTNG_ERR_UND;
3967 goto error;
3968 }
3969
3970 ret = cmd_register_consumer(cmd_ctx->session, cmd_ctx->lsm->domain.type,
3971 cmd_ctx->lsm->u.reg.path, cdata);
3972 break;
3973 }
3974 case LTTNG_DATA_PENDING:
3975 {
3976 int pending_ret;
3977 uint8_t pending_ret_byte;
3978
3979 pending_ret = cmd_data_pending(cmd_ctx->session);
3980
3981 /*
3982 * FIXME
3983 *
3984 * This function may returns 0 or 1 to indicate whether or not
3985 * there is data pending. In case of error, it should return an
3986 * LTTNG_ERR code. However, some code paths may still return
3987 * a nondescript error code, which we handle by returning an
3988 * "unknown" error.
3989 */
3990 if (pending_ret == 0 || pending_ret == 1) {
3991 /*
3992 * ret will be set to LTTNG_OK at the end of
3993 * this function.
3994 */
3995 } else if (pending_ret < 0) {
3996 ret = LTTNG_ERR_UNK;
3997 goto setup_error;
3998 } else {
3999 ret = pending_ret;
4000 goto setup_error;
4001 }
4002
4003 pending_ret_byte = (uint8_t) pending_ret;
4004
4005 /* 1 byte to return whether or not data is pending */
4006 ret = setup_lttng_msg_no_cmd_header(cmd_ctx,
4007 &pending_ret_byte, 1);
4008
4009 if (ret < 0) {
4010 goto setup_error;
4011 }
4012
4013 ret = LTTNG_OK;
4014 break;
4015 }
4016 case LTTNG_SNAPSHOT_ADD_OUTPUT:
4017 {
4018 struct lttcomm_lttng_output_id reply;
4019
4020 ret = cmd_snapshot_add_output(cmd_ctx->session,
4021 &cmd_ctx->lsm->u.snapshot_output.output, &reply.id);
4022 if (ret != LTTNG_OK) {
4023 goto error;
4024 }
4025
4026 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, &reply,
4027 sizeof(reply));
4028 if (ret < 0) {
4029 goto setup_error;
4030 }
4031
4032 /* Copy output list into message payload */
4033 ret = LTTNG_OK;
4034 break;
4035 }
4036 case LTTNG_SNAPSHOT_DEL_OUTPUT:
4037 {
4038 ret = cmd_snapshot_del_output(cmd_ctx->session,
4039 &cmd_ctx->lsm->u.snapshot_output.output);
4040 break;
4041 }
4042 case LTTNG_SNAPSHOT_LIST_OUTPUT:
4043 {
4044 ssize_t nb_output;
4045 struct lttng_snapshot_output *outputs = NULL;
4046
4047 nb_output = cmd_snapshot_list_outputs(cmd_ctx->session, &outputs);
4048 if (nb_output < 0) {
4049 ret = -nb_output;
4050 goto error;
4051 }
4052
4053 assert((nb_output > 0 && outputs) || nb_output == 0);
4054 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, outputs,
4055 nb_output * sizeof(struct lttng_snapshot_output));
4056 free(outputs);
4057
4058 if (ret < 0) {
4059 goto setup_error;
4060 }
4061
4062 ret = LTTNG_OK;
4063 break;
4064 }
4065 case LTTNG_SNAPSHOT_RECORD:
4066 {
4067 ret = cmd_snapshot_record(cmd_ctx->session,
4068 &cmd_ctx->lsm->u.snapshot_record.output,
4069 cmd_ctx->lsm->u.snapshot_record.wait);
4070 break;
4071 }
4072 case LTTNG_CREATE_SESSION_SNAPSHOT:
4073 {
4074 size_t nb_uri, len;
4075 struct lttng_uri *uris = NULL;
4076
4077 nb_uri = cmd_ctx->lsm->u.uri.size;
4078 len = nb_uri * sizeof(struct lttng_uri);
4079
4080 if (nb_uri > 0) {
4081 uris = zmalloc(len);
4082 if (uris == NULL) {
4083 ret = LTTNG_ERR_FATAL;
4084 goto error;
4085 }
4086
4087 /* Receive variable len data */
4088 DBG("Waiting for %zu URIs from client ...", nb_uri);
4089 ret = lttcomm_recv_unix_sock(sock, uris, len);
4090 if (ret <= 0) {
4091 DBG("No URIs received from client... continuing");
4092 *sock_error = 1;
4093 ret = LTTNG_ERR_SESSION_FAIL;
4094 free(uris);
4095 goto error;
4096 }
4097
4098 if (nb_uri == 1 && uris[0].dtype != LTTNG_DST_PATH) {
4099 DBG("Creating session with ONE network URI is a bad call");
4100 ret = LTTNG_ERR_SESSION_FAIL;
4101 free(uris);
4102 goto error;
4103 }
4104 }
4105
4106 ret = cmd_create_session_snapshot(cmd_ctx->lsm->session.name, uris,
4107 nb_uri, &cmd_ctx->creds);
4108 free(uris);
4109 break;
4110 }
4111 case LTTNG_CREATE_SESSION_LIVE:
4112 {
4113 size_t nb_uri, len;
4114 struct lttng_uri *uris = NULL;
4115
4116 nb_uri = cmd_ctx->lsm->u.uri.size;
4117 len = nb_uri * sizeof(struct lttng_uri);
4118
4119 if (nb_uri > 0) {
4120 uris = zmalloc(len);
4121 if (uris == NULL) {
4122 ret = LTTNG_ERR_FATAL;
4123 goto error;
4124 }
4125
4126 /* Receive variable len data */
4127 DBG("Waiting for %zu URIs from client ...", nb_uri);
4128 ret = lttcomm_recv_unix_sock(sock, uris, len);
4129 if (ret <= 0) {
4130 DBG("No URIs received from client... continuing");
4131 *sock_error = 1;
4132 ret = LTTNG_ERR_SESSION_FAIL;
4133 free(uris);
4134 goto error;
4135 }
4136
4137 if (nb_uri == 1 && uris[0].dtype != LTTNG_DST_PATH) {
4138 DBG("Creating session with ONE network URI is a bad call");
4139 ret = LTTNG_ERR_SESSION_FAIL;
4140 free(uris);
4141 goto error;
4142 }
4143 }
4144
4145 ret = cmd_create_session_uri(cmd_ctx->lsm->session.name, uris,
4146 nb_uri, &cmd_ctx->creds, cmd_ctx->lsm->u.session_live.timer_interval);
4147 free(uris);
4148 break;
4149 }
4150 case LTTNG_SAVE_SESSION:
4151 {
4152 ret = cmd_save_sessions(&cmd_ctx->lsm->u.save_session.attr,
4153 &cmd_ctx->creds);
4154 break;
4155 }
4156 case LTTNG_SET_SESSION_SHM_PATH:
4157 {
4158 ret = cmd_set_session_shm_path(cmd_ctx->session,
4159 cmd_ctx->lsm->u.set_shm_path.shm_path);
4160 break;
4161 }
4162 case LTTNG_METADATA_REGENERATE:
4163 {
4164 ret = cmd_metadata_regenerate(cmd_ctx->session);
4165 break;
4166 }
4167 default:
4168 ret = LTTNG_ERR_UND;
4169 break;
4170 }
4171
4172 error:
4173 if (cmd_ctx->llm == NULL) {
4174 DBG("Missing llm structure. Allocating one.");
4175 if (setup_lttng_msg_no_cmd_header(cmd_ctx, NULL, 0) < 0) {
4176 goto setup_error;
4177 }
4178 }
4179 /* Set return code */
4180 cmd_ctx->llm->ret_code = ret;
4181 setup_error:
4182 if (cmd_ctx->session) {
4183 session_unlock(cmd_ctx->session);
4184 }
4185 if (need_tracing_session) {
4186 session_unlock_list();
4187 }
4188 init_setup_error:
4189 assert(!rcu_read_ongoing());
4190 return ret;
4191 }
4192
4193 /*
4194 * Thread managing health check socket.
4195 */
4196 static void *thread_manage_health(void *data)
4197 {
4198 int sock = -1, new_sock = -1, ret, i, pollfd, err = -1;
4199 uint32_t revents, nb_fd;
4200 struct lttng_poll_event events;
4201 struct health_comm_msg msg;
4202 struct health_comm_reply reply;
4203
4204 DBG("[thread] Manage health check started");
4205
4206 rcu_register_thread();
4207
4208 /* We might hit an error path before this is created. */
4209 lttng_poll_init(&events);
4210
4211 /* Create unix socket */
4212 sock = lttcomm_create_unix_sock(health_unix_sock_path);
4213 if (sock < 0) {
4214 ERR("Unable to create health check Unix socket");
4215 ret = -1;
4216 goto error;
4217 }
4218
4219 if (is_root) {
4220 /* lttng health client socket path permissions */
4221 ret = chown(health_unix_sock_path, 0,
4222 utils_get_group_id(tracing_group_name));
4223 if (ret < 0) {
4224 ERR("Unable to set group on %s", health_unix_sock_path);
4225 PERROR("chown");
4226 ret = -1;
4227 goto error;
4228 }
4229
4230 ret = chmod(health_unix_sock_path,
4231 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
4232 if (ret < 0) {
4233 ERR("Unable to set permissions on %s", health_unix_sock_path);
4234 PERROR("chmod");
4235 ret = -1;
4236 goto error;
4237 }
4238 }
4239
4240 /*
4241 * Set the CLOEXEC flag. Return code is useless because either way, the
4242 * show must go on.
4243 */
4244 (void) utils_set_fd_cloexec(sock);
4245
4246 ret = lttcomm_listen_unix_sock(sock);
4247 if (ret < 0) {
4248 goto error;
4249 }
4250
4251 /*
4252 * Pass 2 as size here for the thread quit pipe and client_sock. Nothing
4253 * more will be added to this poll set.
4254 */
4255 ret = sessiond_set_thread_pollset(&events, 2);
4256 if (ret < 0) {
4257 goto error;
4258 }
4259
4260 /* Add the application registration socket */
4261 ret = lttng_poll_add(&events, sock, LPOLLIN | LPOLLPRI);
4262 if (ret < 0) {
4263 goto error;
4264 }
4265
4266 sessiond_notify_ready();
4267
4268 while (1) {
4269 DBG("Health check ready");
4270
4271 /* Inifinite blocking call, waiting for transmission */
4272 restart:
4273 ret = lttng_poll_wait(&events, -1);
4274 if (ret < 0) {
4275 /*
4276 * Restart interrupted system call.
4277 */
4278 if (errno == EINTR) {
4279 goto restart;
4280 }
4281 goto error;
4282 }
4283
4284 nb_fd = ret;
4285
4286 for (i = 0; i < nb_fd; i++) {
4287 /* Fetch once the poll data */
4288 revents = LTTNG_POLL_GETEV(&events, i);
4289 pollfd = LTTNG_POLL_GETFD(&events, i);
4290
4291 if (!revents) {
4292 /* No activity for this FD (poll implementation). */
4293 continue;
4294 }
4295
4296 /* Thread quit pipe has been closed. Killing thread. */
4297 ret = sessiond_check_thread_quit_pipe(pollfd, revents);
4298 if (ret) {
4299 err = 0;
4300 goto exit;
4301 }
4302
4303 /* Event on the registration socket */
4304 if (pollfd == sock) {
4305 if (revents & LPOLLIN) {
4306 continue;
4307 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
4308 ERR("Health socket poll error");
4309 goto error;
4310 } else {
4311 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
4312 goto error;
4313 }
4314 }
4315 }
4316
4317 new_sock = lttcomm_accept_unix_sock(sock);
4318 if (new_sock < 0) {
4319 goto error;
4320 }
4321
4322 /*
4323 * Set the CLOEXEC flag. Return code is useless because either way, the
4324 * show must go on.
4325 */
4326 (void) utils_set_fd_cloexec(new_sock);
4327
4328 DBG("Receiving data from client for health...");
4329 ret = lttcomm_recv_unix_sock(new_sock, (void *)&msg, sizeof(msg));
4330 if (ret <= 0) {
4331 DBG("Nothing recv() from client... continuing");
4332 ret = close(new_sock);
4333 if (ret) {
4334 PERROR("close");
4335 }
4336 new_sock = -1;
4337 continue;
4338 }
4339
4340 rcu_thread_online();
4341
4342 memset(&reply, 0, sizeof(reply));
4343 for (i = 0; i < NR_HEALTH_SESSIOND_TYPES; i++) {
4344 /*
4345 * health_check_state returns 0 if health is
4346 * bad.
4347 */
4348 if (!health_check_state(health_sessiond, i)) {
4349 reply.ret_code |= 1ULL << i;
4350 }
4351 }
4352
4353 DBG2("Health check return value %" PRIx64, reply.ret_code);
4354
4355 ret = send_unix_sock(new_sock, (void *) &reply, sizeof(reply));
4356 if (ret < 0) {
4357 ERR("Failed to send health data back to client");
4358 }
4359
4360 /* End of transmission */
4361 ret = close(new_sock);
4362 if (ret) {
4363 PERROR("close");
4364 }
4365 new_sock = -1;
4366 }
4367
4368 exit:
4369 error:
4370 if (err) {
4371 ERR("Health error occurred in %s", __func__);
4372 }
4373 DBG("Health check thread dying");
4374 unlink(health_unix_sock_path);
4375 if (sock >= 0) {
4376 ret = close(sock);
4377 if (ret) {
4378 PERROR("close");
4379 }
4380 }
4381
4382 lttng_poll_clean(&events);
4383 stop_threads();
4384 rcu_unregister_thread();
4385 return NULL;
4386 }
4387
4388 /*
4389 * This thread manage all clients request using the unix client socket for
4390 * communication.
4391 */
4392 static void *thread_manage_clients(void *data)
4393 {
4394 int sock = -1, ret, i, pollfd, err = -1;
4395 int sock_error;
4396 uint32_t revents, nb_fd;
4397 struct command_ctx *cmd_ctx = NULL;
4398 struct lttng_poll_event events;
4399
4400 DBG("[thread] Manage client started");
4401
4402 rcu_register_thread();
4403
4404 health_register(health_sessiond, HEALTH_SESSIOND_TYPE_CMD);
4405
4406 health_code_update();
4407
4408 ret = lttcomm_listen_unix_sock(client_sock);
4409 if (ret < 0) {
4410 goto error_listen;
4411 }
4412
4413 /*
4414 * Pass 2 as size here for the thread quit pipe and client_sock. Nothing
4415 * more will be added to this poll set.
4416 */
4417 ret = sessiond_set_thread_pollset(&events, 2);
4418 if (ret < 0) {
4419 goto error_create_poll;
4420 }
4421
4422 /* Add the application registration socket */
4423 ret = lttng_poll_add(&events, client_sock, LPOLLIN | LPOLLPRI);
4424 if (ret < 0) {
4425 goto error;
4426 }
4427
4428 sessiond_notify_ready();
4429 ret = sem_post(&load_info->message_thread_ready);
4430 if (ret) {
4431 PERROR("sem_post message_thread_ready");
4432 goto error;
4433 }
4434
4435 /* This testpoint is after we signal readiness to the parent. */
4436 if (testpoint(sessiond_thread_manage_clients)) {
4437 goto error;
4438 }
4439
4440 if (testpoint(sessiond_thread_manage_clients_before_loop)) {
4441 goto error;
4442 }
4443
4444 health_code_update();
4445
4446 while (1) {
4447 DBG("Accepting client command ...");
4448
4449 /* Inifinite blocking call, waiting for transmission */
4450 restart:
4451 health_poll_entry();
4452 ret = lttng_poll_wait(&events, -1);
4453 health_poll_exit();
4454 if (ret < 0) {
4455 /*
4456 * Restart interrupted system call.
4457 */
4458 if (errno == EINTR) {
4459 goto restart;
4460 }
4461 goto error;
4462 }
4463
4464 nb_fd = ret;
4465
4466 for (i = 0; i < nb_fd; i++) {
4467 /* Fetch once the poll data */
4468 revents = LTTNG_POLL_GETEV(&events, i);
4469 pollfd = LTTNG_POLL_GETFD(&events, i);
4470
4471 health_code_update();
4472
4473 if (!revents) {
4474 /* No activity for this FD (poll implementation). */
4475 continue;
4476 }
4477
4478 /* Thread quit pipe has been closed. Killing thread. */
4479 ret = sessiond_check_thread_quit_pipe(pollfd, revents);
4480 if (ret) {
4481 err = 0;
4482 goto exit;
4483 }
4484
4485 /* Event on the registration socket */
4486 if (pollfd == client_sock) {
4487 if (revents & LPOLLIN) {
4488 continue;
4489 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
4490 ERR("Client socket poll error");
4491 goto error;
4492 } else {
4493 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
4494 goto error;
4495 }
4496 }
4497 }
4498
4499 DBG("Wait for client response");
4500
4501 health_code_update();
4502
4503 sock = lttcomm_accept_unix_sock(client_sock);
4504 if (sock < 0) {
4505 goto error;
4506 }
4507
4508 /*
4509 * Set the CLOEXEC flag. Return code is useless because either way, the
4510 * show must go on.
4511 */
4512 (void) utils_set_fd_cloexec(sock);
4513
4514 /* Set socket option for credentials retrieval */
4515 ret = lttcomm_setsockopt_creds_unix_sock(sock);
4516 if (ret < 0) {
4517 goto error;
4518 }
4519
4520 /* Allocate context command to process the client request */
4521 cmd_ctx = zmalloc(sizeof(struct command_ctx));
4522 if (cmd_ctx == NULL) {
4523 PERROR("zmalloc cmd_ctx");
4524 goto error;
4525 }
4526
4527 /* Allocate data buffer for reception */
4528 cmd_ctx->lsm = zmalloc(sizeof(struct lttcomm_session_msg));
4529 if (cmd_ctx->lsm == NULL) {
4530 PERROR("zmalloc cmd_ctx->lsm");
4531 goto error;
4532 }
4533
4534 cmd_ctx->llm = NULL;
4535 cmd_ctx->session = NULL;
4536
4537 health_code_update();
4538
4539 /*
4540 * Data is received from the lttng client. The struct
4541 * lttcomm_session_msg (lsm) contains the command and data request of
4542 * the client.
4543 */
4544 DBG("Receiving data from client ...");
4545 ret = lttcomm_recv_creds_unix_sock(sock, cmd_ctx->lsm,
4546 sizeof(struct lttcomm_session_msg), &cmd_ctx->creds);
4547 if (ret <= 0) {
4548 DBG("Nothing recv() from client... continuing");
4549 ret = close(sock);
4550 if (ret) {
4551 PERROR("close");
4552 }
4553 sock = -1;
4554 clean_command_ctx(&cmd_ctx);
4555 continue;
4556 }
4557
4558 health_code_update();
4559
4560 // TODO: Validate cmd_ctx including sanity check for
4561 // security purpose.
4562
4563 rcu_thread_online();
4564 /*
4565 * This function dispatch the work to the kernel or userspace tracer
4566 * libs and fill the lttcomm_lttng_msg data structure of all the needed
4567 * informations for the client. The command context struct contains
4568 * everything this function may needs.
4569 */
4570 ret = process_client_msg(cmd_ctx, sock, &sock_error);
4571 rcu_thread_offline();
4572 if (ret < 0) {
4573 ret = close(sock);
4574 if (ret) {
4575 PERROR("close");
4576 }
4577 sock = -1;
4578 /*
4579 * TODO: Inform client somehow of the fatal error. At
4580 * this point, ret < 0 means that a zmalloc failed
4581 * (ENOMEM). Error detected but still accept
4582 * command, unless a socket error has been
4583 * detected.
4584 */
4585 clean_command_ctx(&cmd_ctx);
4586 continue;
4587 }
4588
4589 health_code_update();
4590
4591 DBG("Sending response (size: %d, retcode: %s (%d))",
4592 cmd_ctx->lttng_msg_size,
4593 lttng_strerror(-cmd_ctx->llm->ret_code),
4594 cmd_ctx->llm->ret_code);
4595 ret = send_unix_sock(sock, cmd_ctx->llm, cmd_ctx->lttng_msg_size);
4596 if (ret < 0) {
4597 ERR("Failed to send data back to client");
4598 }
4599
4600 /* End of transmission */
4601 ret = close(sock);
4602 if (ret) {
4603 PERROR("close");
4604 }
4605 sock = -1;
4606
4607 clean_command_ctx(&cmd_ctx);
4608
4609 health_code_update();
4610 }
4611
4612 exit:
4613 error:
4614 if (sock >= 0) {
4615 ret = close(sock);
4616 if (ret) {
4617 PERROR("close");
4618 }
4619 }
4620
4621 lttng_poll_clean(&events);
4622 clean_command_ctx(&cmd_ctx);
4623
4624 error_listen:
4625 error_create_poll:
4626 unlink(client_unix_sock_path);
4627 if (client_sock >= 0) {
4628 ret = close(client_sock);
4629 if (ret) {
4630 PERROR("close");
4631 }
4632 }
4633
4634 if (err) {
4635 health_error();
4636 ERR("Health error occurred in %s", __func__);
4637 }
4638
4639 health_unregister(health_sessiond);
4640
4641 DBG("Client thread dying");
4642
4643 rcu_unregister_thread();
4644
4645 /*
4646 * Since we are creating the consumer threads, we own them, so we need
4647 * to join them before our thread exits.
4648 */
4649 ret = join_consumer_thread(&kconsumer_data);
4650 if (ret) {
4651 errno = ret;
4652 PERROR("join_consumer");
4653 }
4654
4655 ret = join_consumer_thread(&ustconsumer32_data);
4656 if (ret) {
4657 errno = ret;
4658 PERROR("join_consumer ust32");
4659 }
4660
4661 ret = join_consumer_thread(&ustconsumer64_data);
4662 if (ret) {
4663 errno = ret;
4664 PERROR("join_consumer ust64");
4665 }
4666 return NULL;
4667 }
4668
4669 static int string_match(const char *str1, const char *str2)
4670 {
4671 return (str1 && str2) && !strcmp(str1, str2);
4672 }
4673
4674 /*
4675 * Take an option from the getopt output and set it in the right variable to be
4676 * used later.
4677 *
4678 * Return 0 on success else a negative value.
4679 */
4680 static int set_option(int opt, const char *arg, const char *optname)
4681 {
4682 int ret = 0;
4683
4684 if (string_match(optname, "client-sock") || opt == 'c') {
4685 if (!arg || *arg == '\0') {
4686 ret = -EINVAL;
4687 goto end;
4688 }
4689 if (lttng_is_setuid_setgid()) {
4690 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4691 "-c, --client-sock");
4692 } else {
4693 snprintf(client_unix_sock_path, PATH_MAX, "%s", arg);
4694 }
4695 } else if (string_match(optname, "apps-sock") || opt == 'a') {
4696 if (!arg || *arg == '\0') {
4697 ret = -EINVAL;
4698 goto end;
4699 }
4700 if (lttng_is_setuid_setgid()) {
4701 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4702 "-a, --apps-sock");
4703 } else {
4704 snprintf(apps_unix_sock_path, PATH_MAX, "%s", arg);
4705 }
4706 } else if (string_match(optname, "daemonize") || opt == 'd') {
4707 opt_daemon = 1;
4708 } else if (string_match(optname, "background") || opt == 'b') {
4709 opt_background = 1;
4710 } else if (string_match(optname, "group") || opt == 'g') {
4711 if (!arg || *arg == '\0') {
4712 ret = -EINVAL;
4713 goto end;
4714 }
4715 if (lttng_is_setuid_setgid()) {
4716 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4717 "-g, --group");
4718 } else {
4719 /*
4720 * If the override option is set, the pointer points to a
4721 * *non* const thus freeing it even though the variable type is
4722 * set to const.
4723 */
4724 if (tracing_group_name_override) {
4725 free((void *) tracing_group_name);
4726 }
4727 tracing_group_name = strdup(arg);
4728 if (!tracing_group_name) {
4729 PERROR("strdup");
4730 ret = -ENOMEM;
4731 }
4732 tracing_group_name_override = 1;
4733 }
4734 } else if (string_match(optname, "help") || opt == 'h') {
4735 ret = utils_show_man_page(8, "lttng-sessiond");
4736 if (ret) {
4737 ERR("Cannot view man page lttng-sessiond(8)");
4738 perror("exec");
4739 }
4740 exit(ret ? EXIT_FAILURE : EXIT_SUCCESS);
4741 } else if (string_match(optname, "version") || opt == 'V') {
4742 fprintf(stdout, "%s\n", VERSION);
4743 exit(EXIT_SUCCESS);
4744 } else if (string_match(optname, "sig-parent") || opt == 'S') {
4745 opt_sig_parent = 1;
4746 } else if (string_match(optname, "kconsumerd-err-sock")) {
4747 if (!arg || *arg == '\0') {
4748 ret = -EINVAL;
4749 goto end;
4750 }
4751 if (lttng_is_setuid_setgid()) {
4752 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4753 "--kconsumerd-err-sock");
4754 } else {
4755 snprintf(kconsumer_data.err_unix_sock_path, PATH_MAX, "%s", arg);
4756 }
4757 } else if (string_match(optname, "kconsumerd-cmd-sock")) {
4758 if (!arg || *arg == '\0') {
4759 ret = -EINVAL;
4760 goto end;
4761 }
4762 if (lttng_is_setuid_setgid()) {
4763 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4764 "--kconsumerd-cmd-sock");
4765 } else {
4766 snprintf(kconsumer_data.cmd_unix_sock_path, PATH_MAX, "%s", arg);
4767 }
4768 } else if (string_match(optname, "ustconsumerd64-err-sock")) {
4769 if (!arg || *arg == '\0') {
4770 ret = -EINVAL;
4771 goto end;
4772 }
4773 if (lttng_is_setuid_setgid()) {
4774 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4775 "--ustconsumerd64-err-sock");
4776 } else {
4777 snprintf(ustconsumer64_data.err_unix_sock_path, PATH_MAX, "%s", arg);
4778 }
4779 } else if (string_match(optname, "ustconsumerd64-cmd-sock")) {
4780 if (!arg || *arg == '\0') {
4781 ret = -EINVAL;
4782 goto end;
4783 }
4784 if (lttng_is_setuid_setgid()) {
4785 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4786 "--ustconsumerd64-cmd-sock");
4787 } else {
4788 snprintf(ustconsumer64_data.cmd_unix_sock_path, PATH_MAX, "%s", arg);
4789 }
4790 } else if (string_match(optname, "ustconsumerd32-err-sock")) {
4791 if (!arg || *arg == '\0') {
4792 ret = -EINVAL;
4793 goto end;
4794 }
4795 if (lttng_is_setuid_setgid()) {
4796 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4797 "--ustconsumerd32-err-sock");
4798 } else {
4799 snprintf(ustconsumer32_data.err_unix_sock_path, PATH_MAX, "%s", arg);
4800 }
4801 } else if (string_match(optname, "ustconsumerd32-cmd-sock")) {
4802 if (!arg || *arg == '\0') {
4803 ret = -EINVAL;
4804 goto end;
4805 }
4806 if (lttng_is_setuid_setgid()) {
4807 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4808 "--ustconsumerd32-cmd-sock");
4809 } else {
4810 snprintf(ustconsumer32_data.cmd_unix_sock_path, PATH_MAX, "%s", arg);
4811 }
4812 } else if (string_match(optname, "no-kernel")) {
4813 opt_no_kernel = 1;
4814 } else if (string_match(optname, "quiet") || opt == 'q') {
4815 lttng_opt_quiet = 1;
4816 } else if (string_match(optname, "verbose") || opt == 'v') {
4817 /* Verbose level can increase using multiple -v */
4818 if (arg) {
4819 /* Value obtained from config file */
4820 lttng_opt_verbose = config_parse_value(arg);
4821 } else {
4822 /* -v used on command line */
4823 lttng_opt_verbose++;
4824 }
4825 /* Clamp value to [0, 3] */
4826 lttng_opt_verbose = lttng_opt_verbose < 0 ? 0 :
4827 (lttng_opt_verbose <= 3 ? lttng_opt_verbose : 3);
4828 } else if (string_match(optname, "verbose-consumer")) {
4829 if (arg) {
4830 opt_verbose_consumer = config_parse_value(arg);
4831 } else {
4832 opt_verbose_consumer++;
4833 }
4834 } else if (string_match(optname, "consumerd32-path")) {
4835 if (!arg || *arg == '\0') {
4836 ret = -EINVAL;
4837 goto end;
4838 }
4839 if (lttng_is_setuid_setgid()) {
4840 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4841 "--consumerd32-path");
4842 } else {
4843 if (consumerd32_bin_override) {
4844 free((void *) consumerd32_bin);
4845 }
4846 consumerd32_bin = strdup(arg);
4847 if (!consumerd32_bin) {
4848 PERROR("strdup");
4849 ret = -ENOMEM;
4850 }
4851 consumerd32_bin_override = 1;
4852 }
4853 } else if (string_match(optname, "consumerd32-libdir")) {
4854 if (!arg || *arg == '\0') {
4855 ret = -EINVAL;
4856 goto end;
4857 }
4858 if (lttng_is_setuid_setgid()) {
4859 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4860 "--consumerd32-libdir");
4861 } else {
4862 if (consumerd32_libdir_override) {
4863 free((void *) consumerd32_libdir);
4864 }
4865 consumerd32_libdir = strdup(arg);
4866 if (!consumerd32_libdir) {
4867 PERROR("strdup");
4868 ret = -ENOMEM;
4869 }
4870 consumerd32_libdir_override = 1;
4871 }
4872 } else if (string_match(optname, "consumerd64-path")) {
4873 if (!arg || *arg == '\0') {
4874 ret = -EINVAL;
4875 goto end;
4876 }
4877 if (lttng_is_setuid_setgid()) {
4878 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4879 "--consumerd64-path");
4880 } else {
4881 if (consumerd64_bin_override) {
4882 free((void *) consumerd64_bin);
4883 }
4884 consumerd64_bin = strdup(arg);
4885 if (!consumerd64_bin) {
4886 PERROR("strdup");
4887 ret = -ENOMEM;
4888 }
4889 consumerd64_bin_override = 1;
4890 }
4891 } else if (string_match(optname, "consumerd64-libdir")) {
4892 if (!arg || *arg == '\0') {
4893 ret = -EINVAL;
4894 goto end;
4895 }
4896 if (lttng_is_setuid_setgid()) {
4897 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4898 "--consumerd64-libdir");
4899 } else {
4900 if (consumerd64_libdir_override) {
4901 free((void *) consumerd64_libdir);
4902 }
4903 consumerd64_libdir = strdup(arg);
4904 if (!consumerd64_libdir) {
4905 PERROR("strdup");
4906 ret = -ENOMEM;
4907 }
4908 consumerd64_libdir_override = 1;
4909 }
4910 } else if (string_match(optname, "pidfile") || opt == 'p') {
4911 if (!arg || *arg == '\0') {
4912 ret = -EINVAL;
4913 goto end;
4914 }
4915 if (lttng_is_setuid_setgid()) {
4916 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4917 "-p, --pidfile");
4918 } else {
4919 free(opt_pidfile);
4920 opt_pidfile = strdup(arg);
4921 if (!opt_pidfile) {
4922 PERROR("strdup");
4923 ret = -ENOMEM;
4924 }
4925 }
4926 } else if (string_match(optname, "agent-tcp-port")) {
4927 if (!arg || *arg == '\0') {
4928 ret = -EINVAL;
4929 goto end;
4930 }
4931 if (lttng_is_setuid_setgid()) {
4932 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4933 "--agent-tcp-port");
4934 } else {
4935 unsigned long v;
4936
4937 if (!arg) {
4938 ret = -EINVAL;
4939 goto end;
4940 }
4941 errno = 0;
4942 v = strtoul(arg, NULL, 0);
4943 if (errno != 0 || !isdigit(arg[0])) {
4944 ERR("Wrong value in --agent-tcp-port parameter: %s", arg);
4945 return -1;
4946 }
4947 if (v == 0 || v >= 65535) {
4948 ERR("Port overflow in --agent-tcp-port parameter: %s", arg);
4949 return -1;
4950 }
4951 agent_tcp_port = (uint32_t) v;
4952 DBG3("Agent TCP port set to non default: %u", agent_tcp_port);
4953 }
4954 } else if (string_match(optname, "load") || opt == 'l') {
4955 if (!arg || *arg == '\0') {
4956 ret = -EINVAL;
4957 goto end;
4958 }
4959 if (lttng_is_setuid_setgid()) {
4960 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4961 "-l, --load");
4962 } else {
4963 free(opt_load_session_path);
4964 opt_load_session_path = strdup(arg);
4965 if (!opt_load_session_path) {
4966 PERROR("strdup");
4967 ret = -ENOMEM;
4968 }
4969 }
4970 } else if (string_match(optname, "kmod-probes")) {
4971 if (!arg || *arg == '\0') {
4972 ret = -EINVAL;
4973 goto end;
4974 }
4975 if (lttng_is_setuid_setgid()) {
4976 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4977 "--kmod-probes");
4978 } else {
4979 free(kmod_probes_list);
4980 kmod_probes_list = strdup(arg);
4981 if (!kmod_probes_list) {
4982 PERROR("strdup");
4983 ret = -ENOMEM;
4984 }
4985 }
4986 } else if (string_match(optname, "extra-kmod-probes")) {
4987 if (!arg || *arg == '\0') {
4988 ret = -EINVAL;
4989 goto end;
4990 }
4991 if (lttng_is_setuid_setgid()) {
4992 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4993 "--extra-kmod-probes");
4994 } else {
4995 free(kmod_extra_probes_list);
4996 kmod_extra_probes_list = strdup(arg);
4997 if (!kmod_extra_probes_list) {
4998 PERROR("strdup");
4999 ret = -ENOMEM;
5000 }
5001 }
5002 } else if (string_match(optname, "config") || opt == 'f') {
5003 /* This is handled in set_options() thus silent skip. */
5004 goto end;
5005 } else {
5006 /* Unknown option or other error.
5007 * Error is printed by getopt, just return */
5008 ret = -1;
5009 }
5010
5011 end:
5012 if (ret == -EINVAL) {
5013 const char *opt_name = "unknown";
5014 int i;
5015
5016 for (i = 0; i < sizeof(long_options) / sizeof(struct option);
5017 i++) {
5018 if (opt == long_options[i].val) {
5019 opt_name = long_options[i].name;
5020 break;
5021 }
5022 }
5023
5024 WARN("Invalid argument provided for option \"%s\", using default value.",
5025 opt_name);
5026 }
5027
5028 return ret;
5029 }
5030
5031 /*
5032 * config_entry_handler_cb used to handle options read from a config file.
5033 * See config_entry_handler_cb comment in common/config/session-config.h for the
5034 * return value conventions.
5035 */
5036 static int config_entry_handler(const struct config_entry *entry, void *unused)
5037 {
5038 int ret = 0, i;
5039
5040 if (!entry || !entry->name || !entry->value) {
5041 ret = -EINVAL;
5042 goto end;
5043 }
5044
5045 /* Check if the option is to be ignored */
5046 for (i = 0; i < sizeof(config_ignore_options) / sizeof(char *); i++) {
5047 if (!strcmp(entry->name, config_ignore_options[i])) {
5048 goto end;
5049 }
5050 }
5051
5052 for (i = 0; i < (sizeof(long_options) / sizeof(struct option)) - 1;
5053 i++) {
5054
5055 /* Ignore if not fully matched. */
5056 if (strcmp(entry->name, long_options[i].name)) {
5057 continue;
5058 }
5059
5060 /*
5061 * If the option takes no argument on the command line, we have to
5062 * check if the value is "true". We support non-zero numeric values,
5063 * true, on and yes.
5064 */
5065 if (!long_options[i].has_arg) {
5066 ret = config_parse_value(entry->value);
5067 if (ret <= 0) {
5068 if (ret) {
5069 WARN("Invalid configuration value \"%s\" for option %s",
5070 entry->value, entry->name);
5071 }
5072 /* False, skip boolean config option. */
5073 goto end;
5074 }
5075 }
5076
5077 ret = set_option(long_options[i].val, entry->value, entry->name);
5078 goto end;
5079 }
5080
5081 WARN("Unrecognized option \"%s\" in daemon configuration file.", entry->name);
5082
5083 end:
5084 return ret;
5085 }
5086
5087 /*
5088 * daemon configuration loading and argument parsing
5089 */
5090 static int set_options(int argc, char **argv)
5091 {
5092 int ret = 0, c = 0, option_index = 0;
5093 int orig_optopt = optopt, orig_optind = optind;
5094 char *optstring;
5095 const char *config_path = NULL;
5096
5097 optstring = utils_generate_optstring(long_options,
5098 sizeof(long_options) / sizeof(struct option));
5099 if (!optstring) {
5100 ret = -ENOMEM;
5101 goto end;
5102 }
5103
5104 /* Check for the --config option */
5105 while ((c = getopt_long(argc, argv, optstring, long_options,
5106 &option_index)) != -1) {
5107 if (c == '?') {
5108 ret = -EINVAL;
5109 goto end;
5110 } else if (c != 'f') {
5111 /* if not equal to --config option. */
5112 continue;
5113 }
5114
5115 if (lttng_is_setuid_setgid()) {
5116 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
5117 "-f, --config");
5118 } else {
5119 config_path = utils_expand_path(optarg);
5120 if (!config_path) {
5121 ERR("Failed to resolve path: %s", optarg);
5122 }
5123 }
5124 }
5125
5126 ret = config_get_section_entries(config_path, config_section_name,
5127 config_entry_handler, NULL);
5128 if (ret) {
5129 if (ret > 0) {
5130 ERR("Invalid configuration option at line %i", ret);
5131 ret = -1;
5132 }
5133 goto end;
5134 }
5135
5136 /* Reset getopt's global state */
5137 optopt = orig_optopt;
5138 optind = orig_optind;
5139 while (1) {
5140 option_index = -1;
5141 /*
5142 * getopt_long() will not set option_index if it encounters a
5143 * short option.
5144 */
5145 c = getopt_long(argc, argv, optstring, long_options,
5146 &option_index);
5147 if (c == -1) {
5148 break;
5149 }
5150
5151 /*
5152 * Pass NULL as the long option name if popt left the index
5153 * unset.
5154 */
5155 ret = set_option(c, optarg,
5156 option_index < 0 ? NULL :
5157 long_options[option_index].name);
5158 if (ret < 0) {
5159 break;
5160 }
5161 }
5162
5163 end:
5164 free(optstring);
5165 return ret;
5166 }
5167
5168 /*
5169 * Creates the two needed socket by the daemon.
5170 * apps_sock - The communication socket for all UST apps.
5171 * client_sock - The communication of the cli tool (lttng).
5172 */
5173 static int init_daemon_socket(void)
5174 {
5175 int ret = 0;
5176 mode_t old_umask;
5177
5178 old_umask = umask(0);
5179
5180 /* Create client tool unix socket */
5181 client_sock = lttcomm_create_unix_sock(client_unix_sock_path);
5182 if (client_sock < 0) {
5183 ERR("Create unix sock failed: %s", client_unix_sock_path);
5184 ret = -1;
5185 goto end;
5186 }
5187
5188 /* Set the cloexec flag */
5189 ret = utils_set_fd_cloexec(client_sock);
5190 if (ret < 0) {
5191 ERR("Unable to set CLOEXEC flag to the client Unix socket (fd: %d). "
5192 "Continuing but note that the consumer daemon will have a "
5193 "reference to this socket on exec()", client_sock);
5194 }
5195
5196 /* File permission MUST be 660 */
5197 ret = chmod(client_unix_sock_path, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
5198 if (ret < 0) {
5199 ERR("Set file permissions failed: %s", client_unix_sock_path);
5200 PERROR("chmod");
5201 goto end;
5202 }
5203
5204 /* Create the application unix socket */
5205 apps_sock = lttcomm_create_unix_sock(apps_unix_sock_path);
5206 if (apps_sock < 0) {
5207 ERR("Create unix sock failed: %s", apps_unix_sock_path);
5208 ret = -1;
5209 goto end;
5210 }
5211
5212 /* Set the cloexec flag */
5213 ret = utils_set_fd_cloexec(apps_sock);
5214 if (ret < 0) {
5215 ERR("Unable to set CLOEXEC flag to the app Unix socket (fd: %d). "
5216 "Continuing but note that the consumer daemon will have a "
5217 "reference to this socket on exec()", apps_sock);
5218 }
5219
5220 /* File permission MUST be 666 */
5221 ret = chmod(apps_unix_sock_path,
5222 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
5223 if (ret < 0) {
5224 ERR("Set file permissions failed: %s", apps_unix_sock_path);
5225 PERROR("chmod");
5226 goto end;
5227 }
5228
5229 DBG3("Session daemon client socket %d and application socket %d created",
5230 client_sock, apps_sock);
5231
5232 end:
5233 umask(old_umask);
5234 return ret;
5235 }
5236
5237 /*
5238 * Check if the global socket is available, and if a daemon is answering at the
5239 * other side. If yes, error is returned.
5240 */
5241 static int check_existing_daemon(void)
5242 {
5243 /* Is there anybody out there ? */
5244 if (lttng_session_daemon_alive()) {
5245 return -EEXIST;
5246 }
5247
5248 return 0;
5249 }
5250
5251 /*
5252 * Set the tracing group gid onto the client socket.
5253 *
5254 * Race window between mkdir and chown is OK because we are going from more
5255 * permissive (root.root) to less permissive (root.tracing).
5256 */
5257 static int set_permissions(char *rundir)
5258 {
5259 int ret;
5260 gid_t gid;
5261
5262 gid = utils_get_group_id(tracing_group_name);
5263
5264 /* Set lttng run dir */
5265 ret = chown(rundir, 0, gid);
5266 if (ret < 0) {
5267 ERR("Unable to set group on %s", rundir);
5268 PERROR("chown");
5269 }
5270
5271 /*
5272 * Ensure all applications and tracing group can search the run
5273 * dir. Allow everyone to read the directory, since it does not
5274 * buy us anything to hide its content.
5275 */
5276 ret = chmod(rundir, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
5277 if (ret < 0) {
5278 ERR("Unable to set permissions on %s", rundir);
5279 PERROR("chmod");
5280 }
5281
5282 /* lttng client socket path */
5283 ret = chown(client_unix_sock_path, 0, gid);
5284 if (ret < 0) {
5285 ERR("Unable to set group on %s", client_unix_sock_path);
5286 PERROR("chown");
5287 }
5288
5289 /* kconsumer error socket path */
5290 ret = chown(kconsumer_data.err_unix_sock_path, 0, 0);
5291 if (ret < 0) {
5292 ERR("Unable to set group on %s", kconsumer_data.err_unix_sock_path);
5293 PERROR("chown");
5294 }
5295
5296 /* 64-bit ustconsumer error socket path */
5297 ret = chown(ustconsumer64_data.err_unix_sock_path, 0, 0);
5298 if (ret < 0) {
5299 ERR("Unable to set group on %s", ustconsumer64_data.err_unix_sock_path);
5300 PERROR("chown");
5301 }
5302
5303 /* 32-bit ustconsumer compat32 error socket path */
5304 ret = chown(ustconsumer32_data.err_unix_sock_path, 0, 0);
5305 if (ret < 0) {
5306 ERR("Unable to set group on %s", ustconsumer32_data.err_unix_sock_path);
5307 PERROR("chown");
5308 }
5309
5310 DBG("All permissions are set");
5311
5312 return ret;
5313 }
5314
5315 /*
5316 * Create the lttng run directory needed for all global sockets and pipe.
5317 */
5318 static int create_lttng_rundir(const char *rundir)
5319 {
5320 int ret;
5321
5322 DBG3("Creating LTTng run directory: %s", rundir);
5323
5324 ret = mkdir(rundir, S_IRWXU);
5325 if (ret < 0) {
5326 if (errno != EEXIST) {
5327 ERR("Unable to create %s", rundir);
5328 goto error;
5329 } else {
5330 ret = 0;
5331 }
5332 }
5333
5334 error:
5335 return ret;
5336 }
5337
5338 /*
5339 * Setup sockets and directory needed by the kconsumerd communication with the
5340 * session daemon.
5341 */
5342 static int set_consumer_sockets(struct consumer_data *consumer_data,
5343 const char *rundir)
5344 {
5345 int ret;
5346 char path[PATH_MAX];
5347
5348 switch (consumer_data->type) {
5349 case LTTNG_CONSUMER_KERNEL:
5350 snprintf(path, PATH_MAX, DEFAULT_KCONSUMERD_PATH, rundir);
5351 break;
5352 case LTTNG_CONSUMER64_UST:
5353 snprintf(path, PATH_MAX, DEFAULT_USTCONSUMERD64_PATH, rundir);
5354 break;
5355 case LTTNG_CONSUMER32_UST:
5356 snprintf(path, PATH_MAX, DEFAULT_USTCONSUMERD32_PATH, rundir);
5357 break;
5358 default:
5359 ERR("Consumer type unknown");
5360 ret = -EINVAL;
5361 goto error;
5362 }
5363
5364 DBG2("Creating consumer directory: %s", path);
5365
5366 ret = mkdir(path, S_IRWXU | S_IRGRP | S_IXGRP);
5367 if (ret < 0) {
5368 if (errno != EEXIST) {
5369 PERROR("mkdir");
5370 ERR("Failed to create %s", path);
5371 goto error;
5372 }
5373 ret = -1;
5374 }
5375 if (is_root) {
5376 ret = chown(path, 0, utils_get_group_id(tracing_group_name));
5377 if (ret < 0) {
5378 ERR("Unable to set group on %s", path);
5379 PERROR("chown");
5380 goto error;
5381 }
5382 }
5383
5384 /* Create the kconsumerd error unix socket */
5385 consumer_data->err_sock =
5386 lttcomm_create_unix_sock(consumer_data->err_unix_sock_path);
5387 if (consumer_data->err_sock < 0) {
5388 ERR("Create unix sock failed: %s", consumer_data->err_unix_sock_path);
5389 ret = -1;
5390 goto error;
5391 }
5392
5393 /*
5394 * Set the CLOEXEC flag. Return code is useless because either way, the
5395 * show must go on.
5396 */
5397 ret = utils_set_fd_cloexec(consumer_data->err_sock);
5398 if (ret < 0) {
5399 PERROR("utils_set_fd_cloexec");
5400 /* continue anyway */
5401 }
5402
5403 /* File permission MUST be 660 */
5404 ret = chmod(consumer_data->err_unix_sock_path,
5405 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
5406 if (ret < 0) {
5407 ERR("Set file permissions failed: %s", consumer_data->err_unix_sock_path);
5408 PERROR("chmod");
5409 goto error;
5410 }
5411
5412 error:
5413 return ret;
5414 }
5415
5416 /*
5417 * Signal handler for the daemon
5418 *
5419 * Simply stop all worker threads, leaving main() return gracefully after
5420 * joining all threads and calling cleanup().
5421 */
5422 static void sighandler(int sig)
5423 {
5424 switch (sig) {
5425 case SIGINT:
5426 DBG("SIGINT caught");
5427 stop_threads();
5428 break;
5429 case SIGTERM:
5430 DBG("SIGTERM caught");
5431 stop_threads();
5432 break;
5433 case SIGUSR1:
5434 CMM_STORE_SHARED(recv_child_signal, 1);
5435 break;
5436 default:
5437 break;
5438 }
5439 }
5440
5441 /*
5442 * Setup signal handler for :
5443 * SIGINT, SIGTERM, SIGPIPE
5444 */
5445 static int set_signal_handler(void)
5446 {
5447 int ret = 0;
5448 struct sigaction sa;
5449 sigset_t sigset;
5450
5451 if ((ret = sigemptyset(&sigset)) < 0) {
5452 PERROR("sigemptyset");
5453 return ret;
5454 }
5455
5456 sa.sa_mask = sigset;
5457 sa.sa_flags = 0;
5458
5459 sa.sa_handler = sighandler;
5460 if ((ret = sigaction(SIGTERM, &sa, NULL)) < 0) {
5461 PERROR("sigaction");
5462 return ret;
5463 }
5464
5465 if ((ret = sigaction(SIGINT, &sa, NULL)) < 0) {
5466 PERROR("sigaction");
5467 return ret;
5468 }
5469
5470 if ((ret = sigaction(SIGUSR1, &sa, NULL)) < 0) {
5471 PERROR("sigaction");
5472 return ret;
5473 }
5474
5475 sa.sa_handler = SIG_IGN;
5476 if ((ret = sigaction(SIGPIPE, &sa, NULL)) < 0) {
5477 PERROR("sigaction");
5478 return ret;
5479 }
5480
5481 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
5482
5483 return ret;
5484 }
5485
5486 /*
5487 * Set open files limit to unlimited. This daemon can open a large number of
5488 * file descriptors in order to consumer multiple kernel traces.
5489 */
5490 static void set_ulimit(void)
5491 {
5492 int ret;
5493 struct rlimit lim;
5494
5495 /* The kernel does not allowed an infinite limit for open files */
5496 lim.rlim_cur = 65535;
5497 lim.rlim_max = 65535;
5498
5499 ret = setrlimit(RLIMIT_NOFILE, &lim);
5500 if (ret < 0) {
5501 PERROR("failed to set open files limit");
5502 }
5503 }
5504
5505 /*
5506 * Write pidfile using the rundir and opt_pidfile.
5507 */
5508 static int write_pidfile(void)
5509 {
5510 int ret;
5511 char pidfile_path[PATH_MAX];
5512
5513 assert(rundir);
5514
5515 if (opt_pidfile) {
5516 if (lttng_strncpy(pidfile_path, opt_pidfile, sizeof(pidfile_path))) {
5517 ret = -1;
5518 goto error;
5519 }
5520 } else {
5521 /* Build pidfile path from rundir and opt_pidfile. */
5522 ret = snprintf(pidfile_path, sizeof(pidfile_path), "%s/"
5523 DEFAULT_LTTNG_SESSIOND_PIDFILE, rundir);
5524 if (ret < 0) {
5525 PERROR("snprintf pidfile path");
5526 goto error;
5527 }
5528 }
5529
5530 /*
5531 * Create pid file in rundir.
5532 */
5533 ret = utils_create_pid_file(getpid(), pidfile_path);
5534 error:
5535 return ret;
5536 }
5537
5538 /*
5539 * Create lockfile using the rundir and return its fd.
5540 */
5541 static int create_lockfile(void)
5542 {
5543 int ret;
5544 char lockfile_path[PATH_MAX];
5545
5546 ret = generate_lock_file_path(lockfile_path, sizeof(lockfile_path));
5547 if (ret < 0) {
5548 goto error;
5549 }
5550
5551 ret = utils_create_lock_file(lockfile_path);
5552 error:
5553 return ret;
5554 }
5555
5556 /*
5557 * Write agent TCP port using the rundir.
5558 */
5559 static int write_agent_port(void)
5560 {
5561 int ret;
5562 char path[PATH_MAX];
5563
5564 assert(rundir);
5565
5566 ret = snprintf(path, sizeof(path), "%s/"
5567 DEFAULT_LTTNG_SESSIOND_AGENTPORT_FILE, rundir);
5568 if (ret < 0) {
5569 PERROR("snprintf agent port path");
5570 goto error;
5571 }
5572
5573 /*
5574 * Create TCP agent port file in rundir.
5575 */
5576 ret = utils_create_pid_file(agent_tcp_port, path);
5577
5578 error:
5579 return ret;
5580 }
5581
5582 /*
5583 * main
5584 */
5585 int main(int argc, char **argv)
5586 {
5587 int ret = 0, retval = 0;
5588 void *status;
5589 const char *home_path, *env_app_timeout;
5590
5591 init_kernel_workarounds();
5592
5593 rcu_register_thread();
5594
5595 if (set_signal_handler()) {
5596 retval = -1;
5597 goto exit_set_signal_handler;
5598 }
5599
5600 setup_consumerd_path();
5601
5602 page_size = sysconf(_SC_PAGESIZE);
5603 if (page_size < 0) {
5604 PERROR("sysconf _SC_PAGESIZE");
5605 page_size = LONG_MAX;
5606 WARN("Fallback page size to %ld", page_size);
5607 }
5608
5609 /*
5610 * Parse arguments and load the daemon configuration file.
5611 *
5612 * We have an exit_options exit path to free memory reserved by
5613 * set_options. This is needed because the rest of sessiond_cleanup()
5614 * depends on ht_cleanup_thread, which depends on lttng_daemonize, which
5615 * depends on set_options.
5616 */
5617 progname = argv[0];
5618 if (set_options(argc, argv)) {
5619 retval = -1;
5620 goto exit_options;
5621 }
5622
5623 /* Daemonize */
5624 if (opt_daemon || opt_background) {
5625 int i;
5626
5627 ret = lttng_daemonize(&child_ppid, &recv_child_signal,
5628 !opt_background);
5629 if (ret < 0) {
5630 retval = -1;
5631 goto exit_options;
5632 }
5633
5634 /*
5635 * We are in the child. Make sure all other file descriptors are
5636 * closed, in case we are called with more opened file
5637 * descriptors than the standard ones.
5638 */
5639 for (i = 3; i < sysconf(_SC_OPEN_MAX); i++) {
5640 (void) close(i);
5641 }
5642 }
5643
5644 if (run_as_create_worker(argv[0]) < 0) {
5645 goto exit_create_run_as_worker_cleanup;
5646 }
5647
5648 /*
5649 * Starting from here, we can create threads. This needs to be after
5650 * lttng_daemonize due to RCU.
5651 */
5652
5653 /*
5654 * Initialize the health check subsystem. This call should set the
5655 * appropriate time values.
5656 */
5657 health_sessiond = health_app_create(NR_HEALTH_SESSIOND_TYPES);
5658 if (!health_sessiond) {
5659 PERROR("health_app_create error");
5660 retval = -1;
5661 goto exit_health_sessiond_cleanup;
5662 }
5663
5664 if (init_ht_cleanup_quit_pipe()) {
5665 retval = -1;
5666 goto exit_ht_cleanup_quit_pipe;
5667 }
5668
5669 /* Setup the thread ht_cleanup communication pipe. */
5670 if (utils_create_pipe_cloexec(ht_cleanup_pipe)) {
5671 retval = -1;
5672 goto exit_ht_cleanup_pipe;
5673 }
5674
5675 /* Set up max poll set size */
5676 if (lttng_poll_set_max_size()) {
5677 retval = -1;
5678 goto exit_set_max_size;
5679 }
5680
5681 /* Create thread to clean up RCU hash tables */
5682 ret = pthread_create(&ht_cleanup_thread, NULL,
5683 thread_ht_cleanup, (void *) NULL);
5684 if (ret) {
5685 errno = ret;
5686 PERROR("pthread_create ht_cleanup");
5687 retval = -1;
5688 goto exit_ht_cleanup;
5689 }
5690
5691 /* Create thread quit pipe */
5692 if (init_thread_quit_pipe()) {
5693 retval = -1;
5694 goto exit_init_data;
5695 }
5696
5697 /* Check if daemon is UID = 0 */
5698 is_root = !getuid();
5699
5700 if (is_root) {
5701 rundir = strdup(DEFAULT_LTTNG_RUNDIR);
5702 if (!rundir) {
5703 retval = -1;
5704 goto exit_init_data;
5705 }
5706
5707 /* Create global run dir with root access */
5708 if (create_lttng_rundir(rundir)) {
5709 retval = -1;
5710 goto exit_init_data;
5711 }
5712
5713 if (strlen(apps_unix_sock_path) == 0) {
5714 ret = snprintf(apps_unix_sock_path, PATH_MAX,
5715 DEFAULT_GLOBAL_APPS_UNIX_SOCK);
5716 if (ret < 0) {
5717 retval = -1;
5718 goto exit_init_data;
5719 }
5720 }
5721
5722 if (strlen(client_unix_sock_path) == 0) {
5723 ret = snprintf(client_unix_sock_path, PATH_MAX,
5724 DEFAULT_GLOBAL_CLIENT_UNIX_SOCK);
5725 if (ret < 0) {
5726 retval = -1;
5727 goto exit_init_data;
5728 }
5729 }
5730
5731 /* Set global SHM for ust */
5732 if (strlen(wait_shm_path) == 0) {
5733 ret = snprintf(wait_shm_path, PATH_MAX,
5734 DEFAULT_GLOBAL_APPS_WAIT_SHM_PATH);
5735 if (ret < 0) {
5736 retval = -1;
5737 goto exit_init_data;
5738 }
5739 }
5740
5741 if (strlen(health_unix_sock_path) == 0) {
5742 ret = snprintf(health_unix_sock_path,
5743 sizeof(health_unix_sock_path),
5744 DEFAULT_GLOBAL_HEALTH_UNIX_SOCK);
5745 if (ret < 0) {
5746 retval = -1;
5747 goto exit_init_data;
5748 }
5749 }
5750
5751 /* Setup kernel consumerd path */
5752 ret = snprintf(kconsumer_data.err_unix_sock_path, PATH_MAX,
5753 DEFAULT_KCONSUMERD_ERR_SOCK_PATH, rundir);
5754 if (ret < 0) {
5755 retval = -1;
5756 goto exit_init_data;
5757 }
5758 ret = snprintf(kconsumer_data.cmd_unix_sock_path, PATH_MAX,
5759 DEFAULT_KCONSUMERD_CMD_SOCK_PATH, rundir);
5760 if (ret < 0) {
5761 retval = -1;
5762 goto exit_init_data;
5763 }
5764
5765 DBG2("Kernel consumer err path: %s",
5766 kconsumer_data.err_unix_sock_path);
5767 DBG2("Kernel consumer cmd path: %s",
5768 kconsumer_data.cmd_unix_sock_path);
5769 } else {
5770 home_path = utils_get_home_dir();
5771 if (home_path == NULL) {
5772 /* TODO: Add --socket PATH option */
5773 ERR("Can't get HOME directory for sockets creation.");
5774 retval = -1;
5775 goto exit_init_data;
5776 }
5777
5778 /*
5779 * Create rundir from home path. This will create something like
5780 * $HOME/.lttng
5781 */
5782 ret = asprintf(&rundir, DEFAULT_LTTNG_HOME_RUNDIR, home_path);
5783 if (ret < 0) {
5784 retval = -1;
5785 goto exit_init_data;
5786 }
5787
5788 if (create_lttng_rundir(rundir)) {
5789 retval = -1;
5790 goto exit_init_data;
5791 }
5792
5793 if (strlen(apps_unix_sock_path) == 0) {
5794 ret = snprintf(apps_unix_sock_path, PATH_MAX,
5795 DEFAULT_HOME_APPS_UNIX_SOCK,
5796 home_path);
5797 if (ret < 0) {
5798 retval = -1;
5799 goto exit_init_data;
5800 }
5801 }
5802
5803 /* Set the cli tool unix socket path */
5804 if (strlen(client_unix_sock_path) == 0) {
5805 ret = snprintf(client_unix_sock_path, PATH_MAX,
5806 DEFAULT_HOME_CLIENT_UNIX_SOCK,
5807 home_path);
5808 if (ret < 0) {
5809 retval = -1;
5810 goto exit_init_data;
5811 }
5812 }
5813
5814 /* Set global SHM for ust */
5815 if (strlen(wait_shm_path) == 0) {
5816 ret = snprintf(wait_shm_path, PATH_MAX,
5817 DEFAULT_HOME_APPS_WAIT_SHM_PATH,
5818 getuid());
5819 if (ret < 0) {
5820 retval = -1;
5821 goto exit_init_data;
5822 }
5823 }
5824
5825 /* Set health check Unix path */
5826 if (strlen(health_unix_sock_path) == 0) {
5827 ret = snprintf(health_unix_sock_path,
5828 sizeof(health_unix_sock_path),
5829 DEFAULT_HOME_HEALTH_UNIX_SOCK,
5830 home_path);
5831 if (ret < 0) {
5832 retval = -1;
5833 goto exit_init_data;
5834 }
5835 }
5836 }
5837
5838 lockfile_fd = create_lockfile();
5839 if (lockfile_fd < 0) {
5840 retval = -1;
5841 goto exit_init_data;
5842 }
5843
5844 /* Set consumer initial state */
5845 kernel_consumerd_state = CONSUMER_STOPPED;
5846 ust_consumerd_state = CONSUMER_STOPPED;
5847
5848 DBG("Client socket path %s", client_unix_sock_path);
5849 DBG("Application socket path %s", apps_unix_sock_path);
5850 DBG("Application wait path %s", wait_shm_path);
5851 DBG("LTTng run directory path: %s", rundir);
5852
5853 /* 32 bits consumerd path setup */
5854 ret = snprintf(ustconsumer32_data.err_unix_sock_path, PATH_MAX,
5855 DEFAULT_USTCONSUMERD32_ERR_SOCK_PATH, rundir);
5856 if (ret < 0) {
5857 PERROR("snprintf 32-bit consumer error socket path");
5858 retval = -1;
5859 goto exit_init_data;
5860 }
5861 ret = snprintf(ustconsumer32_data.cmd_unix_sock_path, PATH_MAX,
5862 DEFAULT_USTCONSUMERD32_CMD_SOCK_PATH, rundir);
5863 if (ret < 0) {
5864 PERROR("snprintf 32-bit consumer command socket path");
5865 retval = -1;
5866 goto exit_init_data;
5867 }
5868
5869 DBG2("UST consumer 32 bits err path: %s",
5870 ustconsumer32_data.err_unix_sock_path);
5871 DBG2("UST consumer 32 bits cmd path: %s",
5872 ustconsumer32_data.cmd_unix_sock_path);
5873
5874 /* 64 bits consumerd path setup */
5875 ret = snprintf(ustconsumer64_data.err_unix_sock_path, PATH_MAX,
5876 DEFAULT_USTCONSUMERD64_ERR_SOCK_PATH, rundir);
5877 if (ret < 0) {
5878 PERROR("snprintf 64-bit consumer error socket path");
5879 retval = -1;
5880 goto exit_init_data;
5881 }
5882 ret = snprintf(ustconsumer64_data.cmd_unix_sock_path, PATH_MAX,
5883 DEFAULT_USTCONSUMERD64_CMD_SOCK_PATH, rundir);
5884 if (ret < 0) {
5885 PERROR("snprintf 64-bit consumer command socket path");
5886 retval = -1;
5887 goto exit_init_data;
5888 }
5889
5890 DBG2("UST consumer 64 bits err path: %s",
5891 ustconsumer64_data.err_unix_sock_path);
5892 DBG2("UST consumer 64 bits cmd path: %s",
5893 ustconsumer64_data.cmd_unix_sock_path);
5894
5895 /*
5896 * See if daemon already exist.
5897 */
5898 if (check_existing_daemon()) {
5899 ERR("Already running daemon.\n");
5900 /*
5901 * We do not goto exit because we must not cleanup()
5902 * because a daemon is already running.
5903 */
5904 retval = -1;
5905 goto exit_init_data;
5906 }
5907
5908 /*
5909 * Init UST app hash table. Alloc hash table before this point since
5910 * cleanup() can get called after that point.
5911 */
5912 if (ust_app_ht_alloc()) {
5913 ERR("Failed to allocate UST app hash table");
5914 retval = -1;
5915 goto exit_init_data;
5916 }
5917
5918 /*
5919 * Initialize agent app hash table. We allocate the hash table here
5920 * since cleanup() can get called after this point.
5921 */
5922 if (agent_app_ht_alloc()) {
5923 ERR("Failed to allocate Agent app hash table");
5924 retval = -1;
5925 goto exit_init_data;
5926 }
5927
5928 /*
5929 * These actions must be executed as root. We do that *after* setting up
5930 * the sockets path because we MUST make the check for another daemon using
5931 * those paths *before* trying to set the kernel consumer sockets and init
5932 * kernel tracer.
5933 */
5934 if (is_root) {
5935 if (set_consumer_sockets(&kconsumer_data, rundir)) {
5936 retval = -1;
5937 goto exit_init_data;
5938 }
5939
5940 /* Setup kernel tracer */
5941 if (!opt_no_kernel) {
5942 init_kernel_tracer();
5943 if (kernel_tracer_fd >= 0) {
5944 ret = syscall_init_table();
5945 if (ret < 0) {
5946 ERR("Unable to populate syscall table. "
5947 "Syscall tracing won't work "
5948 "for this session daemon.");
5949 }
5950 }
5951 }
5952
5953 /* Set ulimit for open files */
5954 set_ulimit();
5955 }
5956 /* init lttng_fd tracking must be done after set_ulimit. */
5957 lttng_fd_init();
5958
5959 if (set_consumer_sockets(&ustconsumer64_data, rundir)) {
5960 retval = -1;
5961 goto exit_init_data;
5962 }
5963
5964 if (set_consumer_sockets(&ustconsumer32_data, rundir)) {
5965 retval = -1;
5966 goto exit_init_data;
5967 }
5968
5969 /* Setup the needed unix socket */
5970 if (init_daemon_socket()) {
5971 retval = -1;
5972 goto exit_init_data;
5973 }
5974
5975 /* Set credentials to socket */
5976 if (is_root && set_permissions(rundir)) {
5977 retval = -1;
5978 goto exit_init_data;
5979 }
5980
5981 /* Get parent pid if -S, --sig-parent is specified. */
5982 if (opt_sig_parent) {
5983 ppid = getppid();
5984 }
5985
5986 /* Setup the kernel pipe for waking up the kernel thread */
5987 if (is_root && !opt_no_kernel) {
5988 if (utils_create_pipe_cloexec(kernel_poll_pipe)) {
5989 retval = -1;
5990 goto exit_init_data;
5991 }
5992 }
5993
5994 /* Setup the thread apps communication pipe. */
5995 if (utils_create_pipe_cloexec(apps_cmd_pipe)) {
5996 retval = -1;
5997 goto exit_init_data;
5998 }
5999
6000 /* Setup the thread apps notify communication pipe. */
6001 if (utils_create_pipe_cloexec(apps_cmd_notify_pipe)) {
6002 retval = -1;
6003 goto exit_init_data;
6004 }
6005
6006 /* Initialize global buffer per UID and PID registry. */
6007 buffer_reg_init_uid_registry();
6008 buffer_reg_init_pid_registry();
6009
6010 /* Init UST command queue. */
6011 cds_wfcq_init(&ust_cmd_queue.head, &ust_cmd_queue.tail);
6012
6013 /*
6014 * Get session list pointer. This pointer MUST NOT be free'd. This list
6015 * is statically declared in session.c
6016 */
6017 session_list_ptr = session_get_list();
6018
6019 cmd_init();
6020
6021 /* Check for the application socket timeout env variable. */
6022 env_app_timeout = getenv(DEFAULT_APP_SOCKET_TIMEOUT_ENV);
6023 if (env_app_timeout) {
6024 app_socket_timeout = atoi(env_app_timeout);
6025 } else {
6026 app_socket_timeout = DEFAULT_APP_SOCKET_RW_TIMEOUT;
6027 }
6028
6029 ret = write_pidfile();
6030 if (ret) {
6031 ERR("Error in write_pidfile");
6032 retval = -1;
6033 goto exit_init_data;
6034 }
6035 ret = write_agent_port();
6036 if (ret) {
6037 ERR("Error in write_agent_port");
6038 retval = -1;
6039 goto exit_init_data;
6040 }
6041
6042 /* Initialize communication library */
6043 lttcomm_init();
6044 /* Initialize TCP timeout values */
6045 lttcomm_inet_init();
6046
6047 if (load_session_init_data(&load_info) < 0) {
6048 retval = -1;
6049 goto exit_init_data;
6050 }
6051 load_info->path = opt_load_session_path;
6052
6053 /* Create health-check thread */
6054 ret = pthread_create(&health_thread, NULL,
6055 thread_manage_health, (void *) NULL);
6056 if (ret) {
6057 errno = ret;
6058 PERROR("pthread_create health");
6059 retval = -1;
6060 goto exit_health;
6061 }
6062
6063 /* Create thread to manage the client socket */
6064 ret = pthread_create(&client_thread, NULL,
6065 thread_manage_clients, (void *) NULL);
6066 if (ret) {
6067 errno = ret;
6068 PERROR("pthread_create clients");
6069 retval = -1;
6070 goto exit_client;
6071 }
6072
6073 /* Create thread to dispatch registration */
6074 ret = pthread_create(&dispatch_thread, NULL,
6075 thread_dispatch_ust_registration, (void *) NULL);
6076 if (ret) {
6077 errno = ret;
6078 PERROR("pthread_create dispatch");
6079 retval = -1;
6080 goto exit_dispatch;
6081 }
6082
6083 /* Create thread to manage application registration. */
6084 ret = pthread_create(&reg_apps_thread, NULL,
6085 thread_registration_apps, (void *) NULL);
6086 if (ret) {
6087 errno = ret;
6088 PERROR("pthread_create registration");
6089 retval = -1;
6090 goto exit_reg_apps;
6091 }
6092
6093 /* Create thread to manage application socket */
6094 ret = pthread_create(&apps_thread, NULL,
6095 thread_manage_apps, (void *) NULL);
6096 if (ret) {
6097 errno = ret;
6098 PERROR("pthread_create apps");
6099 retval = -1;
6100 goto exit_apps;
6101 }
6102
6103 /* Create thread to manage application notify socket */
6104 ret = pthread_create(&apps_notify_thread, NULL,
6105 ust_thread_manage_notify, (void *) NULL);
6106 if (ret) {
6107 errno = ret;
6108 PERROR("pthread_create notify");
6109 retval = -1;
6110 goto exit_apps_notify;
6111 }
6112
6113 /* Create agent registration thread. */
6114 ret = pthread_create(&agent_reg_thread, NULL,
6115 agent_thread_manage_registration, (void *) NULL);
6116 if (ret) {
6117 errno = ret;
6118 PERROR("pthread_create agent");
6119 retval = -1;
6120 goto exit_agent_reg;
6121 }
6122
6123 /* Don't start this thread if kernel tracing is not requested nor root */
6124 if (is_root && !opt_no_kernel) {
6125 /* Create kernel thread to manage kernel event */
6126 ret = pthread_create(&kernel_thread, NULL,
6127 thread_manage_kernel, (void *) NULL);
6128 if (ret) {
6129 errno = ret;
6130 PERROR("pthread_create kernel");
6131 retval = -1;
6132 goto exit_kernel;
6133 }
6134 }
6135
6136 /* Create session loading thread. */
6137 ret = pthread_create(&load_session_thread, NULL, thread_load_session,
6138 load_info);
6139 if (ret) {
6140 errno = ret;
6141 PERROR("pthread_create load_session_thread");
6142 retval = -1;
6143 goto exit_load_session;
6144 }
6145
6146 /*
6147 * This is where we start awaiting program completion (e.g. through
6148 * signal that asks threads to teardown).
6149 */
6150
6151 ret = pthread_join(load_session_thread, &status);
6152 if (ret) {
6153 errno = ret;
6154 PERROR("pthread_join load_session_thread");
6155 retval = -1;
6156 }
6157 exit_load_session:
6158
6159 if (is_root && !opt_no_kernel) {
6160 ret = pthread_join(kernel_thread, &status);
6161 if (ret) {
6162 errno = ret;
6163 PERROR("pthread_join");
6164 retval = -1;
6165 }
6166 }
6167 exit_kernel:
6168
6169 ret = pthread_join(agent_reg_thread, &status);
6170 if (ret) {
6171 errno = ret;
6172 PERROR("pthread_join agent");
6173 retval = -1;
6174 }
6175 exit_agent_reg:
6176
6177 ret = pthread_join(apps_notify_thread, &status);
6178 if (ret) {
6179 errno = ret;
6180 PERROR("pthread_join apps notify");
6181 retval = -1;
6182 }
6183 exit_apps_notify:
6184
6185 ret = pthread_join(apps_thread, &status);
6186 if (ret) {
6187 errno = ret;
6188 PERROR("pthread_join apps");
6189 retval = -1;
6190 }
6191 exit_apps:
6192
6193 ret = pthread_join(reg_apps_thread, &status);
6194 if (ret) {
6195 errno = ret;
6196 PERROR("pthread_join");
6197 retval = -1;
6198 }
6199 exit_reg_apps:
6200
6201 /*
6202 * Join dispatch thread after joining reg_apps_thread to ensure
6203 * we don't leak applications in the queue.
6204 */
6205 ret = pthread_join(dispatch_thread, &status);
6206 if (ret) {
6207 errno = ret;
6208 PERROR("pthread_join");
6209 retval = -1;
6210 }
6211 exit_dispatch:
6212
6213 ret = pthread_join(client_thread, &status);
6214 if (ret) {
6215 errno = ret;
6216 PERROR("pthread_join");
6217 retval = -1;
6218 }
6219 exit_client:
6220
6221 ret = pthread_join(health_thread, &status);
6222 if (ret) {
6223 errno = ret;
6224 PERROR("pthread_join health thread");
6225 retval = -1;
6226 }
6227 exit_health:
6228
6229 exit_init_data:
6230 /*
6231 * Wait for all pending call_rcu work to complete before tearing
6232 * down data structures. call_rcu worker may be trying to
6233 * perform lookups in those structures.
6234 */
6235 rcu_barrier();
6236 /*
6237 * sessiond_cleanup() is called when no other thread is running, except
6238 * the ht_cleanup thread, which is needed to destroy the hash tables.
6239 */
6240 rcu_thread_online();
6241 sessiond_cleanup();
6242 rcu_thread_offline();
6243 rcu_unregister_thread();
6244
6245 /*
6246 * Ensure all prior call_rcu are done. call_rcu callbacks may push
6247 * hash tables to the ht_cleanup thread. Therefore, we ensure that
6248 * the queue is empty before shutting down the clean-up thread.
6249 */
6250 rcu_barrier();
6251
6252 ret = notify_thread_pipe(ht_cleanup_quit_pipe[1]);
6253 if (ret < 0) {
6254 ERR("write error on ht_cleanup quit pipe");
6255 retval = -1;
6256 }
6257
6258 ret = pthread_join(ht_cleanup_thread, &status);
6259 if (ret) {
6260 errno = ret;
6261 PERROR("pthread_join ht cleanup thread");
6262 retval = -1;
6263 }
6264 exit_ht_cleanup:
6265 exit_set_max_size:
6266
6267 utils_close_pipe(ht_cleanup_pipe);
6268 exit_ht_cleanup_pipe:
6269
6270 /*
6271 * Close the ht_cleanup quit pipe.
6272 */
6273 utils_close_pipe(ht_cleanup_quit_pipe);
6274 exit_ht_cleanup_quit_pipe:
6275
6276 health_app_destroy(health_sessiond);
6277 exit_health_sessiond_cleanup:
6278 exit_create_run_as_worker_cleanup:
6279
6280 exit_options:
6281 sessiond_cleanup_options();
6282
6283 exit_set_signal_handler:
6284
6285 if (!retval) {
6286 exit(EXIT_SUCCESS);
6287 } else {
6288 exit(EXIT_FAILURE);
6289 }
6290 }
This page took 0.253823 seconds and 4 git commands to generate.