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