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