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