bea9665c3c5eba17ec14aa8af7fd6e16f59c431d
[citadel.git] / citadel / threads.c
1 /*
2  * Thread handling stuff for Citadel server
3  *
4  * Copyright (c) 1987-2011 by the citadel.org team
5  *
6  * This program is open source software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License, version 3.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14
15 #include <stdlib.h>
16 #include <unistd.h>
17 #include <stdio.h>
18 #include <sys/types.h>
19 #include <errno.h>
20 #include <sys/socket.h>
21 #include <unistd.h>
22 #include <fcntl.h>
23 #include <signal.h>
24 #include <syslog.h>
25
26 #include "sysdep.h"
27 #if TIME_WITH_SYS_TIME
28 # include <sys/time.h>
29 # include <time.h>
30 #else
31 # if HAVE_SYS_TIME_H
32 #  include <sys/time.h>
33 # else
34 #  include <time.h>
35 # endif
36 #endif
37
38 #ifdef HAVE_SYSCALL_H
39 # include <syscall.h>
40 #else 
41 # if HAVE_SYS_SYSCALL_H
42 #  include <sys/syscall.h>
43 # endif
44 #endif
45
46 #include <libcitadel.h>
47
48 #include "threads.h"
49 #include "ctdl_module.h"
50 #include "modules_init.h"
51 #include "housekeeping.h"
52 #include "config.h"
53 #include "citserver.h"
54 #include "sysdep_decls.h"
55 #include "context.h"
56 #include "event_client.h"
57
58
59 int num_workers = 0;                            /* Current number of worker threads */
60 int active_workers = 0;                         /* Number of ACTIVE worker threads */
61 pthread_key_t ThreadKey;
62 pthread_mutex_t Critters[MAX_SEMAPHORES];       /* Things needing locking */
63 struct thread_tsd masterTSD;
64 int server_shutting_down = 0;                   /* set to nonzero during shutdown */
65
66 pthread_mutex_t ThreadCountMutex;;
67
68
69 void InitializeSemaphores(void)
70 {
71         int i;
72
73         /* Set up a bunch of semaphores to be used for critical sections */
74         for (i=0; i<MAX_SEMAPHORES; ++i) {
75                 pthread_mutex_init(&Critters[i], NULL);
76         }
77 }
78
79
80
81
82 /*
83  * Obtain a semaphore lock to begin a critical section.
84  * but only if no one else has one
85  */
86 int try_critical_section(int which_one)
87 {
88         /* For all types of critical sections except those listed here,
89          * ensure nobody ever tries to do a critical section within a
90          * transaction; this could lead to deadlock.
91          */
92         if (    (which_one != S_FLOORCACHE)
93                 && (which_one != S_RPLIST)
94         ) {
95                 cdb_check_handles();
96         }
97         return (pthread_mutex_trylock(&Critters[which_one]));
98 }
99
100
101 /*
102  * Obtain a semaphore lock to begin a critical section.
103  */
104 void begin_critical_section(int which_one)
105 {
106         /* For all types of critical sections except those listed here,
107          * ensure nobody ever tries to do a critical section within a
108          * transaction; this could lead to deadlock.
109          */
110         if (    (which_one != S_FLOORCACHE)
111                 && (which_one != S_RPLIST)
112         ) {
113                 cdb_check_handles();
114         }
115         pthread_mutex_lock(&Critters[which_one]);
116 }
117
118 /*
119  * Release a semaphore lock to end a critical section.
120  */
121 void end_critical_section(int which_one)
122 {
123         pthread_mutex_unlock(&Critters[which_one]);
124 }
125
126
127
128
129 /*
130  * Return a pointer to our thread-specific (not session-specific) data.
131  */ 
132 struct thread_tsd *MyThread(void) {
133         register struct thread_tsd *c;
134         return ((c = (struct thread_tsd *) pthread_getspecific(ThreadKey), c == NULL) ? &masterTSD : c);
135 }
136
137
138
139 /* 
140  * Called by CtdlThreadCreate()
141  * We have to pass through here before starting our thread in order to create a set of data
142  * that is thread-specific rather than session-specific.
143  */
144 void *CTC_backend(void *supplied_start_routine)
145 {
146         struct thread_tsd *mytsd;
147         void *(*start_routine)(void*) = supplied_start_routine;
148
149         mytsd = (struct thread_tsd *) malloc(sizeof(struct thread_tsd));
150         memset(mytsd, 0, sizeof(struct thread_tsd));
151         pthread_setspecific(ThreadKey, (const void *) mytsd);
152
153         start_routine(NULL);
154
155         free(mytsd);
156         return(NULL);
157 }
158
159  
160 /*
161  * Function to create a thread.
162  */ 
163 void CtdlThreadCreate(void *(*start_routine)(void*))
164 {
165         pthread_t thread;
166         pthread_attr_t attr;
167         int ret = 0;
168
169
170         ret = pthread_attr_init(&attr);
171         ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE);
172         ret = pthread_create(&thread, &attr, CTC_backend, (void *)start_routine);
173         if (ret != 0) syslog(LOG_EMERG, "pthread_create() : %s", strerror(errno));
174 }
175
176
177 void InitializeMasterTSD(void) {
178         memset(&masterTSD, 0, sizeof(struct thread_tsd));
179 }
180
181 extern void ShutDownEventQueues(void);
182
183 int EventQShuttingDown = 0;
184 int EVQShutDown = 0;
185 /*
186  * Initialize the thread system
187  */
188 void go_threading(void)
189 {
190         if (pthread_key_create(&ThreadKey, NULL) != 0) {
191                 syslog(LOG_EMERG, "pthread_key_create() : %s", strerror(errno));
192                 abort();
193         }
194
195         pthread_mutex_init(&ThreadCountMutex, NULL);
196
197         /* Second call to module init functions now that threading is up */
198         initialise_modules(1);
199
200         /* Begin with one worker thread.  We will expand the pool if necessary */
201         CtdlThreadCreate(worker_thread);
202
203         /* The supervisor thread monitors worker threads and spawns more of them if it finds that
204          * they are all in use.
205          */
206         while (!server_shutting_down) {
207                 if ((active_workers == num_workers) && (num_workers < config.c_max_workers)) {
208                         CtdlThreadCreate(worker_thread);
209                 }
210                 usleep(1000000);
211         }
212
213         /* When we get to this point we are getting ready to shut down our Citadel server */
214         if (!EventQShuttingDown)
215         {
216                 EventQShuttingDown = 1;
217                 ShutDownEventQueues();
218         }
219         while (!EVQShutDown)
220                 usleep(1000000);
221
222
223         terminate_all_sessions();               /* close all client sockets */
224         CtdlShutdownServiceHooks();             /* close all listener sockets to prevent new connections */
225         PerformSessionHooks(EVT_SHUTDOWN);      /* run any registered shutdown hooks */
226
227         int countdown = 30;
228         while ( (num_workers > 0) && (countdown-- > 0)) {
229                 syslog(LOG_DEBUG, "Waiting %d seconds for %d worker threads to exit",
230                         countdown, num_workers
231                 );
232                 usleep(1000000);
233         }
234 }