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