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