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