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