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