]> granicus.if.org Git - apache/blob - modules/proxy/mod_proxy_balancer.c
Cleanup effort in prep for GA push:
[apache] / modules / proxy / mod_proxy_balancer.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 /* Load balancer module for Apache proxy */
18
19 #include "mod_proxy.h"
20 #include "scoreboard.h"
21 #include "ap_mpm.h"
22 #include "apr_version.h"
23 #include "ap_hooks.h"
24 #include "apr_date.h"
25
26 static const char *balancer_mutex_type = "proxy-balancer-shm";
27 ap_slotmem_provider_t *storage = NULL;
28
29 module AP_MODULE_DECLARE_DATA proxy_balancer_module;
30
31 /*
32  * Register our mutex type before the config is read so we
33  * can adjust the mutex settings using the Mutex directive.
34  */
35 static int balancer_pre_config(apr_pool_t *pconf, apr_pool_t *plog,
36                                apr_pool_t *ptemp)
37 {
38
39     apr_status_t rv;
40
41     rv = ap_mutex_register(pconf, balancer_mutex_type, NULL,
42                                APR_LOCK_DEFAULT, 0);
43     if (rv != APR_SUCCESS) {
44         return rv;
45     }
46
47     return OK;
48 }
49
50 #if 0
51 extern void proxy_update_members(proxy_balancer **balancer, request_rec *r,
52                                  proxy_server_conf *conf);
53 #endif
54
55 static int proxy_balancer_canon(request_rec *r, char *url)
56 {
57     char *host, *path;
58     char *search = NULL;
59     const char *err;
60     apr_port_t port = 0;
61
62     /* TODO: offset of BALANCER_PREFIX ?? */
63     if (strncasecmp(url, "balancer:", 9) == 0) {
64         url += 9;
65     }
66     else {
67         return DECLINED;
68     }
69
70     ap_log_error(APLOG_MARK, APLOG_TRACE1, 0, r->server,
71              "proxy: BALANCER: canonicalising URL %s", url);
72
73     /* do syntatic check.
74      * We break the URL into host, port, path, search
75      */
76     err = ap_proxy_canon_netloc(r->pool, &url, NULL, NULL, &host, &port);
77     if (err) {
78         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
79                       "error parsing URL %s: %s",
80                       url, err);
81         return HTTP_BAD_REQUEST;
82     }
83     /*
84      * now parse path/search args, according to rfc1738:
85      * process the path. With proxy-noncanon set (by
86      * mod_proxy) we use the raw, unparsed uri
87      */
88     if (apr_table_get(r->notes, "proxy-nocanon")) {
89         path = url;   /* this is the raw path */
90     }
91     else {
92         path = ap_proxy_canonenc(r->pool, url, strlen(url), enc_path, 0,
93                                  r->proxyreq);
94         search = r->args;
95     }
96     if (path == NULL)
97         return HTTP_BAD_REQUEST;
98
99     r->filename = apr_pstrcat(r->pool, "proxy:", BALANCER_PREFIX, host,
100             "/", path, (search) ? "?" : "", (search) ? search : "", NULL);
101
102     r->path_info = apr_pstrcat(r->pool, "/", path, NULL);
103
104     return OK;
105 }
106
107 static void init_balancer_members(apr_pool_t *p, server_rec *s,
108                                  proxy_balancer *balancer)
109 {
110     int i;
111     proxy_worker **workers;
112
113     workers = (proxy_worker **)balancer->workers->elts;
114
115     for (i = 0; i < balancer->workers->nelts; i++) {
116         int worker_is_initialized;
117         proxy_worker *worker = *workers;
118         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
119                      "Looking at %s -> %s initialized?", balancer->name, worker->s->name);
120         worker_is_initialized = PROXY_WORKER_IS_INITIALIZED(worker);
121         if (!worker_is_initialized) {
122             ap_proxy_initialize_worker(worker, s, p);
123         }
124         ++workers;
125     }
126
127     /* Set default number of attempts to the number of
128      * workers.
129      */
130     if (!balancer->s->max_attempts_set && balancer->workers->nelts > 1) {
131         balancer->s->max_attempts = balancer->workers->nelts - 1;
132         balancer->s->max_attempts_set = 1;
133     }
134 }
135
136 /* Retrieve the parameter with the given name
137  * Something like 'JSESSIONID=12345...N'
138  */
139 static char *get_path_param(apr_pool_t *pool, char *url,
140                             const char *name, int scolon_sep)
141 {
142     char *path = NULL;
143     char *pathdelims = "?&";
144
145     if (scolon_sep) {
146         pathdelims = ";?&";
147     }
148     for (path = strstr(url, name); path; path = strstr(path + 1, name)) {
149         path += strlen(name);
150         if (*path == '=') {
151             /*
152              * Session path was found, get its value
153              */
154             ++path;
155             if (*path) {
156                 char *q;
157                 path = apr_strtok(apr_pstrdup(pool, path), pathdelims, &q);
158                 return path;
159             }
160         }
161     }
162     return NULL;
163 }
164
165 static char *get_cookie_param(request_rec *r, const char *name)
166 {
167     const char *cookies;
168     const char *start_cookie;
169
170     if ((cookies = apr_table_get(r->headers_in, "Cookie"))) {
171         for (start_cookie = ap_strstr_c(cookies, name); start_cookie;
172              start_cookie = ap_strstr_c(start_cookie + 1, name)) {
173             if (start_cookie == cookies ||
174                 start_cookie[-1] == ';' ||
175                 start_cookie[-1] == ',' ||
176                 isspace(start_cookie[-1])) {
177
178                 start_cookie += strlen(name);
179                 while(*start_cookie && isspace(*start_cookie))
180                     ++start_cookie;
181                 if (*start_cookie++ == '=' && *start_cookie) {
182                     /*
183                      * Session cookie was found, get its value
184                      */
185                     char *end_cookie, *cookie;
186                     cookie = apr_pstrdup(r->pool, start_cookie);
187                     if ((end_cookie = strchr(cookie, ';')) != NULL)
188                         *end_cookie = '\0';
189                     if((end_cookie = strchr(cookie, ',')) != NULL)
190                         *end_cookie = '\0';
191                     return cookie;
192                 }
193             }
194         }
195     }
196     return NULL;
197 }
198
199 /* Find the worker that has the 'route' defined
200  */
201 static proxy_worker *find_route_worker(proxy_balancer *balancer,
202                                        const char *route, request_rec *r)
203 {
204     int i;
205     int checking_standby;
206     int checked_standby;
207
208     proxy_worker **workers;
209
210     checking_standby = checked_standby = 0;
211     while (!checked_standby) {
212         workers = (proxy_worker **)balancer->workers->elts;
213         for (i = 0; i < balancer->workers->nelts; i++, workers++) {
214             proxy_worker *worker = *workers;
215             if ( (checking_standby ? !PROXY_WORKER_IS_STANDBY(worker) : PROXY_WORKER_IS_STANDBY(worker)) )
216                 continue;
217             if (*(worker->s->route) && strcmp(worker->s->route, route) == 0) {
218                 if (worker && PROXY_WORKER_IS_USABLE(worker)) {
219                     return worker;
220                 } else {
221                     /*
222                      * If the worker is in error state run
223                      * retry on that worker. It will be marked as
224                      * operational if the retry timeout is elapsed.
225                      * The worker might still be unusable, but we try
226                      * anyway.
227                      */
228                     ap_proxy_retry_worker("BALANCER", worker, r->server);
229                     if (PROXY_WORKER_IS_USABLE(worker)) {
230                             return worker;
231                     } else {
232                         /*
233                          * We have a worker that is unusable.
234                          * It can be in error or disabled, but in case
235                          * it has a redirection set use that redirection worker.
236                          * This enables to safely remove the member from the
237                          * balancer. Of course you will need some kind of
238                          * session replication between those two remote.
239                          */
240                         if (*worker->s->redirect) {
241                             proxy_worker *rworker = NULL;
242                             rworker = find_route_worker(balancer, worker->s->redirect, r);
243                             /* Check if the redirect worker is usable */
244                             if (rworker && !PROXY_WORKER_IS_USABLE(rworker)) {
245                                 /*
246                                  * If the worker is in error state run
247                                  * retry on that worker. It will be marked as
248                                  * operational if the retry timeout is elapsed.
249                                  * The worker might still be unusable, but we try
250                                  * anyway.
251                                  */
252                                 ap_proxy_retry_worker("BALANCER", rworker, r->server);
253                             }
254                             if (rworker && PROXY_WORKER_IS_USABLE(rworker))
255                                 return rworker;
256                         }
257                     }
258                 }
259             }
260         }
261         checked_standby = checking_standby++;
262     }
263     return NULL;
264 }
265
266 static proxy_worker *find_session_route(proxy_balancer *balancer,
267                                         request_rec *r,
268                                         char **route,
269                                         const char **sticky_used,
270                                         char **url)
271 {
272     proxy_worker *worker = NULL;
273
274     if (!*balancer->s->sticky)
275         return NULL;
276     /* Try to find the sticky route inside url */
277     *route = get_path_param(r->pool, *url, balancer->s->sticky_path, balancer->s->scolonsep);
278     if (*route) {
279         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
280                      "proxy: BALANCER: Found value %s for "
281                      "stickysession %s", *route, balancer->s->sticky_path);
282         *sticky_used =  balancer->s->sticky_path;
283     }
284     else {
285         *route = get_cookie_param(r, balancer->s->sticky);
286         if (*route) {
287             *sticky_used =  balancer->s->sticky;
288             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
289                          "proxy: BALANCER: Found value %s for "
290                          "stickysession %s", *route, balancer->s->sticky);
291         }
292     }
293     /*
294      * If we found a value for sticksession, find the first '.' within.
295      * Everything after '.' (if present) is our route.
296      */
297     if ((*route) && ((*route = strchr(*route, '.')) != NULL ))
298         (*route)++;
299     if ((*route) && (**route)) {
300         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
301                                   "proxy: BALANCER: Found route %s", *route);
302         /* We have a route in path or in cookie
303          * Find the worker that has this route defined.
304          */
305         worker = find_route_worker(balancer, *route, r);
306         if (worker && strcmp(*route, worker->s->route)) {
307             /*
308              * Notice that the route of the worker chosen is different from
309              * the route supplied by the client.
310              */
311             apr_table_setn(r->subprocess_env, "BALANCER_ROUTE_CHANGED", "1");
312             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
313                          "proxy: BALANCER: Route changed from %s to %s",
314                          *route, worker->s->route);
315         }
316         return worker;
317     }
318     else
319         return NULL;
320 }
321
322 static proxy_worker *find_best_worker(proxy_balancer *balancer,
323                                       request_rec *r)
324 {
325     proxy_worker *candidate = NULL;
326     apr_status_t rv;
327
328     if ((rv = PROXY_THREAD_LOCK(balancer)) != APR_SUCCESS) {
329         ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
330         "proxy: BALANCER: (%s). Lock failed for find_best_worker()", balancer->name);
331         return NULL;
332     }
333
334     candidate = (*balancer->lbmethod->finder)(balancer, r);
335
336     if (candidate)
337         candidate->s->elected++;
338
339     if ((rv = PROXY_THREAD_UNLOCK(balancer)) != APR_SUCCESS) {
340         ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
341         "proxy: BALANCER: (%s). Unlock failed for find_best_worker()", balancer->name);
342     }
343
344     if (candidate == NULL) {
345         /* All the workers are in error state or disabled.
346          * If the balancer has a timeout sleep for a while
347          * and try again to find the worker. The chances are
348          * that some other thread will release a connection.
349          * By default the timeout is not set, and the server
350          * returns SERVER_BUSY.
351          */
352         if (balancer->s->timeout) {
353             /* XXX: This can perhaps be build using some
354              * smarter mechanism, like tread_cond.
355              * But since the statuses can came from
356              * different childs, use the provided algo.
357              */
358             apr_interval_time_t timeout = balancer->s->timeout;
359             apr_interval_time_t step, tval = 0;
360             /* Set the timeout to 0 so that we don't
361              * end in infinite loop
362              */
363             balancer->s->timeout = 0;
364             step = timeout / 100;
365             while (tval < timeout) {
366                 apr_sleep(step);
367                 /* Try again */
368                 if ((candidate = find_best_worker(balancer, r)))
369                     break;
370                 tval += step;
371             }
372             /* restore the timeout */
373             balancer->s->timeout = timeout;
374         }
375     }
376
377     return candidate;
378
379 }
380
381 static int rewrite_url(request_rec *r, proxy_worker *worker,
382                         char **url)
383 {
384     const char *scheme = strstr(*url, "://");
385     const char *path = NULL;
386
387     if (scheme)
388         path = ap_strchr_c(scheme + 3, '/');
389
390     /* we break the URL into host, port, uri */
391     if (!worker) {
392         return ap_proxyerror(r, HTTP_BAD_REQUEST, apr_pstrcat(r->pool,
393                              "missing worker. URI cannot be parsed: ", *url,
394                              NULL));
395     }
396
397     *url = apr_pstrcat(r->pool, worker->s->name, path, NULL);
398
399     return OK;
400 }
401
402 static void force_recovery(proxy_balancer *balancer, server_rec *s)
403 {
404     int i;
405     int ok = 0;
406     proxy_worker **worker;
407
408     worker = (proxy_worker **)balancer->workers->elts;
409     for (i = 0; i < balancer->workers->nelts; i++, worker++) {
410         if (!((*worker)->s->status & PROXY_WORKER_IN_ERROR)) {
411             ok = 1;
412             break;
413         }
414         else {
415             /* Try if we can recover */
416             ap_proxy_retry_worker("BALANCER", *worker, s);
417             if (!((*worker)->s->status & PROXY_WORKER_IN_ERROR)) {
418                 ok = 1;
419                 break;
420             }
421         }
422     }
423     if (!ok) {
424         /* If all workers are in error state force the recovery.
425          */
426         worker = (proxy_worker **)balancer->workers->elts;
427         for (i = 0; i < balancer->workers->nelts; i++, worker++) {
428             ++(*worker)->s->retries;
429             (*worker)->s->status &= ~PROXY_WORKER_IN_ERROR;
430             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
431                          "proxy: BALANCER: (%s). Forcing recovery for worker (%s)",
432                          balancer->name, (*worker)->s->hostname);
433         }
434     }
435 }
436
437 static int proxy_balancer_pre_request(proxy_worker **worker,
438                                       proxy_balancer **balancer,
439                                       request_rec *r,
440                                       proxy_server_conf *conf, char **url)
441 {
442     int access_status;
443     proxy_worker *runtime;
444     char *route = NULL;
445     const char *sticky = NULL;
446     apr_status_t rv;
447
448     *worker = NULL;
449     /* Step 1: check if the url is for us
450      * The url we can handle starts with 'balancer://'
451      * If balancer is already provided skip the search
452      * for balancer, because this is failover attempt.
453      */
454     if (!*balancer &&
455         !(*balancer = ap_proxy_get_balancer(r->pool, conf, *url)))
456         return DECLINED;
457
458     /* Step 2: Lock the LoadBalancer
459      * XXX: perhaps we need the process lock here
460      */
461     if ((rv = PROXY_THREAD_LOCK(*balancer)) != APR_SUCCESS) {
462         ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
463                      "proxy: BALANCER: (%s). Lock failed for pre_request",
464                      (*balancer)->name);
465         return DECLINED;
466     }
467
468     /* Step 3: force recovery */
469     force_recovery(*balancer, r->server);
470
471     /* Step 3.5: Update member list for the balancer */
472     /* TODO: Implement as provider! */
473     ap_proxy_sync_balancer(*balancer, r->server, conf);
474
475     /* Step 4: find the session route */
476     runtime = find_session_route(*balancer, r, &route, &sticky, url);
477     if (runtime) {
478         if ((*balancer)->lbmethod && (*balancer)->lbmethod->updatelbstatus) {
479             /* Call the LB implementation */
480             (*balancer)->lbmethod->updatelbstatus(*balancer, runtime, r->server);
481         }
482         else { /* Use the default one */
483             int i, total_factor = 0;
484             proxy_worker **workers;
485             /* We have a sticky load balancer
486              * Update the workers status
487              * so that even session routes get
488              * into account.
489              */
490             workers = (proxy_worker **)(*balancer)->workers->elts;
491             for (i = 0; i < (*balancer)->workers->nelts; i++) {
492                 /* Take into calculation only the workers that are
493                  * not in error state or not disabled.
494                  */
495                 if (PROXY_WORKER_IS_USABLE(*workers)) {
496                     (*workers)->s->lbstatus += (*workers)->s->lbfactor;
497                     total_factor += (*workers)->s->lbfactor;
498                 }
499                 workers++;
500             }
501             runtime->s->lbstatus -= total_factor;
502         }
503         runtime->s->elected++;
504
505         *worker = runtime;
506     }
507     else if (route && (*balancer)->s->sticky_force) {
508         int i, member_of = 0;
509         proxy_worker **workers;
510         /*
511          * We have a route provided that doesn't match the
512          * balancer name. See if the provider route is the
513          * member of the same balancer in which case return 503
514          */
515         workers = (proxy_worker **)(*balancer)->workers->elts;
516         for (i = 0; i < (*balancer)->workers->nelts; i++) {
517             if (*((*workers)->s->route) && strcmp((*workers)->s->route, route) == 0) {
518                 member_of = 1;
519                 break;
520             }
521             workers++;
522         }
523         if (member_of) {
524             ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
525                          "proxy: BALANCER: (%s). All workers are in error state for route (%s)",
526                          (*balancer)->name, route);
527             if ((rv = PROXY_THREAD_UNLOCK(*balancer)) != APR_SUCCESS) {
528                 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
529                              "proxy: BALANCER: (%s). Unlock failed for pre_request",
530                              (*balancer)->name);
531             }
532             return HTTP_SERVICE_UNAVAILABLE;
533         }
534     }
535
536     if ((rv = PROXY_THREAD_UNLOCK(*balancer)) != APR_SUCCESS) {
537         ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
538                      "proxy: BALANCER: (%s). Unlock failed for pre_request",
539                      (*balancer)->name);
540     }
541     if (!*worker) {
542         runtime = find_best_worker(*balancer, r);
543         if (!runtime) {
544             if ((*balancer)->workers->nelts) {
545                 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
546                             "proxy: BALANCER: (%s). All workers are in error state",
547                             (*balancer)->name);
548             } else {
549                 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
550                             "proxy: BALANCER: (%s). No workers in balancer",
551                             (*balancer)->name);
552             }
553
554             return HTTP_SERVICE_UNAVAILABLE;
555         }
556         if (*(*balancer)->s->sticky && runtime) {
557             /*
558              * This balancer has sticky sessions and the client either has not
559              * supplied any routing information or all workers for this route
560              * including possible redirect and hotstandby workers are in error
561              * state, but we have found another working worker for this
562              * balancer where we can send the request. Thus notice that we have
563              * changed the route to the backend.
564              */
565             apr_table_setn(r->subprocess_env, "BALANCER_ROUTE_CHANGED", "1");
566         }
567         *worker = runtime;
568     }
569
570     (*worker)->s->busy++;
571
572     /* Add balancer/worker info to env. */
573     apr_table_setn(r->subprocess_env,
574                    "BALANCER_NAME", (*balancer)->name);
575     apr_table_setn(r->subprocess_env,
576                    "BALANCER_WORKER_NAME", (*worker)->s->name);
577     apr_table_setn(r->subprocess_env,
578                    "BALANCER_WORKER_ROUTE", (*worker)->s->route);
579
580     /* Rewrite the url from 'balancer://url'
581      * to the 'worker_scheme://worker_hostname[:worker_port]/url'
582      * This replaces the balancers fictional name with the
583      * real hostname of the elected worker.
584      */
585     access_status = rewrite_url(r, *worker, url);
586     /* Add the session route to request notes if present */
587     if (route) {
588         apr_table_setn(r->notes, "session-sticky", sticky);
589         apr_table_setn(r->notes, "session-route", route);
590
591         /* Add session info to env. */
592         apr_table_setn(r->subprocess_env,
593                        "BALANCER_SESSION_STICKY", sticky);
594         apr_table_setn(r->subprocess_env,
595                        "BALANCER_SESSION_ROUTE", route);
596     }
597     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
598                  "proxy: BALANCER (%s) worker (%s) rewritten to %s",
599                  (*balancer)->name, (*worker)->s->name, *url);
600
601     return access_status;
602 }
603
604 static int proxy_balancer_post_request(proxy_worker *worker,
605                                        proxy_balancer *balancer,
606                                        request_rec *r,
607                                        proxy_server_conf *conf)
608 {
609
610     apr_status_t rv;
611
612     if ((rv = PROXY_THREAD_LOCK(balancer)) != APR_SUCCESS) {
613         ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
614             "proxy: BALANCER: (%s). Lock failed for post_request",
615             balancer->name);
616         return HTTP_INTERNAL_SERVER_ERROR;
617     }
618
619     if (!apr_is_empty_array(balancer->errstatuses)) {
620         int i;
621         for (i = 0; i < balancer->errstatuses->nelts; i++) {
622             int val = ((int *)balancer->errstatuses->elts)[i];
623             if (r->status == val) {
624                 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
625                              "proxy: BALANCER: (%s).  Forcing recovery for worker (%s), failonstatus %d",
626                              balancer->name, worker->s->name, val);
627                 worker->s->status |= PROXY_WORKER_IN_ERROR;
628                 worker->s->error_time = apr_time_now();
629                 break;
630             }
631         }
632     }
633
634     if ((rv = PROXY_THREAD_UNLOCK(balancer)) != APR_SUCCESS) {
635         ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
636             "proxy: BALANCER: (%s). Unlock failed for post_request",
637             balancer->name);
638     }
639     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
640                  "proxy_balancer_post_request for (%s)", balancer->name);
641
642     if (worker && worker->s->busy)
643         worker->s->busy--;
644
645     return OK;
646
647 }
648
649 static void recalc_factors(proxy_balancer *balancer)
650 {
651     int i;
652     proxy_worker **workers;
653
654
655     /* Recalculate lbfactors */
656     workers = (proxy_worker **)balancer->workers->elts;
657     /* Special case if there is only one worker its
658      * load factor will always be 1
659      */
660     if (balancer->workers->nelts == 1) {
661         (*workers)->s->lbstatus = (*workers)->s->lbfactor = 1;
662         return;
663     }
664     for (i = 0; i < balancer->workers->nelts; i++) {
665         /* Update the status entries */
666         workers[i]->s->lbstatus = workers[i]->s->lbfactor;
667     }
668 }
669
670 static apr_status_t lock_remove(void *data)
671 {
672     int i;
673     proxy_balancer *balancer;
674     server_rec *s = data;
675     void *sconf = s->module_config;
676     proxy_server_conf *conf = (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
677
678     balancer = (proxy_balancer *)conf->balancers->elts;
679     for (i = 0; i < conf->balancers->nelts; i++, balancer++) {
680         if (balancer->gmutex) {
681             apr_global_mutex_destroy(balancer->gmutex);
682             balancer->gmutex = NULL;
683         }
684     }
685     return(0);
686 }
687
688 /* post_config hook: */
689 static int balancer_post_config(apr_pool_t *pconf, apr_pool_t *plog,
690                          apr_pool_t *ptemp, server_rec *s)
691 {
692     apr_status_t rv;
693     void *sconf = s->module_config;
694     proxy_server_conf *conf = (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
695     ap_slotmem_instance_t *new = NULL;
696     apr_time_t tstamp;
697
698     /* balancer_post_config() will be called twice during startup.  So, don't
699      * set up the static data the 1st time through. */
700     if (ap_state_query(AP_SQ_MAIN_STATE) == AP_SQ_MS_CREATE_PRE_CONFIG)
701         return OK;
702
703     /*
704      * Get slotmem setups
705      */
706     storage = ap_lookup_provider(AP_SLOTMEM_PROVIDER_GROUP, "shared",
707                                  AP_SLOTMEM_PROVIDER_VERSION);
708     if (!storage) {
709         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_EMERG, 0, s,
710                      "ap_lookup_provider %s failed: is mod_slotmem_shm loaded??",
711                      AP_SLOTMEM_PROVIDER_GROUP);
712         return !OK;
713     }
714
715     tstamp = apr_time_now();
716     /*
717      * Go thru each Vhost and create the shared mem slotmem for
718      * each balancer's workers
719      */
720     while (s) {
721         int i,j;
722         proxy_balancer *balancer;
723         sconf = s->module_config;
724         conf = (proxy_server_conf *)ap_get_module_config(sconf, &proxy_module);
725
726         if (conf->balancers->nelts) {
727             conf->max_balancers = conf->balancers->nelts + conf->bgrowth;
728             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, "Doing balancers create: %d, %d (%d)",
729                          (int)ALIGNED_PROXY_BALANCER_SHARED_SIZE,
730                          (int)conf->balancers->nelts, conf->max_balancers);
731
732             rv = storage->create(&new, conf->id,
733                                  ALIGNED_PROXY_BALANCER_SHARED_SIZE,
734                                  conf->max_balancers, AP_SLOTMEM_TYPE_PREGRAB, pconf);
735             if (rv != APR_SUCCESS) {
736                 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s, "balancer slotmem_create failed");
737                 return !OK;
738             }
739             conf->slot = new;
740         }
741         conf->storage = storage;
742
743         /* Initialize shared scoreboard data */
744         balancer = (proxy_balancer *)conf->balancers->elts;
745         for (i = 0; i < conf->balancers->nelts; i++, balancer++) {
746             proxy_worker **workers;
747             proxy_worker *worker;
748             proxy_balancer_shared *bshm;
749             unsigned int index;
750
751             balancer->max_workers = balancer->workers->nelts + balancer->growth;
752             /* no need for the 'balancer://' prefix */
753             ap_pstr2_alnum(pconf, balancer->name + sizeof(BALANCER_PREFIX) - 1,
754                            &balancer->sname);
755             balancer->sname = apr_pstrcat(pconf, conf->id, "_", balancer->sname, NULL);
756
757             /* Create global mutex */
758             rv = ap_global_mutex_create(&(balancer->gmutex), NULL, balancer_mutex_type,
759                                         balancer->sname, s, pconf, 0);
760             if (rv != APR_SUCCESS || !balancer->gmutex) {
761                 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
762                              "mutex creation of %s : %s failed", balancer_mutex_type,
763                              balancer->sname);
764                 return HTTP_INTERNAL_SERVER_ERROR;
765             }
766
767             apr_pool_cleanup_register(pconf, (void *)s, lock_remove,
768                                       apr_pool_cleanup_null);
769
770             /* setup shm for balancers */
771             if ((rv = storage->grab(conf->slot, &index)) != APR_SUCCESS) {
772                 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s, "balancer slotmem_grab failed");
773                 return !OK;
774
775             }
776             if ((rv = storage->dptr(conf->slot, index, (void *)&bshm)) != APR_SUCCESS) {
777                 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s, "balancer slotmem_dptr failed");
778                 return !OK;
779             }
780             if ((rv = ap_proxy_share_balancer(balancer, bshm, index)) != APR_SUCCESS) {
781                 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s, "Cannot share balancer");
782                 return !OK;
783             }
784
785             /* create slotmem slots for workers */
786             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, "Doing workers create: %s (%s), %d, %d",
787                          balancer->name, balancer->sname,
788                          (int)ALIGNED_PROXY_WORKER_SHARED_SIZE,
789                          (int)balancer->max_workers);
790
791             rv = storage->create(&new, balancer->sname,
792                                  ALIGNED_PROXY_WORKER_SHARED_SIZE,
793                                  balancer->max_workers, AP_SLOTMEM_TYPE_PREGRAB, pconf);
794             if (rv != APR_SUCCESS) {
795                 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s, "worker slotmem_create failed");
796                 return !OK;
797             }
798             balancer->slot = new;
799             balancer->storage = storage;
800
801             /* sync all timestamps */
802             balancer->wupdated = balancer->s->wupdated = tstamp;
803
804             /* now go thru each worker */
805             workers = (proxy_worker **)balancer->workers->elts;
806             for (j = 0; j < balancer->workers->nelts; j++, workers++) {
807                 proxy_worker_shared *shm;
808
809                 worker = *workers;
810                 if ((rv = storage->grab(balancer->slot, &index)) != APR_SUCCESS) {
811                     ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s, "worker slotmem_grab failed");
812                     return !OK;
813
814                 }
815                 if ((rv = storage->dptr(balancer->slot, index, (void *)&shm)) != APR_SUCCESS) {
816                     ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s, "worker slotmem_dptr failed");
817                     return !OK;
818                 }
819                 if ((rv = ap_proxy_share_worker(worker, shm, index)) != APR_SUCCESS) {
820                     ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s, "Cannot share worker");
821                     return !OK;
822                 }
823                 worker->s->updated = tstamp;
824             }
825         }
826         s = s->next;
827     }
828
829     return OK;
830 }
831
832 static void create_radio(const char *name, unsigned int flag, request_rec *r)
833 {
834     ap_rvputs(r, "<td>On <input name='", name, "' id='", name, "' value='1' type=radio", NULL);
835     if (flag)
836         ap_rputs(" checked", r);
837     ap_rvputs(r, "> <br/> Off <input name='", name, "' id='", name, "' value='0' type=radio", NULL);
838     if (!flag)
839         ap_rputs(" checked", r);
840     ap_rputs("></td>\n", r);
841 }
842
843 static void push2table(const char *input, apr_table_t *params,
844                        const char *allowed[], apr_pool_t *p)
845 {
846     char *args;
847     char *tok, *val;
848     char *key;
849
850     if (input == NULL) {
851         return;
852     }
853     args = apr_pstrdup(p, input);
854
855     key = apr_strtok(args, "&", &tok);
856     while (key) {
857         val = strchr(key, '=');
858         if (val) {
859             *val++ = '\0';
860         }
861         else {
862             val = "";
863         }
864         ap_unescape_url(key);
865         ap_unescape_url(val);
866         if (allowed == NULL) { /* allow all */
867             apr_table_set(params, key, val);
868         }
869         else {
870             const char *ok = *allowed;
871             while (ok) {
872                 if (strcmp(ok, key) == 0) {
873                     apr_table_set(params, key, val);
874                     break;
875                 }
876                 ok++;
877             }
878         }
879         key = apr_strtok(NULL, "&", &tok);
880     }
881 }
882
883 /* Manages the loadfactors and member status
884  *   The balancer, worker and nonce are obtained from
885  *   the request args (?b=...&w=...&nonce=....).
886  *   All other params are pulled from any POST
887  *   data that exists.
888  * TODO:
889  *   /.../<whatever>/balancer/worker/nonce
890  */
891 static int balancer_handler(request_rec *r)
892 {
893     void *sconf;
894     proxy_server_conf *conf;
895     proxy_balancer *balancer, *bsel = NULL;
896     proxy_worker *worker, *wsel = NULL;
897     proxy_worker **workers = NULL;
898     apr_table_t *params;
899     int i, n;
900     int ok2change = 1;
901     const char *name;
902     const char *action;
903     apr_status_t rv;
904
905     /* is this for us? */
906     if (strcmp(r->handler, "balancer-manager")) {
907         return DECLINED;
908     }
909
910     r->allowed = 0
911     | (AP_METHOD_BIT << M_GET)
912     | (AP_METHOD_BIT << M_POST);
913     if ((r->method_number != M_GET) && (r->method_number != M_POST)) {
914         return DECLINED;
915     }
916
917     sconf = r->server->module_config;
918     conf = (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
919     params = apr_table_make(r->pool, 10);
920
921     balancer = (proxy_balancer *)conf->balancers->elts;
922     for (i = 0; i < conf->balancers->nelts; i++, balancer++) {
923         if ((rv = PROXY_THREAD_LOCK(balancer)) != APR_SUCCESS) {
924             ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
925                          "proxy: BALANCER: (%s). Lock failed for balancer_handler",
926                          balancer->name);
927         }
928         ap_proxy_sync_balancer(balancer, r->server, conf);
929         if ((rv = PROXY_THREAD_UNLOCK(balancer)) != APR_SUCCESS) {
930             ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
931                          "proxy: BALANCER: (%s). Unlock failed for balancer_handler",
932                          balancer->name);
933         }
934     }
935
936     if (r->args && (r->method_number == M_GET)) {
937         const char *allowed[] = { "w", "b", "nonce", NULL };
938         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server, "parsing r->args");
939
940         push2table(r->args, params, allowed, r->pool);
941     }
942     if (r->method_number == M_POST) {
943         apr_bucket_brigade *ib;
944         apr_size_t len = 1024;
945         char *buf = apr_pcalloc(r->pool, len+1);
946
947         ib = apr_brigade_create(r->connection->pool, r->connection->bucket_alloc);
948         rv = ap_get_brigade(r->input_filters, ib, AP_MODE_READBYTES,
949                                 APR_BLOCK_READ, len);
950         if (rv != APR_SUCCESS) {
951             return HTTP_INTERNAL_SERVER_ERROR;
952         }
953         apr_brigade_flatten(ib, buf, &len);
954         buf[len] = '\0';
955         push2table(buf, params, NULL, r->pool);
956     }
957     if ((name = apr_table_get(params, "b")))
958         bsel = ap_proxy_get_balancer(r->pool, conf,
959             apr_pstrcat(r->pool, BALANCER_PREFIX, name, NULL));
960
961     if ((name = apr_table_get(params, "w"))) {
962         wsel = ap_proxy_get_worker(r->pool, bsel, conf, name);
963     }
964
965
966     /* Check that the supplied nonce matches this server's nonce;
967      * otherwise ignore all parameters, to prevent a CSRF attack. */
968     if (!bsel ||
969         (*bsel->s->nonce &&
970          (
971           (name = apr_table_get(params, "nonce")) == NULL ||
972           strcmp(bsel->s->nonce, name) != 0
973          )
974         )
975        ) {
976         apr_table_clear(params);
977         ok2change = 0;
978     }
979
980     /* First set the params */
981     if (wsel && ok2change) {
982         const char *val;
983         int was_usable = PROXY_WORKER_IS_USABLE(wsel);
984
985         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server, "settings worker params");
986
987         if ((val = apr_table_get(params, "w_lf"))) {
988             int ival = atoi(val);
989             if (ival >= 1 && ival <= 100) {
990                 wsel->s->lbfactor = ival;
991                 if (bsel)
992                     recalc_factors(bsel);
993             }
994         }
995         if ((val = apr_table_get(params, "w_wr"))) {
996             if (strlen(val) && strlen(val) < sizeof(wsel->s->route))
997                 strcpy(wsel->s->route, val);
998             else
999                 *wsel->s->route = '\0';
1000         }
1001         if ((val = apr_table_get(params, "w_rr"))) {
1002             if (strlen(val) && strlen(val) < sizeof(wsel->s->redirect))
1003                 strcpy(wsel->s->redirect, val);
1004             else
1005                 *wsel->s->redirect = '\0';
1006         }
1007         if ((val = apr_table_get(params, "w_status_I"))) {
1008             ap_proxy_set_wstatus('I', atoi(val), wsel);
1009         }
1010         if ((val = apr_table_get(params, "w_status_N"))) {
1011             ap_proxy_set_wstatus('N', atoi(val), wsel);
1012         }
1013         if ((val = apr_table_get(params, "w_status_D"))) {
1014             ap_proxy_set_wstatus('D', atoi(val), wsel);
1015         }
1016         if ((val = apr_table_get(params, "w_status_H"))) {
1017             ap_proxy_set_wstatus('H', atoi(val), wsel);
1018         }
1019         if ((val = apr_table_get(params, "w_ls"))) {
1020             int ival = atoi(val);
1021             if (ival >= 0 && ival <= 99) {
1022                 wsel->s->lbset = ival;
1023              }
1024         }
1025         /* if enabling, we need to reset all lb params */
1026         if (bsel && !was_usable && PROXY_WORKER_IS_USABLE(wsel)) {
1027             bsel->s->need_reset = 1;
1028         }
1029
1030     }
1031
1032     if (bsel && ok2change) {
1033         const char *val;
1034         int ival;
1035         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server, "settings balancer params");
1036         if ((val = apr_table_get(params, "b_lbm"))) {
1037             if ((strlen(val) < (sizeof(bsel->s->lbpname)-1)) &&
1038                 strcmp(val, bsel->s->lbpname)) {
1039                 proxy_balancer_method *lbmethod;
1040                 lbmethod = ap_lookup_provider(PROXY_LBMETHOD, val, "0");
1041                 if (lbmethod) {
1042                     PROXY_STRNCPY(bsel->s->lbpname, val);
1043                     bsel->lbmethod = lbmethod;
1044                     bsel->s->wupdated = apr_time_now();
1045                     bsel->s->need_reset = 1;
1046                 }
1047             }
1048         }
1049         if ((val = apr_table_get(params, "b_tmo"))) {
1050             ival = atoi(val);
1051             if (ival >= 0 && ival <= 7200) { /* 2 hrs enuff? */
1052                 bsel->s->timeout = apr_time_from_sec(ival);
1053             }
1054         }
1055         if ((val = apr_table_get(params, "b_max"))) {
1056             ival = atoi(val);
1057             if (ival >= 0 && ival <= 99) {
1058                 bsel->s->max_attempts = ival;
1059             }
1060         }
1061         if ((val = apr_table_get(params, "b_sforce"))) {
1062             ival = atoi(val);
1063             bsel->s->sticky_force = (ival != 0);
1064         }
1065         if ((val = apr_table_get(params, "b_ss")) && *val) {
1066             if (strlen(val) < (sizeof(bsel->s->sticky_path)-1)) {
1067                 if (*val == '-' && *(val+1) == '\0')
1068                     *bsel->s->sticky_path = *bsel->s->sticky = '\0';
1069                 else {
1070                     char *path;
1071                     PROXY_STRNCPY(bsel->s->sticky_path, val);
1072                     PROXY_STRNCPY(bsel->s->sticky, val);
1073
1074                     if ((path = strchr((char *)bsel->s->sticky, '|'))) {
1075                         *path++ = '\0';
1076                         PROXY_STRNCPY(bsel->s->sticky_path, path);
1077                     }
1078                 }
1079             }
1080         }
1081         if ((val = apr_table_get(params, "b_wyes")) &&
1082             (*val == '1' && *(val+1) == '\0') &&
1083             (val = apr_table_get(params, "b_nwrkr"))) {
1084             char *ret;
1085             proxy_worker *nworker;
1086             nworker = ap_proxy_get_worker(conf->pool, bsel, conf, val);
1087             if (!nworker && storage->num_free_slots(bsel->slot)) {
1088                 if ((rv = PROXY_GLOBAL_LOCK(bsel)) != APR_SUCCESS) {
1089                     ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
1090                                  "proxy: BALANCER: (%s). Lock failed for adding worker",
1091                                  bsel->name);
1092                 }
1093                 ret = ap_proxy_define_worker(conf->pool, &nworker, bsel, conf, val, 0);
1094                 if (!ret) {
1095                     unsigned int index;
1096                     proxy_worker_shared *shm;
1097                     PROXY_COPY_CONF_PARAMS(nworker, conf);
1098                     if ((rv = storage->grab(bsel->slot, &index)) != APR_SUCCESS) {
1099                         ap_log_error(APLOG_MARK, APLOG_EMERG, rv, r->server, "worker slotmem_grab failed");
1100                         if ((rv = PROXY_GLOBAL_UNLOCK(bsel)) != APR_SUCCESS) {
1101                             ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
1102                                          "proxy: BALANCER: (%s). Unlock failed for adding worker",
1103                                          bsel->name);
1104                         }
1105                         return HTTP_BAD_REQUEST;
1106                     }
1107                     if ((rv = storage->dptr(bsel->slot, index, (void *)&shm)) != APR_SUCCESS) {
1108                         ap_log_error(APLOG_MARK, APLOG_EMERG, rv, r->server, "worker slotmem_dptr failed");
1109                         if ((rv = PROXY_GLOBAL_UNLOCK(bsel)) != APR_SUCCESS) {
1110                             ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
1111                                          "proxy: BALANCER: (%s). Unlock failed for adding worker",
1112                                          bsel->name);
1113                         }
1114                         return HTTP_BAD_REQUEST;
1115                     }
1116                     if ((rv = ap_proxy_share_worker(nworker, shm, index)) != APR_SUCCESS) {
1117                         ap_log_error(APLOG_MARK, APLOG_EMERG, rv, r->server, "Cannot share worker");
1118                         if ((rv = PROXY_GLOBAL_UNLOCK(bsel)) != APR_SUCCESS) {
1119                             ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
1120                                          "proxy: BALANCER: (%s). Unlock failed for adding worker",
1121                                          bsel->name);
1122                         }
1123                         return HTTP_BAD_REQUEST;
1124                     }
1125                     if ((rv = ap_proxy_initialize_worker(nworker, r->server, conf->pool)) != APR_SUCCESS) {
1126                         ap_log_error(APLOG_MARK, APLOG_EMERG, rv, r->server, "Cannot init worker");
1127                         if ((rv = PROXY_GLOBAL_UNLOCK(bsel)) != APR_SUCCESS) {
1128                             ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
1129                                          "proxy: BALANCER: (%s). Unlock failed for adding worker",
1130                                          bsel->name);
1131                         }
1132                         return HTTP_BAD_REQUEST;
1133                     }
1134                     /* sync all timestamps */
1135                     bsel->wupdated = bsel->s->wupdated = nworker->s->updated = apr_time_now();
1136                     /* by default, all new workers are disabled */
1137                     ap_proxy_set_wstatus('D', 1, nworker);
1138                 }
1139                 if ((rv = PROXY_GLOBAL_UNLOCK(bsel)) != APR_SUCCESS) {
1140                     ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
1141                                  "proxy: BALANCER: (%s). Unlock failed for adding worker",
1142                                  bsel->name);
1143                 }
1144             }
1145
1146         }
1147
1148     }
1149
1150     action = ap_construct_url(r->pool, r->uri, r);
1151     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server, "genning page");
1152
1153     if (apr_table_get(params, "xml")) {
1154         ap_set_content_type(r, "text/xml");
1155         ap_rputs("<?xml version='1.0' encoding='UTF-8' ?>\n", r);
1156         ap_rputs("<httpd:manager xmlns:httpd='http://httpd.apache.org'>\n", r);
1157         ap_rputs("  <httpd:balancers>\n", r);
1158         balancer = (proxy_balancer *)conf->balancers->elts;
1159         for (i = 0; i < conf->balancers->nelts; i++) {
1160             ap_rputs("    <httpd:balancer>\n", r);
1161             ap_rvputs(r, "      <httpd:name>", balancer->name, "</httpd:name>\n", NULL);
1162             ap_rputs("      <httpd:workers>\n", r);
1163             workers = (proxy_worker **)balancer->workers->elts;
1164             for (n = 0; n < balancer->workers->nelts; n++) {
1165                 worker = *workers;
1166                 ap_rputs("        <httpd:worker>\n", r);
1167                 ap_rvputs(r, "          <httpd:scheme>", worker->s->scheme,
1168                           "</httpd:scheme>\n", NULL);
1169                 ap_rvputs(r, "          <httpd:hostname>", worker->s->hostname,
1170                           "</httpd:hostname>\n", NULL);
1171                 ap_rprintf(r, "          <httpd:loadfactor>%d</httpd:loadfactor>\n",
1172                           worker->s->lbfactor);
1173                 ap_rputs("        </httpd:worker>\n", r);
1174                 ++workers;
1175             }
1176             ap_rputs("      </httpd:workers>\n", r);
1177             ap_rputs("    </httpd:balancer>\n", r);
1178             ++balancer;
1179         }
1180         ap_rputs("  </httpd:balancers>\n", r);
1181         ap_rputs("</httpd:manager>", r);
1182     }
1183     else {
1184         ap_set_content_type(r, "text/html; charset=ISO-8859-1");
1185         ap_rputs(DOCTYPE_HTML_3_2
1186                  "<html><head><title>Balancer Manager</title></head>\n", r);
1187         ap_rputs("<body><h1>Load Balancer Manager for ", r);
1188         ap_rvputs(r, ap_get_server_name(r), "</h1>\n\n", NULL);
1189         ap_rvputs(r, "<dl><dt>Server Version: ",
1190                   ap_get_server_description(), "</dt>\n", NULL);
1191         ap_rvputs(r, "<dt>Server Built: ",
1192                   ap_get_server_built(), "\n</dt></dl>\n", NULL);
1193         balancer = (proxy_balancer *)conf->balancers->elts;
1194         for (i = 0; i < conf->balancers->nelts; i++) {
1195
1196             ap_rputs("<hr />\n<h3>LoadBalancer Status for ", r);
1197             ap_rvputs(r, "<a href='", r->uri, "?b=",
1198                       balancer->name + sizeof(BALANCER_PREFIX) - 1,
1199                       "&nonce=", balancer->s->nonce,
1200                       "'>", NULL);
1201             ap_rvputs(r, balancer->name, "</a></h3>\n\n", NULL);
1202             ap_rputs("\n\n<table border='0' style='text-align: left;'><tr>"
1203                 "<th>MaxMembers</th><th>StickySession</th><th>DisableFailover</th><th>Timeout</th><th>FailoverAttempts</th><th>Method</th>"
1204                 "</tr>\n<tr>", r);
1205             /* the below is a safe cast, since the number of slots total will
1206              * never be more than max_workers, which is restricted to int */
1207             ap_rprintf(r, "<td align='center'>%d [%d Used]</td>\n", balancer->max_workers,
1208                        balancer->max_workers - (int)storage->num_free_slots(balancer->slot));
1209             if (*balancer->s->sticky) {
1210                 if (strcmp(balancer->s->sticky, balancer->s->sticky_path)) {
1211                     ap_rvputs(r, "<td align='center'>", balancer->s->sticky, " | ",
1212                               balancer->s->sticky_path, NULL);
1213                 }
1214                 else {
1215                     ap_rvputs(r, "<td align='center'>", balancer->s->sticky, NULL);
1216                 }
1217             }
1218             else {
1219                 ap_rputs("<td align='center'> (None) ", r);
1220             }
1221             ap_rprintf(r, "<td align='center'>%s</td>\n",
1222                        balancer->s->sticky_force ? "On" : "Off");
1223             ap_rprintf(r, "</td><td align='center'>%" APR_TIME_T_FMT "</td>",
1224                 apr_time_sec(balancer->s->timeout));
1225             ap_rprintf(r, "<td align='center'>%d</td>\n", balancer->s->max_attempts);
1226             ap_rprintf(r, "<td align='center'>%s</td>\n",
1227                        balancer->s->lbpname);
1228             ap_rputs("</table>\n<br />", r);
1229             ap_rputs("\n\n<table border='0' style='text-align: left;'><tr>"
1230                 "<th>Worker URL</th>"
1231                 "<th>Route</th><th>RouteRedir</th>"
1232                 "<th>Factor</th><th>Set</th><th align='center'>Status</th>"
1233                 "<th>Elected</th><th>Busy</th><th>Load</th><th>To</th><th>From</th>"
1234                 "</tr>\n", r);
1235
1236             workers = (proxy_worker **)balancer->workers->elts;
1237             for (n = 0; n < balancer->workers->nelts; n++) {
1238                 char fbuf[50];
1239                 worker = *workers;
1240                 ap_rvputs(r, "<tr>\n<td><a href='", r->uri, "?b=",
1241                           balancer->name + sizeof(BALANCER_PREFIX) - 1, "&w=",
1242                           ap_escape_uri(r->pool, worker->s->name),
1243                           "&nonce=", balancer->s->nonce,
1244                           "'>", NULL);
1245                 ap_rvputs(r, worker->s->name, "</a></td>", NULL);
1246                 ap_rvputs(r, "<td align='center'>", ap_escape_html(r->pool, worker->s->route),
1247                           NULL);
1248                 ap_rvputs(r, "</td><td align='center'>",
1249                           ap_escape_html(r->pool, worker->s->redirect), NULL);
1250                 ap_rprintf(r, "</td><td align='center'>%d</td>", worker->s->lbfactor);
1251                 ap_rprintf(r, "<td align='center'>%d</td><td align='center'>", worker->s->lbset);
1252                 ap_rvputs(r, ap_proxy_parse_wstatus(r->pool, worker), NULL);
1253                 ap_rputs("</td>", r);
1254                 ap_rprintf(r, "<td align='center'>%" APR_SIZE_T_FMT "</td>", worker->s->elected);
1255                 ap_rprintf(r, "<td align='center'>%" APR_SIZE_T_FMT "</td>", worker->s->busy);
1256                 ap_rprintf(r, "<td align='center'>%d</td><td align='center'>", worker->s->lbstatus);
1257                 ap_rputs(apr_strfsize(worker->s->transferred, fbuf), r);
1258                 ap_rputs("</td><td align='center'>", r);
1259                 ap_rputs(apr_strfsize(worker->s->read, fbuf), r);
1260                 ap_rputs("</td></tr>\n", r);
1261
1262                 ++workers;
1263             }
1264             ap_rputs("</table>\n", r);
1265             ++balancer;
1266         }
1267         ap_rputs("<hr />\n", r);
1268         if (wsel && bsel) {
1269             ap_rputs("<h3>Edit worker settings for ", r);
1270             ap_rvputs(r, wsel->s->name, "</h3>\n", NULL);
1271             ap_rputs("<form method='POST' enctype='application/x-www-form-urlencoded' action='", r);
1272             ap_rvputs(r, action, "'>\n", NULL);
1273             ap_rputs("<dl>\n<table><tr><td>Load factor:</td><td><input name='w_lf' id='w_lf' type=text ", r);
1274             ap_rprintf(r, "value='%d'></td></tr>\n", wsel->s->lbfactor);
1275             ap_rputs("<tr><td>LB Set:</td><td><input name='w_ls' id='w_ls' type=text ", r);
1276             ap_rprintf(r, "value='%d'></td></tr>\n", wsel->s->lbset);
1277             ap_rputs("<tr><td>Route:</td><td><input name='w_wr' id='w_wr' type=text ", r);
1278             ap_rvputs(r, "value='", ap_escape_html(r->pool, wsel->s->route),
1279                       NULL);
1280             ap_rputs("'></td></tr>\n", r);
1281             ap_rputs("<tr><td>Route Redirect:</td><td><input name='w_rr' id='w_rr' type=text ", r);
1282             ap_rvputs(r, "value='", ap_escape_html(r->pool, wsel->s->redirect),
1283                       NULL);
1284             ap_rputs("'></td></tr>\n", r);
1285             ap_rputs("<tr><td>Status:</td>", r);
1286             ap_rputs("<td><table border='1'><tr><th>Ign</th><th>Drn</th><th>Dis</th><th>Stby</th></tr>\n<tr>", r);
1287             create_radio("w_status_I", (PROXY_WORKER_IGNORE_ERRORS & wsel->s->status), r);
1288             create_radio("w_status_N", (PROXY_WORKER_DRAIN & wsel->s->status), r);
1289             create_radio("w_status_D", (PROXY_WORKER_DISABLED & wsel->s->status), r);
1290             create_radio("w_status_H", (PROXY_WORKER_HOT_STANDBY & wsel->s->status), r);
1291             ap_rputs("</tr></table>\n", r);
1292             ap_rputs("<tr><td colspan=2><input type=submit value='Submit'></td></tr>\n", r);
1293             ap_rvputs(r, "</table>\n<input type=hidden name='w' id='w' ",  NULL);
1294             ap_rvputs(r, "value='", ap_escape_uri(r->pool, wsel->s->name), "'>\n", NULL);
1295             ap_rvputs(r, "<input type=hidden name='b' id='b' ", NULL);
1296             ap_rvputs(r, "value='", bsel->name + sizeof(BALANCER_PREFIX) - 1,
1297                       "'>\n", NULL);
1298             ap_rvputs(r, "<input type=hidden name='nonce' id='nonce' value='",
1299                       bsel->s->nonce, "'>\n", NULL);
1300             ap_rvputs(r, "</form>\n", NULL);
1301             ap_rputs("<hr />\n", r);
1302         } else if (bsel) {
1303             const apr_array_header_t *provs;
1304             const ap_list_provider_names_t *pname;
1305             int i;
1306             ap_rputs("<h3>Edit balancer settings for ", r);
1307             ap_rvputs(r, bsel->name, "</h3>\n", NULL);
1308             ap_rputs("<form method='POST' enctype='application/x-www-form-urlencoded' action='", r);
1309             ap_rvputs(r, action, "'>\n", NULL);
1310             ap_rputs("<dl>\n<table>\n", r);
1311             provs = ap_list_provider_names(r->pool, PROXY_LBMETHOD, "0");
1312             if (provs) {
1313                 ap_rputs("<tr><td>LBmethod:</td>", r);
1314                 ap_rputs("<td>\n<select name='b_lbm' id='b_lbm'>", r);
1315                 pname = (ap_list_provider_names_t *)provs->elts;
1316                 for (i = 0; i < provs->nelts; i++, pname++) {
1317                     ap_rvputs(r,"<option value='", pname->provider_name, "'", NULL);
1318                     if (strcmp(pname->provider_name, bsel->s->lbpname) == 0)
1319                         ap_rputs(" selected ", r);
1320                     ap_rvputs(r, ">", pname->provider_name, "\n", NULL);
1321                 }
1322                 ap_rputs("</select>\n</td></tr>\n", r);
1323             }
1324             ap_rputs("<tr><td>Timeout:</td><td><input name='b_tmo' id='b_tmo' type=text ", r);
1325             ap_rprintf(r, "value='%" APR_TIME_T_FMT "'></td></tr>\n", apr_time_sec(bsel->s->timeout));
1326             ap_rputs("<tr><td>Failover Attempts:</td><td><input name='b_max' id='b_max' type=text ", r);
1327             ap_rprintf(r, "value='%d'></td></tr>\n", bsel->s->max_attempts);
1328             ap_rputs("<tr><td>Disable Failover:</td>", r);
1329             create_radio("b_sforce", bsel->s->sticky_force, r);
1330             ap_rputs("<tr><td>Sticky Session:</td><td><input name='b_ss' id='b_ss' size=64 type=text ", r);
1331             if (strcmp(bsel->s->sticky, bsel->s->sticky_path)) {
1332                 ap_rvputs(r, "value ='", bsel->s->sticky, " | ",
1333                           bsel->s->sticky_path, NULL);
1334             }
1335             else {
1336                 ap_rvputs(r, "value ='", bsel->s->sticky, NULL);
1337             }
1338             ap_rputs("'>&nbsp;&nbsp;&nbsp;&nbsp;(Use '-' to delete)</td></tr>\n", r);
1339             if (storage->num_free_slots(bsel->slot) != 0) {
1340                 ap_rputs("<tr><td>Add New Worker:</td><td><input name='b_nwrkr' id='b_nwrkr' size=32 type=text>"
1341                          "&nbsp;&nbsp;&nbsp;&nbsp;Are you sure? <input name='b_wyes' id='b_wyes' type=checkbox value='1'>"
1342                          "</td></tr>", r);
1343             }
1344             ap_rputs("<tr><td colspan=2><input type=submit value='Submit'></td></tr>\n", r);
1345             ap_rvputs(r, "</table>\n<input type=hidden name='b' id='b' ", NULL);
1346             ap_rvputs(r, "value='", bsel->name + sizeof(BALANCER_PREFIX) - 1,
1347                       "'>\n", NULL);
1348             ap_rvputs(r, "<input type=hidden name='nonce' id='nonce' value='",
1349                       bsel->s->nonce, "'>\n", NULL);
1350             ap_rvputs(r, "</form>\n", NULL);
1351             ap_rputs("<hr />\n", r);
1352         }
1353         ap_rputs(ap_psignature("",r), r);
1354         ap_rputs("</body></html>\n", r);
1355         ap_rflush(r);
1356     }
1357     return DONE;
1358 }
1359
1360 static void balancer_child_init(apr_pool_t *p, server_rec *s)
1361 {
1362     while (s) {
1363         proxy_balancer *balancer;
1364         int i;
1365         void *sconf = s->module_config;
1366         proxy_server_conf *conf = (proxy_server_conf *)ap_get_module_config(sconf, &proxy_module);
1367         apr_status_t rv;
1368
1369         if (conf->balancers->nelts) {
1370             apr_size_t size;
1371             unsigned int num;
1372             storage->attach(&(conf->slot), conf->id, &size, &num, p);
1373             if (!conf->slot) {
1374                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_EMERG, 0, s, "slotmem_attach failed");
1375                 exit(1); /* Ugly, but what else? */
1376             }
1377         }
1378
1379         balancer = (proxy_balancer *)conf->balancers->elts;
1380         for (i = 0; i < conf->balancers->nelts; i++, balancer++) {
1381             rv = ap_proxy_initialize_balancer(balancer, s, p);
1382
1383             if (rv != APR_SUCCESS) {
1384                 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, s,
1385                              "Failed to init balancer %s in child",
1386                              balancer->name);
1387                 exit(1); /* Ugly, but what else? */
1388             }
1389             init_balancer_members(conf->pool, s, balancer);
1390         }
1391         s = s->next;
1392     }
1393
1394 }
1395
1396 static void ap_proxy_balancer_register_hook(apr_pool_t *p)
1397 {
1398     /* Only the mpm_winnt has child init hook handler.
1399      * make sure that we are called after the mpm
1400      * initializes
1401      */
1402     static const char *const aszPred[] = { "mpm_winnt.c", "mod_slotmem_shm.c", NULL};
1403      /* manager handler */
1404     ap_hook_post_config(balancer_post_config, NULL, NULL, APR_HOOK_MIDDLE);
1405     ap_hook_pre_config(balancer_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
1406     ap_hook_handler(balancer_handler, NULL, NULL, APR_HOOK_FIRST);
1407     ap_hook_child_init(balancer_child_init, aszPred, NULL, APR_HOOK_MIDDLE);
1408     proxy_hook_pre_request(proxy_balancer_pre_request, NULL, NULL, APR_HOOK_FIRST);
1409     proxy_hook_post_request(proxy_balancer_post_request, NULL, NULL, APR_HOOK_FIRST);
1410     proxy_hook_canon_handler(proxy_balancer_canon, NULL, NULL, APR_HOOK_FIRST);
1411 }
1412
1413 AP_DECLARE_MODULE(proxy_balancer) = {
1414     STANDARD20_MODULE_STUFF,
1415     NULL,       /* create per-directory config structure */
1416     NULL,       /* merge per-directory config structures */
1417     NULL,       /* create per-server config structure */
1418     NULL,       /* merge per-server config structures */
1419     NULL,       /* command apr_table_t */
1420     ap_proxy_balancer_register_hook /* register hooks */
1421 };