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