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