[libmultipath] move the async logger in libmultipath
[multipath-tools/.git] / libmultipath / log_pthread.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <stdarg.h>
4 #include <pthread.h>
5 #include <sys/mman.h>
6
7 #include <memory.h>
8
9 #include "log_pthread.h"
10 #include "log.h"
11
12 void log_safe (int prio, char * fmt, va_list ap)
13 {
14         pthread_mutex_lock(logq_lock);
15         //va_start(ap, fmt);
16         log_enqueue(prio, fmt, ap);
17         va_end(ap);
18         pthread_mutex_unlock(logq_lock);
19
20         pthread_mutex_lock(logev_lock);
21         pthread_cond_signal(logev_cond);
22         pthread_mutex_unlock(logev_lock);
23 }
24
25 static void flush_logqueue (void)
26 {
27         int empty;
28
29         do {
30                 pthread_mutex_lock(logq_lock);
31                 empty = log_dequeue(la->buff);
32                 pthread_mutex_unlock(logq_lock);
33                 log_syslog(la->buff);
34         } while (empty == 0);
35 }
36
37 static void * log_thread (void * et)
38 {
39         mlockall(MCL_CURRENT | MCL_FUTURE);
40         logdbg(stderr,"enter log_thread\n");
41
42         while (1) {
43                 pthread_mutex_lock(logev_lock);
44                 pthread_cond_wait(logev_cond, logev_lock);
45                 pthread_mutex_unlock(logev_lock);
46
47                 flush_logqueue();
48         }
49 }
50
51 void log_thread_start (void)
52 {
53         pthread_attr_t attr;
54         
55         logdbg(stderr,"enter log_thread_start\n");
56
57         logq_lock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t));
58         logev_lock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t));
59         logev_cond = (pthread_cond_t *) malloc(sizeof(pthread_cond_t));
60         
61         pthread_mutex_init(logq_lock, NULL);
62         pthread_mutex_init(logev_lock, NULL);
63         pthread_cond_init(logev_cond, NULL);
64         
65         pthread_attr_init(&attr);
66         pthread_attr_setstacksize(&attr, 64 * 1024);
67
68         if (log_init("multipathd", 0)) {
69                 fprintf(stderr,"can't initialize log buffer\n");
70                 exit(1);
71         }
72         pthread_create(&log_thr, &attr, log_thread, NULL);
73
74         return;
75 }
76
77 void log_thread_stop (void)
78 {
79         logdbg(stderr,"enter log_thread_stop\n");
80
81         pthread_mutex_lock(logq_lock);
82         pthread_cancel(log_thr);
83         pthread_mutex_unlock(logq_lock);
84
85         flush_logqueue();
86
87         pthread_mutex_destroy(logq_lock);
88         pthread_mutex_destroy(logev_lock);
89         pthread_cond_destroy(logev_cond);
90
91         free_logarea();
92 }