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