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