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