]> granicus.if.org Git - apache/blob - modules/examples/mod_example_ipc.c
ef39cd7b61bc809ccea5a2eb3ef35284e84a5a3f
[apache] / modules / examples / mod_example_ipc.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /* 
18  *  mod_example_ipc -- Apache sample module 
19  * 
20  * This module illustrates the use in an Apache 2.x module of the Interprocess
21  * Communications routines that come with APR. It is example code, and not meant 
22  * to be used in a production server. 
23  *
24  * To play with this sample module first compile it into a DSO file and install
25  * it into Apache's modules directory by running:
26  *
27  *    $ /path/to/apache2/bin/apxs -c -i mod_example_ipc.c
28  *
29  * Then activate it in Apache's httpd.conf file for instance for the URL
30  * /example_ipc in as follows:
31  *
32  *    #   httpd.conf
33  *    LoadModule example_ipc_module modules/mod_example_ipc.so
34  *    <Location /example_ipc>
35  *    SetHandler example_ipc
36  *    </Location>
37  *
38  * Then restart Apache via
39  *
40  *    $ /path/to/apache2/bin/apachectl restart
41  *
42  * The module allocates a counter in shared memory, which is incremented by the
43  * request handler under a mutex. After installation, activate the handler by
44  * hitting the URL configured above with ab at various concurrency levels to see
45  * how mutex contention affects server performance. 
46  */ 
47
48 #include "apr.h"
49 #include "apr_strings.h"
50
51 #include "httpd.h"
52 #include "http_config.h"
53 #include "http_log.h"
54 #include "http_protocol.h"
55 #include "util_mutex.h"
56 #include "ap_config.h"
57
58 #if APR_HAVE_SYS_TYPES_H
59 #include <sys/types.h>
60 #endif
61 #if APR_HAVE_UNISTD_H
62 #include <unistd.h>
63 #endif
64
65 #define HTML_HEADER "<html>\n<head>\n<title>Mod_example_IPC Status Page " \
66                     "</title>\n</head>\n<body>\n<h1>Mod_example_IPC Status</h1>\n"
67 #define HTML_FOOTER "</body>\n</html>\n"
68
69 /* Number of microseconds to camp out on the mutex */
70 #define CAMPOUT 10
71 /* Maximum number of times we camp out before giving up */
72 #define MAXCAMP 10
73 /* Number of microseconds the handler sits on the lock once acquired. */
74 #define SLEEPYTIME 1000
75
76 apr_shm_t *exipc_shm; /* Pointer to shared memory block */
77 char *shmfilename; /* Shared memory file name, used on some systems */
78 apr_global_mutex_t *exipc_mutex; /* Lock around shared memory segment access */
79 static const char *exipc_mutex_type = "example-ipc-shm";
80
81 /* Data structure for shared memory block */
82 typedef struct exipc_data {
83     apr_uint64_t counter; 
84     /* More fields if necessary */
85 } exipc_data;
86
87 /* 
88  * Clean up the shared memory block. This function is registered as 
89  * cleanup function for the configuration pool, which gets called
90  * on restarts. It assures that the new children will not talk to a stale 
91  * shared memory segment. 
92  */
93 static apr_status_t shm_cleanup_wrapper(void *unused) {
94     if (exipc_shm)
95         return apr_shm_destroy(exipc_shm);
96     return OK;
97 }
98
99 /*
100  * This routine is called in the parent; we must register our
101  * mutex type before the config is processed so that users can
102  * adjust the mutex settings using the Mutex directive.
103  */
104
105 static int exipc_pre_config(apr_pool_t *pconf, apr_pool_t *plog, 
106                             apr_pool_t *ptemp)
107 {
108     ap_mutex_register(pconf, exipc_mutex_type, NULL, APR_LOCK_DEFAULT, 0);
109     return OK;
110 }
111
112 /* 
113  * This routine is called in the parent, so we'll set up the shared
114  * memory segment and mutex here. 
115  */
116
117 static int exipc_post_config(apr_pool_t *pconf, apr_pool_t *plog, 
118                              apr_pool_t *ptemp, server_rec *s)
119 {
120     void *data; /* These two help ensure that we only init once. */
121     const char *userdata_key;
122     apr_status_t rs;
123     exipc_data *base;
124     const char *tempdir; 
125
126
127     /* 
128      * The following checks if this routine has been called before. 
129      * This is necessary because the parent process gets initialized
130      * a couple of times as the server starts up, and we don't want 
131      * to create any more mutexes and shared memory segments than
132      * we're actually going to use. 
133      * 
134      * The key needs to be unique for the entire web server, so put
135      * the module name in it.
136      */ 
137     userdata_key = "example_ipc_init_module";
138     apr_pool_userdata_get(&data, userdata_key, s->process->pool);
139     if (!data) {
140         /* 
141          * If no data was found for our key, this must be the first
142          * time the module is initialized. Put some data under that
143          * key and return.
144          */
145         apr_pool_userdata_set((const void *) 1, userdata_key, 
146                               apr_pool_cleanup_null, s->process->pool);
147         return OK;
148     } /* Kilroy was here */
149
150     /* 
151      * The shared memory allocation routines take a file name.
152      * Depending on system-specific implementation of these
153      * routines, that file may or may not actually be created. We'd
154      * like to store those files in the operating system's designated
155      * temporary directory, which APR can point us to.
156      */
157     rs = apr_temp_dir_get(&tempdir, pconf);
158     if (APR_SUCCESS != rs) {
159         ap_log_error(APLOG_MARK, APLOG_ERR, rs, s, 
160                      "Failed to find temporary directory");
161         return HTTP_INTERNAL_SERVER_ERROR;
162     }
163
164     /* Create the shared memory segment */
165
166     /* 
167      * Create a unique filename using our pid. This information is 
168      * stashed in the global variable so the children inherit it.
169      */
170     shmfilename = apr_psprintf(pconf, "%s/httpd_shm.%ld", tempdir, 
171                                (long int)getpid());
172
173     /* Now create that segment */
174     rs = apr_shm_create(&exipc_shm, sizeof(exipc_data), 
175                         (const char *) shmfilename, pconf);
176     if (APR_SUCCESS != rs) {
177         ap_log_error(APLOG_MARK, APLOG_ERR, rs, s, 
178                      "Failed to create shared memory segment on file %s", 
179                      shmfilename);
180         return HTTP_INTERNAL_SERVER_ERROR;
181     }
182
183     /* Created it, now let's zero it out */
184     base = (exipc_data *)apr_shm_baseaddr_get(exipc_shm);
185     base->counter = 0;
186
187     /* Create global mutex */
188
189     rs = ap_global_mutex_create(&exipc_mutex, NULL, exipc_mutex_type, NULL,
190                                 s, pconf, 0);
191     if (APR_SUCCESS != rs) {
192         return HTTP_INTERNAL_SERVER_ERROR;
193     }
194
195     /* 
196      * Destroy the shm segment when the configuration pool gets destroyed. This
197      * happens on server restarts. The parent will then (above) allocate a new
198      * shm segment that the new children will bind to. 
199      */
200     apr_pool_cleanup_register(pconf, NULL, shm_cleanup_wrapper, 
201                               apr_pool_cleanup_null);    
202     return OK;
203 }
204
205 /* 
206  * This routine gets called when a child inits. We use it to attach
207  * to the shared memory segment, and reinitialize the mutex.
208  */
209
210 static void exipc_child_init(apr_pool_t *p, server_rec *s)
211 {
212     apr_status_t rs;
213          
214     /* 
215      * Re-open the mutex for the child. Note we're reusing
216      * the mutex pointer global here. 
217      */
218     rs = apr_global_mutex_child_init(&exipc_mutex, 
219                                      apr_global_mutex_lockfile(exipc_mutex),
220                                      p);
221     if (APR_SUCCESS != rs) {
222         ap_log_error(APLOG_MARK, APLOG_CRIT, rs, s, 
223                      "Failed to reopen mutex %s in child", 
224                      exipc_mutex_type);
225         /* There's really nothing else we can do here, since This
226          * routine doesn't return a status. If this ever goes wrong,
227          * it will turn Apache into a fork bomb. Let's hope it never
228          * will.
229          */
230         exit(1); /* Ugly, but what else? */
231     } 
232 }
233
234 /* The sample content handler */
235 static int exipc_handler(request_rec *r)
236 {
237     int gotlock = 0;
238     int camped;
239     apr_time_t startcamp;
240     apr_int64_t timecamped;
241     apr_status_t rs; 
242     exipc_data *base;
243     
244     if (strcmp(r->handler, "example_ipc")) {
245         return DECLINED;
246     }
247     
248     /* 
249      * The main function of the handler, aside from sending the 
250      * status page to the client, is to increment the counter in 
251      * the shared memory segment. This action needs to be mutexed 
252      * out using the global mutex. 
253      */
254      
255     /* 
256      * First, acquire the lock. This code is a lot more involved than
257      * it usually needs to be, because the process based trylock
258      * routine is not implemented on unix platforms. I left it in to
259      * show how it would work if trylock worked, and for situations
260      * and platforms where trylock works.
261      */
262     for (camped = 0, timecamped = 0; camped < MAXCAMP; camped++) {
263         rs = apr_global_mutex_trylock(exipc_mutex); 
264         if (APR_STATUS_IS_EBUSY(rs)) {
265             apr_sleep(CAMPOUT);
266         } else if (APR_SUCCESS == rs) {
267             gotlock = 1; 
268             break; /* Get out of the loop */
269         } else if (APR_STATUS_IS_ENOTIMPL(rs)) {
270             /* If it's not implemented, just hang in the mutex. */
271             startcamp = apr_time_now();
272             rs = apr_global_mutex_lock(exipc_mutex);
273             timecamped = (apr_int64_t) (apr_time_now() - startcamp);
274             if (APR_SUCCESS == rs) {
275                 gotlock = 1;
276                 break; /* Out of the loop */
277             } else {
278                 /* Some error, log and bail */
279                 ap_log_error(APLOG_MARK, APLOG_ERR, rs, r->server, 
280                              "Child %ld failed to acquire lock", 
281                              (long int)getpid());
282                 break; /* Out of the loop without having the lock */
283             }                
284         } else {
285             /* Some other error, log and bail */
286             ap_log_error(APLOG_MARK, APLOG_ERR, rs, r->server, 
287                          "Child %ld failed to try and acquire lock", 
288                          (long int)getpid());
289             break; /* Out of the loop without having the lock */
290             
291         }
292         /* 
293          * The only way to get to this point is if the trylock worked
294          * and returned BUSY. So, bump the time and try again
295          */
296         timecamped += CAMPOUT;
297         ap_log_error(APLOG_MARK, APLOG_NOERRNO | APLOG_NOTICE, 
298                      0, r->server, "Child %ld camping out on mutex for %" APR_INT64_T_FMT
299                      " microseconds",
300                      (long int) getpid(), timecamped);
301     } /* Lock acquisition loop */
302     
303     /* Sleep for a millisecond to make it a little harder for
304      * httpd children to acquire the lock. 
305      */
306     apr_sleep(SLEEPYTIME);
307     
308     r->content_type = "text/html";      
309
310     if (!r->header_only) {
311         ap_rputs(HTML_HEADER, r);
312         if (gotlock) {
313             /* Increment the counter */
314             base = (exipc_data *)apr_shm_baseaddr_get(exipc_shm);
315             base->counter++;
316             /* Send a page with our pid and the new value of the counter. */
317             ap_rprintf(r, "<p>Lock acquired after %ld microseoncds.</p>\n", 
318                        (long int) timecamped); 
319             ap_rputs("<table border=\"1\">\n", r);
320             ap_rprintf(r, "<tr><td>Child pid:</td><td>%d</td></tr>\n", 
321                        (int) getpid());
322             ap_rprintf(r, "<tr><td>Counter:</td><td>%u</td></tr>\n", 
323                        (unsigned int)base->counter);
324             ap_rputs("</table>\n", r);
325         } else {
326             /* 
327              * Send a page saying that we couldn't get the lock. Don't say
328              * what the counter is, because without the lock the value could
329              * race. 
330              */
331             ap_rprintf(r, "<p>Child %d failed to acquire lock "
332                        "after camping out for %d microseconds.</p>\n", 
333                        (int) getpid(), (int) timecamped);
334         }
335         ap_rputs(HTML_FOOTER, r); 
336     } /* r->header_only */
337     
338     /* Release the lock */
339     if (gotlock)
340         rs = apr_global_mutex_unlock(exipc_mutex); 
341     /* Swallowing the result because what are we going to do with it at 
342      * this stage? 
343      */
344
345     return OK;
346 }
347
348 static void exipc_register_hooks(apr_pool_t *p)
349 {
350     ap_hook_pre_config(exipc_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
351     ap_hook_post_config(exipc_post_config, NULL, NULL, APR_HOOK_MIDDLE); 
352     ap_hook_child_init(exipc_child_init, NULL, NULL, APR_HOOK_MIDDLE); 
353     ap_hook_handler(exipc_handler, NULL, NULL, APR_HOOK_MIDDLE);
354 }
355
356 /* Dispatch list for API hooks */
357 AP_DECLARE_MODULE(example_ipc) = {
358     STANDARD20_MODULE_STUFF, 
359     NULL,                  /* create per-dir    config structures */
360     NULL,                  /* merge  per-dir    config structures */
361     NULL,                  /* create per-server config structures */
362     NULL,                  /* merge  per-server config structures */
363     NULL,                  /* table of config file commands       */
364     exipc_register_hooks   /* register hooks                      */
365 };
366