map shared memory for rendez-vous with non-responding sessiond
[lttng-ust.git] / libust / lttng-ust-comm.c
1 /*
2 * lttng-ust-comm.c
3 *
4 * Copyright (C) 2011 David Goulet <david.goulet@polymtl.ca>
5 * Copyright (C) 2011 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; only
10 * version 2.1 of the License.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 #include <sys/types.h>
23 #include <sys/socket.h>
24 #include <sys/prctl.h>
25 #include <sys/mman.h>
26 #include <sys/stat.h>
27 #include <fcntl.h>
28 #include <unistd.h>
29 #include <errno.h>
30 #include <pthread.h>
31 #include <semaphore.h>
32 #include <time.h>
33 #include <assert.h>
34 #include <signal.h>
35 #include <urcu/uatomic.h>
36
37 #include <lttng-ust-comm.h>
38 #include <ust/usterr-signal-safe.h>
39 #include <ust/lttng-ust-abi.h>
40 #include <ust/tracepoint.h>
41 #include <ust/tracepoint-internal.h>
42 #include <ust/ust.h>
43 #include "ltt-tracer-core.h"
44
45 /*
46 * Has lttng ust comm constructor been called ?
47 */
48 static int initialized;
49
50 /*
51 * The ust_lock/ust_unlock lock is used as a communication thread mutex.
52 * Held when handling a command, also held by fork() to deal with
53 * removal of threads, and by exit path.
54 */
55
56 /* Should the ust comm thread quit ? */
57 static int lttng_ust_comm_should_quit;
58
59 /*
60 * Wait for either of these before continuing to the main
61 * program:
62 * - the register_done message from sessiond daemon
63 * (will let the sessiond daemon enable sessions before main
64 * starts.)
65 * - sessiond daemon is not reachable.
66 * - timeout (ensuring applications are resilient to session
67 * daemon problems).
68 */
69 static sem_t constructor_wait;
70 /*
71 * Doing this for both the global and local sessiond.
72 */
73 static int sem_count = { 2 };
74
75 /*
76 * Info about socket and associated listener thread.
77 */
78 struct sock_info {
79 const char *name;
80 pthread_t ust_listener; /* listener thread */
81 int root_handle;
82 int constructor_sem_posted;
83 int allowed;
84
85 char sock_path[PATH_MAX];
86 int socket;
87
88 char wait_shm_path[PATH_MAX];
89 char *wait_shm_mmap;
90 };
91
92 /* Socket from app (connect) to session daemon (listen) for communication */
93 struct sock_info global_apps = {
94 .name = "global",
95
96 .root_handle = -1,
97 .allowed = 1,
98
99 .sock_path = DEFAULT_GLOBAL_APPS_UNIX_SOCK,
100 .socket = -1,
101
102 .wait_shm_path = DEFAULT_GLOBAL_APPS_WAIT_SHM_PATH,
103 };
104
105 /* TODO: allow global_apps_sock_path override */
106
107 struct sock_info local_apps = {
108 .name = "local",
109 .root_handle = -1,
110 .allowed = 0, /* Check setuid bit first */
111
112 .socket = -1,
113 };
114
115 extern void ltt_ring_buffer_client_overwrite_init(void);
116 extern void ltt_ring_buffer_client_discard_init(void);
117 extern void ltt_ring_buffer_metadata_client_init(void);
118 extern void ltt_ring_buffer_client_overwrite_exit(void);
119 extern void ltt_ring_buffer_client_discard_exit(void);
120 extern void ltt_ring_buffer_metadata_client_exit(void);
121
122 static
123 int setup_local_apps(void)
124 {
125 const char *home_dir;
126 uid_t uid;
127
128 uid = getuid();
129 /*
130 * Disallow per-user tracing for setuid binaries.
131 */
132 if (uid != geteuid()) {
133 local_apps.allowed = 0;
134 return 0;
135 } else {
136 local_apps.allowed = 1;
137 }
138 home_dir = (const char *) getenv("HOME");
139 if (!home_dir)
140 return -ENOENT;
141 snprintf(local_apps.sock_path, PATH_MAX,
142 DEFAULT_HOME_APPS_UNIX_SOCK, home_dir);
143 snprintf(local_apps.wait_shm_path, PATH_MAX,
144 DEFAULT_HOME_APPS_WAIT_SHM_PATH, uid);
145 return 0;
146 }
147
148 static
149 int register_app_to_sessiond(int socket)
150 {
151 ssize_t ret;
152 int prctl_ret;
153 struct {
154 uint32_t major;
155 uint32_t minor;
156 pid_t pid;
157 pid_t ppid;
158 uid_t uid;
159 gid_t gid;
160 char name[16]; /* process name */
161 } reg_msg;
162
163 reg_msg.major = LTTNG_UST_COMM_VERSION_MAJOR;
164 reg_msg.minor = LTTNG_UST_COMM_VERSION_MINOR;
165 reg_msg.pid = getpid();
166 reg_msg.ppid = getppid();
167 reg_msg.uid = getuid();
168 reg_msg.gid = getgid();
169 prctl_ret = prctl(PR_GET_NAME, (unsigned long) reg_msg.name, 0, 0, 0);
170 if (prctl_ret) {
171 ERR("Error executing prctl");
172 return -errno;
173 }
174
175 ret = lttcomm_send_unix_sock(socket, &reg_msg, sizeof(reg_msg));
176 if (ret >= 0 && ret != sizeof(reg_msg))
177 return -EIO;
178 return ret;
179 }
180
181 static
182 int send_reply(int sock, struct lttcomm_ust_reply *lur)
183 {
184 ssize_t len;
185
186 len = lttcomm_send_unix_sock(sock, lur, sizeof(*lur));
187 switch (len) {
188 case sizeof(*lur):
189 DBG("message successfully sent");
190 return 0;
191 case -1:
192 if (errno == ECONNRESET) {
193 printf("remote end closed connection\n");
194 return 0;
195 }
196 return -1;
197 default:
198 printf("incorrect message size: %zd\n", len);
199 return -1;
200 }
201 }
202
203 static
204 int handle_register_done(struct sock_info *sock_info)
205 {
206 int ret;
207
208 if (sock_info->constructor_sem_posted)
209 return 0;
210 sock_info->constructor_sem_posted = 1;
211 ret = uatomic_add_return(&sem_count, -1);
212 if (ret == 0) {
213 ret = sem_post(&constructor_wait);
214 assert(!ret);
215 }
216 return 0;
217 }
218
219 static
220 int handle_message(struct sock_info *sock_info,
221 int sock, struct lttcomm_ust_msg *lum)
222 {
223 int ret = 0;
224 const struct objd_ops *ops;
225 struct lttcomm_ust_reply lur;
226
227 ust_lock();
228
229 memset(&lur, 0, sizeof(lur));
230
231 if (lttng_ust_comm_should_quit) {
232 ret = -EPERM;
233 goto end;
234 }
235
236 ops = objd_ops(lum->handle);
237 if (!ops) {
238 ret = -ENOENT;
239 goto end;
240 }
241
242 switch (lum->cmd) {
243 case LTTNG_UST_REGISTER_DONE:
244 if (lum->handle == LTTNG_UST_ROOT_HANDLE)
245 ret = handle_register_done(sock_info);
246 else
247 ret = -EINVAL;
248 break;
249 case LTTNG_UST_RELEASE:
250 if (lum->handle == LTTNG_UST_ROOT_HANDLE)
251 ret = -EPERM;
252 else
253 ret = objd_unref(lum->handle);
254 break;
255 default:
256 if (ops->cmd)
257 ret = ops->cmd(lum->handle, lum->cmd,
258 (unsigned long) &lum->u);
259 else
260 ret = -ENOSYS;
261 break;
262 }
263
264 end:
265 lur.handle = lum->handle;
266 lur.cmd = lum->cmd;
267 lur.ret_val = ret;
268 if (ret >= 0) {
269 lur.ret_code = LTTCOMM_OK;
270 } else {
271 lur.ret_code = LTTCOMM_SESSION_FAIL;
272 }
273 ret = send_reply(sock, &lur);
274
275 ust_unlock();
276 return ret;
277 }
278
279 static
280 void cleanup_sock_info(struct sock_info *sock_info)
281 {
282 int ret;
283
284 if (sock_info->socket != -1) {
285 ret = close(sock_info->socket);
286 if (ret) {
287 ERR("Error closing apps socket");
288 }
289 sock_info->socket = -1;
290 }
291 if (sock_info->root_handle != -1) {
292 ret = objd_unref(sock_info->root_handle);
293 if (ret) {
294 ERR("Error unref root handle");
295 }
296 sock_info->root_handle = -1;
297 }
298 sock_info->constructor_sem_posted = 0;
299 if (sock_info->wait_shm_mmap) {
300 ret = munmap(sock_info->wait_shm_mmap, sysconf(_SC_PAGE_SIZE));
301 if (ret) {
302 ERR("Error unmapping wait shm");
303 }
304 sock_info->wait_shm_mmap = NULL;
305 }
306 }
307
308 static
309 char *get_map_shm(struct sock_info *sock_info)
310 {
311 size_t mmap_size = sysconf(_SC_PAGE_SIZE);
312 int wait_shm_fd, ret;
313 char *wait_shm_mmap;
314
315 /*
316 * Get existing (read-only) shm, or open new shm.
317 * First try to open read-only.
318 */
319 wait_shm_fd = shm_open(sock_info->wait_shm_path,
320 O_RDONLY, 0700);
321 if (wait_shm_fd >= 0)
322 goto got_shm;
323 /*
324 * Real-only open did not work. If it is because it did
325 * not exist, try creating it. Else it's a failure that
326 * prohibits using shm.
327 */
328 if (errno != ENOENT) {
329 ERR("Error opening shm %s", sock_info->wait_shm_path);
330 goto error;
331 }
332 wait_shm_fd = shm_open(sock_info->wait_shm_path,
333 O_RDWR | O_CREAT | O_EXCL, 0700);
334 if (wait_shm_fd >= 0)
335 goto created_shm;
336 if (errno != EEXIST) {
337 ERR("Error opening shm %s", sock_info->wait_shm_path);
338 goto error;
339 }
340 /*
341 * If another process beat us to create the shm, we are
342 * pretty certain the shm is available for us in
343 * read-only mode.
344 */
345 wait_shm_fd = shm_open(sock_info->wait_shm_path,
346 O_RDWR | O_CREAT | O_EXCL, 0700);
347 if (wait_shm_fd >= 0)
348 goto got_shm;
349 else
350 goto error;
351
352 created_shm:
353 ret = ftruncate(wait_shm_fd, mmap_size);
354 if (ret) {
355 PERROR("ftruncate");
356 ret = close(wait_shm_fd);
357 if (ret) {
358 ERR("Error closing fd");
359 }
360 wait_shm_fd = -1;
361 goto error;
362 }
363 got_shm:
364 wait_shm_mmap = mmap(NULL, mmap_size, PROT_READ,
365 MAP_SHARED, wait_shm_fd, 0);
366 if (wait_shm_mmap == MAP_FAILED) {
367 PERROR("mmap");
368 goto error;
369 }
370 /* close shm fd immediately after taking the mmap reference */
371 ret = close(wait_shm_fd);
372 if (ret) {
373 ERR("Error closing fd");
374 }
375 return wait_shm_mmap;
376
377 error:
378 return NULL;
379 }
380
381 static
382 void wait_for_sessiond(struct sock_info *sock_info)
383 {
384 ust_lock();
385 if (lttng_ust_comm_should_quit) {
386 goto quit;
387 }
388 if (!sock_info->wait_shm_mmap) {
389 sock_info->wait_shm_mmap = get_map_shm(sock_info);
390 if (!sock_info->wait_shm_mmap)
391 goto error;
392 }
393 ust_unlock();
394
395 DBG("Waiting for %s apps sessiond", sock_info->name);
396 /* Wait for futex wakeup TODO */
397 sleep(5);
398
399 return;
400
401 quit:
402 ust_unlock();
403 return;
404
405 error:
406 ust_unlock();
407 /* Error handling: fallback on a 5 seconds sleep. */
408 sleep(5);
409 return;
410 }
411
412 /*
413 * This thread does not allocate any resource, except within
414 * handle_message, within mutex protection. This mutex protects against
415 * fork and exit.
416 * The other moment it allocates resources is at socket connexion, which
417 * is also protected by the mutex.
418 */
419 static
420 void *ust_listener_thread(void *arg)
421 {
422 struct sock_info *sock_info = arg;
423 int sock, ret;
424
425 /* Restart trying to connect to the session daemon */
426 restart:
427 ust_lock();
428
429 if (lttng_ust_comm_should_quit) {
430 ust_unlock();
431 goto quit;
432 }
433
434 if (sock_info->socket != -1) {
435 ret = close(sock_info->socket);
436 if (ret) {
437 ERR("Error closing %s apps socket", sock_info->name);
438 }
439 sock_info->socket = -1;
440 }
441
442 /* Register */
443 ret = lttcomm_connect_unix_sock(sock_info->sock_path);
444 if (ret < 0) {
445 ERR("Error connecting to %s apps socket", sock_info->name);
446 /*
447 * If we cannot find the sessiond daemon, don't delay
448 * constructor execution.
449 */
450 ret = handle_register_done(sock_info);
451 assert(!ret);
452 ust_unlock();
453
454 /* Wait for sessiond availability with pipe */
455 wait_for_sessiond(sock_info);
456 goto restart;
457 }
458
459 sock_info->socket = sock = ret;
460
461 /*
462 * Create only one root handle per listener thread for the whole
463 * process lifetime.
464 */
465 if (sock_info->root_handle == -1) {
466 ret = lttng_abi_create_root_handle();
467 if (ret) {
468 ERR("Error creating root handle");
469 ust_unlock();
470 goto quit;
471 }
472 sock_info->root_handle = ret;
473 }
474
475 ret = register_app_to_sessiond(sock);
476 if (ret < 0) {
477 ERR("Error registering to %s apps socket", sock_info->name);
478 /*
479 * If we cannot register to the sessiond daemon, don't
480 * delay constructor execution.
481 */
482 ret = handle_register_done(sock_info);
483 assert(!ret);
484 ust_unlock();
485 wait_for_sessiond(sock_info);
486 goto restart;
487 }
488 ust_unlock();
489
490 for (;;) {
491 ssize_t len;
492 struct lttcomm_ust_msg lum;
493
494 len = lttcomm_recv_unix_sock(sock, &lum, sizeof(lum));
495 switch (len) {
496 case 0: /* orderly shutdown */
497 DBG("%s ltt-sessiond has performed an orderly shutdown\n", sock_info->name);
498 goto end;
499 case sizeof(lum):
500 DBG("message received\n");
501 ret = handle_message(sock_info, sock, &lum);
502 if (ret < 0) {
503 ERR("Error handling message for %s socket", sock_info->name);
504 }
505 continue;
506 case -1:
507 if (errno == ECONNRESET) {
508 ERR("%s remote end closed connection\n", sock_info->name);
509 goto end;
510 }
511 goto end;
512 default:
513 ERR("incorrect message size (%s socket): %zd\n", sock_info->name, len);
514 continue;
515 }
516
517 }
518 end:
519 goto restart; /* try to reconnect */
520 quit:
521 return NULL;
522 }
523
524 /*
525 * Return values: -1: don't wait. 0: wait forever. 1: timeout wait.
526 */
527 static
528 int get_timeout(struct timespec *constructor_timeout)
529 {
530 long constructor_delay_ms = LTTNG_UST_DEFAULT_CONSTRUCTOR_TIMEOUT_MS;
531 char *str_delay;
532 int ret;
533
534 str_delay = getenv("UST_REGISTER_TIMEOUT");
535 if (str_delay) {
536 constructor_delay_ms = strtol(str_delay, NULL, 10);
537 }
538
539 switch (constructor_delay_ms) {
540 case -1:/* fall-through */
541 case 0:
542 return constructor_delay_ms;
543 default:
544 break;
545 }
546
547 /*
548 * If we are unable to find the current time, don't wait.
549 */
550 ret = clock_gettime(CLOCK_REALTIME, constructor_timeout);
551 if (ret) {
552 return -1;
553 }
554 constructor_timeout->tv_sec += constructor_delay_ms / 1000UL;
555 constructor_timeout->tv_nsec +=
556 (constructor_delay_ms % 1000UL) * 1000000UL;
557 if (constructor_timeout->tv_nsec >= 1000000000UL) {
558 constructor_timeout->tv_sec++;
559 constructor_timeout->tv_nsec -= 1000000000UL;
560 }
561 return 1;
562 }
563
564 /*
565 * sessiond monitoring thread: monitor presence of global and per-user
566 * sessiond by polling the application common named pipe.
567 */
568 /* TODO */
569
570 void __attribute__((constructor)) lttng_ust_init(void)
571 {
572 struct timespec constructor_timeout;
573 int timeout_mode;
574 int ret;
575
576 if (uatomic_xchg(&initialized, 1) == 1)
577 return;
578
579 /*
580 * We want precise control over the order in which we construct
581 * our sub-libraries vs starting to receive commands from
582 * sessiond (otherwise leading to errors when trying to create
583 * sessiond before the init functions are completed).
584 */
585 init_usterr();
586 init_tracepoint();
587 ltt_ring_buffer_metadata_client_init();
588 ltt_ring_buffer_client_overwrite_init();
589 ltt_ring_buffer_client_discard_init();
590
591 timeout_mode = get_timeout(&constructor_timeout);
592
593 ret = sem_init(&constructor_wait, 0, 0);
594 assert(!ret);
595
596 ret = setup_local_apps();
597 if (ret) {
598 ERR("Error setting up to local apps");
599 }
600 ret = pthread_create(&local_apps.ust_listener, NULL,
601 ust_listener_thread, &local_apps);
602
603 if (local_apps.allowed) {
604 ret = pthread_create(&global_apps.ust_listener, NULL,
605 ust_listener_thread, &global_apps);
606 } else {
607 handle_register_done(&local_apps);
608 }
609
610 switch (timeout_mode) {
611 case 1: /* timeout wait */
612 do {
613 ret = sem_timedwait(&constructor_wait,
614 &constructor_timeout);
615 } while (ret < 0 && errno == EINTR);
616 if (ret < 0 && errno == ETIMEDOUT) {
617 ERR("Timed out waiting for ltt-sessiond");
618 } else {
619 assert(!ret);
620 }
621 break;
622 case -1:/* wait forever */
623 do {
624 ret = sem_wait(&constructor_wait);
625 } while (ret < 0 && errno == EINTR);
626 assert(!ret);
627 break;
628 case 0: /* no timeout */
629 break;
630 }
631 }
632
633 static
634 void lttng_ust_cleanup(int exiting)
635 {
636 cleanup_sock_info(&global_apps);
637 if (local_apps.allowed) {
638 cleanup_sock_info(&local_apps);
639 }
640 lttng_ust_abi_exit();
641 ltt_events_exit();
642 ltt_ring_buffer_client_discard_exit();
643 ltt_ring_buffer_client_overwrite_exit();
644 ltt_ring_buffer_metadata_client_exit();
645 exit_tracepoint();
646 if (!exiting) {
647 /* Reinitialize values for fork */
648 sem_count = 2;
649 lttng_ust_comm_should_quit = 0;
650 initialized = 0;
651 }
652 }
653
654 void __attribute__((destructor)) lttng_ust_exit(void)
655 {
656 int ret;
657
658 /*
659 * Using pthread_cancel here because:
660 * A) we don't want to hang application teardown.
661 * B) the thread is not allocating any resource.
662 */
663
664 /*
665 * Require the communication thread to quit. Synchronize with
666 * mutexes to ensure it is not in a mutex critical section when
667 * pthread_cancel is later called.
668 */
669 ust_lock();
670 lttng_ust_comm_should_quit = 1;
671 ust_unlock();
672
673 ret = pthread_cancel(global_apps.ust_listener);
674 if (ret) {
675 ERR("Error cancelling global ust listener thread");
676 }
677 if (local_apps.allowed) {
678 ret = pthread_cancel(local_apps.ust_listener);
679 if (ret) {
680 ERR("Error cancelling local ust listener thread");
681 }
682 }
683 lttng_ust_cleanup(1);
684 }
685
686 /*
687 * We exclude the worker threads across fork and clone (except
688 * CLONE_VM), because these system calls only keep the forking thread
689 * running in the child. Therefore, we don't want to call fork or clone
690 * in the middle of an tracepoint or ust tracing state modification.
691 * Holding this mutex protects these structures across fork and clone.
692 */
693 void ust_before_fork(ust_fork_info_t *fork_info)
694 {
695 /*
696 * Disable signals. This is to avoid that the child intervenes
697 * before it is properly setup for tracing. It is safer to
698 * disable all signals, because then we know we are not breaking
699 * anything by restoring the original mask.
700 */
701 sigset_t all_sigs;
702 int ret;
703
704 /* Disable signals */
705 sigfillset(&all_sigs);
706 ret = sigprocmask(SIG_BLOCK, &all_sigs, &fork_info->orig_sigs);
707 if (ret == -1) {
708 PERROR("sigprocmask");
709 }
710 ust_lock();
711 rcu_bp_before_fork();
712 }
713
714 static void ust_after_fork_common(ust_fork_info_t *fork_info)
715 {
716 int ret;
717
718 DBG("process %d", getpid());
719 ust_unlock();
720 /* Restore signals */
721 ret = sigprocmask(SIG_SETMASK, &fork_info->orig_sigs, NULL);
722 if (ret == -1) {
723 PERROR("sigprocmask");
724 }
725 }
726
727 void ust_after_fork_parent(ust_fork_info_t *fork_info)
728 {
729 DBG("process %d", getpid());
730 rcu_bp_after_fork_parent();
731 /* Release mutexes and reenable signals */
732 ust_after_fork_common(fork_info);
733 }
734
735 /*
736 * After fork, in the child, we need to cleanup all the leftover state,
737 * except the worker thread which already magically disappeared thanks
738 * to the weird Linux fork semantics. After tyding up, we call
739 * lttng_ust_init() again to start over as a new PID.
740 *
741 * This is meant for forks() that have tracing in the child between the
742 * fork and following exec call (if there is any).
743 */
744 void ust_after_fork_child(ust_fork_info_t *fork_info)
745 {
746 DBG("process %d", getpid());
747 /* Release urcu mutexes */
748 rcu_bp_after_fork_child();
749 lttng_ust_cleanup(0);
750 /* Release mutexes and reenable signals */
751 ust_after_fork_common(fork_info);
752 lttng_ust_init();
753 }
This page took 0.04378 seconds and 4 git commands to generate.