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