]> granicus.if.org Git - apache/blob - modules/examples/mod_example_ipc.c
mod_ssl: Ensure that the SSL close notify alert is flushed to the client.
[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_core.h"
54 #include "http_log.h"
55 #include "http_protocol.h"
56 #include "util_mutex.h"
57 #include "ap_config.h"
58
59 #if APR_HAVE_SYS_TYPES_H
60 #include <sys/types.h>
61 #endif
62 #if APR_HAVE_UNISTD_H
63 #include <unistd.h>
64 #endif
65
66 #define HTML_HEADER "<html>\n<head>\n<title>Mod_example_IPC Status Page " \
67                     "</title>\n</head>\n<body>\n<h1>Mod_example_IPC Status</h1>\n"
68 #define HTML_FOOTER "</body>\n</html>\n"
69
70 /* Number of microseconds to camp out on the mutex */
71 #define CAMPOUT 10
72 /* Maximum number of times we camp out before giving up */
73 #define MAXCAMP 10
74 /* Number of microseconds the handler sits on the lock once acquired. */
75 #define SLEEPYTIME 1000
76
77 apr_shm_t *exipc_shm; /* Pointer to shared memory block */
78 char *shmfilename; /* Shared memory file name, used on some systems */
79 apr_global_mutex_t *exipc_mutex; /* Lock around shared memory segment access */
80 static const char *exipc_mutex_type = "example-ipc-shm";
81
82 /* Data structure for shared memory block */
83 typedef struct exipc_data {
84     apr_uint64_t counter;
85     /* More fields if necessary */
86 } exipc_data;
87
88 /*
89  * Clean up the shared memory block. This function is registered as
90  * cleanup function for the configuration pool, which gets called
91  * on restarts. It assures that the new children will not talk to a stale
92  * shared memory segment.
93  */
94 static apr_status_t shm_cleanup_wrapper(void *unused) {
95     if (exipc_shm)
96         return apr_shm_destroy(exipc_shm);
97     return OK;
98 }
99
100 /*
101  * This routine is called in the parent; we must register our
102  * mutex type before the config is processed so that users can
103  * adjust the mutex settings using the Mutex directive.
104  */
105
106 static int exipc_pre_config(apr_pool_t *pconf, apr_pool_t *plog,
107                             apr_pool_t *ptemp)
108 {
109     ap_mutex_register(pconf, exipc_mutex_type, NULL, APR_LOCK_DEFAULT, 0);
110     return OK;
111 }
112
113 /*
114  * This routine is called in the parent, so we'll set up the shared
115  * memory segment and mutex here.
116  */
117
118 static int exipc_post_config(apr_pool_t *pconf, apr_pool_t *plog,
119                              apr_pool_t *ptemp, server_rec *s)
120 {
121     apr_status_t rs;
122     exipc_data *base;
123     const char *tempdir;
124
125
126     /*
127      * Do nothing if we are not creating the final configuration.
128      * The parent process gets initialized a couple of times as the
129      * server starts up, and we don't want to create any more mutexes
130      * and shared memory segments than we're actually going to use.
131      */
132     if (ap_state_query(AP_SQ_MAIN_STATE) == AP_SQ_MS_CREATE_PRE_CONFIG)
133         return OK;
134
135     /*
136      * The shared memory allocation routines take a file name.
137      * Depending on system-specific implementation of these
138      * routines, that file may or may not actually be created. We'd
139      * like to store those files in the operating system's designated
140      * temporary directory, which APR can point us to.
141      */
142     rs = apr_temp_dir_get(&tempdir, pconf);
143     if (APR_SUCCESS != rs) {
144         ap_log_error(APLOG_MARK, APLOG_ERR, rs, s,
145                      "Failed to find temporary directory");
146         return HTTP_INTERNAL_SERVER_ERROR;
147     }
148
149     /* Create the shared memory segment */
150
151     /*
152      * Create a unique filename using our pid. This information is
153      * stashed in the global variable so the children inherit it.
154      */
155     shmfilename = apr_psprintf(pconf, "%s/httpd_shm.%ld", tempdir,
156                                (long int)getpid());
157
158     /* Now create that segment */
159     rs = apr_shm_create(&exipc_shm, sizeof(exipc_data),
160                         (const char *) shmfilename, pconf);
161     if (APR_SUCCESS != rs) {
162         ap_log_error(APLOG_MARK, APLOG_ERR, rs, s,
163                      "Failed to create shared memory segment on file %s",
164                      shmfilename);
165         return HTTP_INTERNAL_SERVER_ERROR;
166     }
167
168     /* Created it, now let's zero it out */
169     base = (exipc_data *)apr_shm_baseaddr_get(exipc_shm);
170     base->counter = 0;
171
172     /* Create global mutex */
173
174     rs = ap_global_mutex_create(&exipc_mutex, NULL, exipc_mutex_type, NULL,
175                                 s, pconf, 0);
176     if (APR_SUCCESS != rs) {
177         return HTTP_INTERNAL_SERVER_ERROR;
178     }
179
180     /*
181      * Destroy the shm segment when the configuration pool gets destroyed. This
182      * happens on server restarts. The parent will then (above) allocate a new
183      * shm segment that the new children will bind to.
184      */
185     apr_pool_cleanup_register(pconf, NULL, shm_cleanup_wrapper,
186                               apr_pool_cleanup_null);
187     return OK;
188 }
189
190 /*
191  * This routine gets called when a child inits. We use it to attach
192  * to the shared memory segment, and reinitialize the mutex.
193  */
194
195 static void exipc_child_init(apr_pool_t *p, server_rec *s)
196 {
197     apr_status_t rs;
198
199     /*
200      * Re-open the mutex for the child. Note we're reusing
201      * the mutex pointer global here.
202      */
203     rs = apr_global_mutex_child_init(&exipc_mutex,
204                                      apr_global_mutex_lockfile(exipc_mutex),
205                                      p);
206     if (APR_SUCCESS != rs) {
207         ap_log_error(APLOG_MARK, APLOG_CRIT, rs, s,
208                      "Failed to reopen mutex %s in child",
209                      exipc_mutex_type);
210         /* There's really nothing else we can do here, since This
211          * routine doesn't return a status. If this ever goes wrong,
212          * it will turn Apache into a fork bomb. Let's hope it never
213          * will.
214          */
215         exit(1); /* Ugly, but what else? */
216     }
217 }
218
219 /* The sample content handler */
220 static int exipc_handler(request_rec *r)
221 {
222     int gotlock = 0;
223     int camped;
224     apr_time_t startcamp;
225     apr_int64_t timecamped;
226     apr_status_t rs;
227     exipc_data *base;
228
229     if (strcmp(r->handler, "example_ipc")) {
230         return DECLINED;
231     }
232
233     /*
234      * The main function of the handler, aside from sending the
235      * status page to the client, is to increment the counter in
236      * the shared memory segment. This action needs to be mutexed
237      * out using the global mutex.
238      */
239
240     /*
241      * First, acquire the lock. This code is a lot more involved than
242      * it usually needs to be, because the process based trylock
243      * routine is not implemented on unix platforms. I left it in to
244      * show how it would work if trylock worked, and for situations
245      * and platforms where trylock works.
246      */
247     for (camped = 0, timecamped = 0; camped < MAXCAMP; camped++) {
248         rs = apr_global_mutex_trylock(exipc_mutex);
249         if (APR_STATUS_IS_EBUSY(rs)) {
250             apr_sleep(CAMPOUT);
251         } else if (APR_SUCCESS == rs) {
252             gotlock = 1;
253             break; /* Get out of the loop */
254         } else if (APR_STATUS_IS_ENOTIMPL(rs)) {
255             /* If it's not implemented, just hang in the mutex. */
256             startcamp = apr_time_now();
257             rs = apr_global_mutex_lock(exipc_mutex);
258             timecamped = (apr_int64_t) (apr_time_now() - startcamp);
259             if (APR_SUCCESS == rs) {
260                 gotlock = 1;
261                 break; /* Out of the loop */
262             } else {
263                 /* Some error, log and bail */
264                 ap_log_error(APLOG_MARK, APLOG_ERR, rs, r->server,
265                              "Child %ld failed to acquire lock",
266                              (long int)getpid());
267                 break; /* Out of the loop without having the lock */
268             }
269         } else {
270             /* Some other error, log and bail */
271             ap_log_error(APLOG_MARK, APLOG_ERR, rs, r->server,
272                          "Child %ld failed to try and acquire lock",
273                          (long int)getpid());
274             break; /* Out of the loop without having the lock */
275
276         }
277         /*
278          * The only way to get to this point is if the trylock worked
279          * and returned BUSY. So, bump the time and try again
280          */
281         timecamped += CAMPOUT;
282         ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, r->server,
283                      "Child %ld camping out on mutex for %" APR_INT64_T_FMT
284                      " microseconds",
285                      (long int) getpid(), timecamped);
286     } /* Lock acquisition loop */
287
288     /* Sleep for a millisecond to make it a little harder for
289      * httpd children to acquire the lock.
290      */
291     apr_sleep(SLEEPYTIME);
292
293     r->content_type = "text/html";
294
295     if (!r->header_only) {
296         ap_rputs(HTML_HEADER, r);
297         if (gotlock) {
298             /* Increment the counter */
299             base = (exipc_data *)apr_shm_baseaddr_get(exipc_shm);
300             base->counter++;
301             /* Send a page with our pid and the new value of the counter. */
302             ap_rprintf(r, "<p>Lock acquired after %ld microseoncds.</p>\n",
303                        (long int) timecamped);
304             ap_rputs("<table border=\"1\">\n", r);
305             ap_rprintf(r, "<tr><td>Child pid:</td><td>%d</td></tr>\n",
306                        (int) getpid());
307             ap_rprintf(r, "<tr><td>Counter:</td><td>%u</td></tr>\n",
308                        (unsigned int)base->counter);
309             ap_rputs("</table>\n", r);
310         } else {
311             /*
312              * Send a page saying that we couldn't get the lock. Don't say
313              * what the counter is, because without the lock the value could
314              * race.
315              */
316             ap_rprintf(r, "<p>Child %d failed to acquire lock "
317                        "after camping out for %d microseconds.</p>\n",
318                        (int) getpid(), (int) timecamped);
319         }
320         ap_rputs(HTML_FOOTER, r);
321     } /* r->header_only */
322
323     /* Release the lock */
324     if (gotlock)
325         rs = apr_global_mutex_unlock(exipc_mutex);
326     /* Swallowing the result because what are we going to do with it at
327      * this stage?
328      */
329
330     return OK;
331 }
332
333 static void exipc_register_hooks(apr_pool_t *p)
334 {
335     ap_hook_pre_config(exipc_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
336     ap_hook_post_config(exipc_post_config, NULL, NULL, APR_HOOK_MIDDLE);
337     ap_hook_child_init(exipc_child_init, NULL, NULL, APR_HOOK_MIDDLE);
338     ap_hook_handler(exipc_handler, NULL, NULL, APR_HOOK_MIDDLE);
339 }
340
341 /* Dispatch list for API hooks */
342 AP_DECLARE_MODULE(example_ipc) = {
343     STANDARD20_MODULE_STUFF,
344     NULL,                  /* create per-dir    config structures */
345     NULL,                  /* merge  per-dir    config structures */
346     NULL,                  /* create per-server config structures */
347     NULL,                  /* merge  per-server config structures */
348     NULL,                  /* table of config file commands       */
349     exipc_register_hooks   /* register hooks                      */
350 };
351