]> granicus.if.org Git - apache/blob - modules/proxy/mod_proxy_balancer.c
Allow the load balancing method to "create" workers.
[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 "apr_hooks.h"
24 #include "apr_uuid.h"
25
26 module AP_MODULE_DECLARE_DATA proxy_balancer_module;
27
28 static char balancer_nonce[APR_UUID_FORMATTED_LENGTH + 1];
29
30 static int proxy_balancer_canon(request_rec *r, char *url)
31 {
32     char *host, *path;
33     char *search = NULL;
34     const char *err;
35     apr_port_t port = 0;
36
37     if (strncasecmp(url, "balancer:", 9) == 0) {
38         url += 9;
39     }
40     else {
41         return DECLINED;
42     }
43
44     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
45              "proxy: BALANCER: canonicalising URL %s", url);
46
47     /* do syntatic check.
48      * We break the URL into host, port, path, search
49      */
50     err = ap_proxy_canon_netloc(r->pool, &url, NULL, NULL, &host, &port);
51     if (err) {
52         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
53                       "error parsing URL %s: %s",
54                       url, err);
55         return HTTP_BAD_REQUEST;
56     }
57     /*
58      * now parse path/search args, according to rfc1738:
59      * process the path. With proxy-noncanon set (by
60      * mod_proxy) we use the raw, unparsed uri
61      */
62     if (apr_table_get(r->notes, "proxy-nocanon")) {
63         path = url;   /* this is the raw path */
64     }
65     else {
66         path = ap_proxy_canonenc(r->pool, url, strlen(url), enc_path, 0,
67                                  r->proxyreq);
68         search = r->args;
69     }
70     if (path == NULL)
71         return HTTP_BAD_REQUEST;
72
73     r->filename = apr_pstrcat(r->pool, "proxy:balancer://", host,
74             "/", path, (search) ? "?" : "", (search) ? search : "", NULL);
75
76     r->path_info = apr_pstrcat(r->pool, "/", path, NULL);
77
78     return OK;
79 }
80
81 static int init_balancer_members(proxy_server_conf *conf, server_rec *s,
82                                  proxy_balancer *balancer)
83 {
84     int i;
85     proxy_worker **workers;
86
87     workers = (proxy_worker **)balancer->workers->elts;
88
89     for (i = 0; i < balancer->workers->nelts; i++) {
90         int worker_is_initialized;
91         worker_is_initialized = PROXY_WORKER_IS_INITIALIZED(*workers);
92         if (!worker_is_initialized) {
93             proxy_worker_stat *slot;
94             /*
95              * If the worker is not initialized check whether its scoreboard
96              * slot is already initialized.
97              */
98             slot = (proxy_worker_stat *) ap_get_scoreboard_lb((*workers)->id);
99             if (slot) {
100                 worker_is_initialized = slot->status & PROXY_WORKER_INITIALIZED;
101             }
102             else {
103                 worker_is_initialized = 0;
104             }
105         }
106         ap_proxy_initialize_worker_share(conf, *workers, s);
107         ap_proxy_initialize_worker(*workers, s, conf->pool);
108         if (!worker_is_initialized) {
109             /* Set to the original configuration */
110             (*workers)->s->lbstatus = (*workers)->s->lbfactor =
111             ((*workers)->lbfactor ? (*workers)->lbfactor : 1);
112             (*workers)->s->lbset = (*workers)->lbset;
113         }
114         ++workers;
115     }
116
117     /* Set default number of attempts to the number of
118      * workers.
119      */
120     if (!balancer->max_attempts_set && balancer->workers->nelts > 1) {
121         balancer->max_attempts = balancer->workers->nelts - 1;
122         balancer->max_attempts_set = 1;
123     }
124     return 0;
125 }
126
127 /* Retrieve the parameter with the given name
128  * Something like 'JSESSIONID=12345...N'
129  */
130 static char *get_path_param(apr_pool_t *pool, char *url,
131                             const char *name, int scolon_sep)
132 {
133     char *path = NULL;
134     char *pathdelims = "?&";
135
136     if (scolon_sep) {
137         pathdelims = ";?&";
138     }
139     for (path = strstr(url, name); path; path = strstr(path + 1, name)) {
140         path += strlen(name);
141         if (*path == '=') {
142             /*
143              * Session path was found, get it's value
144              */
145             ++path;
146             if (strlen(path)) {
147                 char *q;
148                 path = apr_strtok(apr_pstrdup(pool, path), pathdelims, &q);
149                 return path;
150             }
151         }
152     }
153     return NULL;
154 }
155
156 static char *get_cookie_param(request_rec *r, const char *name)
157 {
158     const char *cookies;
159     const char *start_cookie;
160
161     if ((cookies = apr_table_get(r->headers_in, "Cookie"))) {
162         for (start_cookie = ap_strstr_c(cookies, name); start_cookie;
163              start_cookie = ap_strstr_c(start_cookie + 1, name)) {
164             if (start_cookie == cookies ||
165                 start_cookie[-1] == ';' ||
166                 start_cookie[-1] == ',' ||
167                 isspace(start_cookie[-1])) {
168
169                 start_cookie += strlen(name);
170                 while(*start_cookie && isspace(*start_cookie))
171                     ++start_cookie;
172                 if (*start_cookie == '=' && start_cookie[1]) {
173                     /*
174                      * Session cookie was found, get it's value
175                      */
176                     char *end_cookie, *cookie;
177                     ++start_cookie;
178                     cookie = apr_pstrdup(r->pool, start_cookie);
179                     if ((end_cookie = strchr(cookie, ';')) != NULL)
180                         *end_cookie = '\0';
181                     if((end_cookie = strchr(cookie, ',')) != NULL)
182                         *end_cookie = '\0';
183                     return cookie;
184                 }
185             }
186         }
187     }
188     return NULL;
189 }
190
191 /* Find the worker that has the 'route' defined
192  */
193 static proxy_worker *find_route_worker(proxy_balancer *balancer,
194                                        const char *route, request_rec *r)
195 {
196     int i;
197     int checking_standby;
198     int checked_standby;
199     
200     proxy_worker *worker;
201
202     checking_standby = checked_standby = 0;
203     while (!checked_standby) {
204         worker = (proxy_worker *)balancer->workers->elts;
205         for (i = 0; i < balancer->workers->nelts; i++, worker++) {
206             if ( (checking_standby ? !PROXY_WORKER_IS_STANDBY(worker) : PROXY_WORKER_IS_STANDBY(worker)) )
207                 continue;
208             if (*(worker->s->route) && strcmp(worker->s->route, route) == 0) {
209                 if (worker && PROXY_WORKER_IS_USABLE(worker)) {
210                     return worker;
211                 } else {
212                     /*
213                      * If the worker is in error state run
214                      * retry on that worker. It will be marked as
215                      * operational if the retry timeout is elapsed.
216                      * The worker might still be unusable, but we try
217                      * anyway.
218                      */
219                     ap_proxy_retry_worker("BALANCER", worker, r->server);
220                     if (PROXY_WORKER_IS_USABLE(worker)) {
221                             return worker;
222                     } else {
223                         /*
224                          * We have a worker that is unusable.
225                          * It can be in error or disabled, but in case
226                          * it has a redirection set use that redirection worker.
227                          * This enables to safely remove the member from the
228                          * balancer. Of course you will need some kind of
229                          * session replication between those two remote.
230                          */
231                         if (*worker->s->redirect) {
232                             proxy_worker *rworker = NULL;
233                             rworker = find_route_worker(balancer, worker->s->redirect, r);
234                             /* Check if the redirect worker is usable */
235                             if (rworker && !PROXY_WORKER_IS_USABLE(rworker)) {
236                                 /*
237                                  * If the worker is in error state run
238                                  * retry on that worker. It will be marked as
239                                  * operational if the retry timeout is elapsed.
240                                  * The worker might still be unusable, but we try
241                                  * anyway.
242                                  */
243                                 ap_proxy_retry_worker("BALANCER", rworker, r->server);
244                             }
245                             if (rworker && PROXY_WORKER_IS_USABLE(rworker))
246                                 return rworker;
247                         }
248                     }
249                 }
250             }
251         }
252         checked_standby = checking_standby++;
253     }
254     return NULL;
255 }
256
257 static proxy_worker *find_session_route(proxy_balancer *balancer,
258                                         request_rec *r,
259                                         char **route,
260                                         const char **sticky_used,
261                                         char **url)
262 {
263     proxy_worker *worker = NULL;
264
265     if (!balancer->sticky)
266         return NULL;
267     /* Try to find the sticky route inside url */
268     *route = get_path_param(r->pool, *url, balancer->sticky_path, balancer->scolonsep);
269     if (*route) {
270         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
271                      "proxy: BALANCER: Found value %s for "
272                      "stickysession %s", *route, balancer->sticky_path);
273         *sticky_used =  balancer->sticky_path;
274     }
275     else {
276         *route = get_cookie_param(r, balancer->sticky);
277         if (*route) {
278             *sticky_used =  balancer->sticky;
279             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
280                          "proxy: BALANCER: Found value %s for "
281                          "stickysession %s", *route, balancer->sticky);
282         }
283     }
284     /*
285      * If we found a value for sticksession, find the first '.' within.
286      * Everything after '.' (if present) is our route.
287      */
288     if ((*route) && ((*route = strchr(*route, '.')) != NULL ))
289         (*route)++;
290     if ((*route) && (**route)) {
291         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
292                                   "proxy: BALANCER: Found route %s", *route);
293         /* We have a route in path or in cookie
294          * Find the worker that has this route defined.
295          */
296         worker = find_route_worker(balancer, *route, r);
297         if (worker && strcmp(*route, worker->s->route)) {
298             /*
299              * Notice that the route of the worker chosen is different from
300              * the route supplied by the client.
301              */
302             apr_table_setn(r->subprocess_env, "BALANCER_ROUTE_CHANGED", "1");
303             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
304                          "proxy: BALANCER: Route changed from %s to %s",
305                          *route, worker->s->route);
306         }
307         return worker;
308     }
309     else
310         return NULL;
311 }
312
313 static proxy_worker *find_best_worker(proxy_balancer *balancer,
314                                       request_rec *r)
315 {
316     proxy_worker *candidate = NULL;
317     apr_status_t rv;
318
319     if ((rv = PROXY_THREAD_LOCK(balancer)) != APR_SUCCESS) {
320         ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
321         "proxy: BALANCER: (%s). Lock failed for find_best_worker()", balancer->name);
322         return NULL;
323     }
324
325     candidate = (*balancer->lbmethod->finder)(balancer, r);
326
327     if (candidate)
328         candidate->s->elected++;
329
330 /*
331         PROXY_THREAD_UNLOCK(balancer);
332         return NULL;
333 */
334
335     if ((rv = PROXY_THREAD_UNLOCK(balancer)) != APR_SUCCESS) {
336         ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
337         "proxy: BALANCER: (%s). Unlock failed for find_best_worker()", balancer->name);
338     }
339
340     if (candidate == NULL) {
341         /* All the workers are in error state or disabled.
342          * If the balancer has a timeout sleep for a while
343          * and try again to find the worker. The chances are
344          * that some other thread will release a connection.
345          * By default the timeout is not set, and the server
346          * returns SERVER_BUSY.
347          */
348 #if APR_HAS_THREADS
349         if (balancer->timeout) {
350             /* XXX: This can perhaps be build using some
351              * smarter mechanism, like tread_cond.
352              * But since the statuses can came from
353              * different childs, use the provided algo.
354              */
355             apr_interval_time_t timeout = balancer->timeout;
356             apr_interval_time_t step, tval = 0;
357             /* Set the timeout to 0 so that we don't
358              * end in infinite loop
359              */
360             balancer->timeout = 0;
361             step = timeout / 100;
362             while (tval < timeout) {
363                 apr_sleep(step);
364                 /* Try again */
365                 if ((candidate = find_best_worker(balancer, r)))
366                     break;
367                 tval += step;
368             }
369             /* restore the timeout */
370             balancer->timeout = timeout;
371         }
372 #endif
373     }
374
375     return candidate;
376
377 }
378
379 static int rewrite_url(request_rec *r, proxy_worker *worker,
380                         char **url)
381 {
382     const char *scheme = strstr(*url, "://");
383     const char *path = NULL;
384
385     if (scheme)
386         path = ap_strchr_c(scheme + 3, '/');
387
388     /* we break the URL into host, port, uri */
389     if (!worker) {
390         return ap_proxyerror(r, HTTP_BAD_REQUEST, apr_pstrcat(r->pool,
391                              "missing worker. URI cannot be parsed: ", *url,
392                              NULL));
393     }
394
395     *url = apr_pstrcat(r->pool, worker->name, path, NULL);
396
397     return OK;
398 }
399
400 static void force_recovery(proxy_balancer *balancer, server_rec *s)
401 {
402     int i;
403     int ok = 0;
404     proxy_worker **worker;
405
406     worker = (proxy_worker **)balancer->workers->elts;
407     for (i = 0; i < balancer->workers->nelts; i++, worker++) {
408         if (!((*worker)->s->status & PROXY_WORKER_IN_ERROR)) {
409             ok = 1;
410             break;
411         }
412         else {
413             /* Try if we can recover */
414             ap_proxy_retry_worker("BALANCER", *worker, s);
415             if (!((*worker)->s->status & PROXY_WORKER_IN_ERROR)) {
416                 ok = 1;
417                 break;
418             }
419         }
420     }
421     if (!ok) {
422         /* If all workers are in error state force the recovery.
423          */
424         worker = (proxy_worker **)balancer->workers->elts;
425         for (i = 0; i < balancer->workers->nelts; i++, worker++) {
426             ++(*worker)->s->retries;
427             (*worker)->s->status &= ~PROXY_WORKER_IN_ERROR;
428             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
429                          "proxy: BALANCER: (%s). Forcing recovery for worker (%s)",
430                          balancer->name, (*worker)->hostname);
431         }
432     }
433 }
434
435 static int proxy_balancer_pre_request(proxy_worker **worker,
436                                       proxy_balancer **balancer,
437                                       request_rec *r,
438                                       proxy_server_conf *conf, char **url)
439 {
440     int access_status;
441     proxy_worker *runtime;
442     char *route = NULL;
443     const char *sticky = NULL;
444     apr_status_t rv;
445
446     *worker = NULL;
447     /* Step 1: check if the url is for us
448      * The url we can handle starts with 'balancer://'
449      * If balancer is already provided skip the search
450      * for balancer, because this is failover attempt.
451      */
452     if (!*balancer &&
453         !(*balancer = ap_proxy_get_balancer(r->pool, conf, *url)))
454         return DECLINED;
455
456     /* Step 2: Lock the LoadBalancer
457      * XXX: perhaps we need the process lock here
458      */
459     if ((rv = PROXY_THREAD_LOCK(*balancer)) != APR_SUCCESS) {
460         ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
461                      "proxy: BALANCER: (%s). Lock failed for pre_request",
462                      (*balancer)->name);
463         return DECLINED;
464     }
465
466     /* Step 3: force recovery */
467     force_recovery(*balancer, r->server);
468
469     /* Step 4: find the session route */
470     runtime = find_session_route(*balancer, r, &route, &sticky, url);
471     if (runtime) {
472         int i, total_factor = 0;
473         proxy_worker *workers;
474         /* We have a sticky load balancer
475          * Update the workers status
476          * so that even session routes get
477          * into account.
478          */
479         workers = (proxy_worker *)(*balancer)->workers->elts;
480         for (i = 0; i < (*balancer)->workers->nelts; i++) {
481             /* Take into calculation only the workers that are
482              * not in error state or not disabled.
483              *
484              * TODO: Abstract the below, since this is dependent
485              *       on the LB implementation
486              */
487             if (PROXY_WORKER_IS_USABLE(workers)) {
488                 workers->s->lbstatus += workers->s->lbfactor;
489                 total_factor += workers->s->lbfactor;
490             }
491             workers++;
492         }
493         runtime->s->lbstatus -= total_factor;
494         runtime->s->elected++;
495
496         *worker = runtime;
497     }
498     else if (route && (*balancer)->sticky_force) {
499         int i, member_of = 0;
500         proxy_worker *workers;
501         /*
502          * We have a route provided that doesn't match the
503          * balancer name. See if the provider route is the
504          * member of the same balancer in which case return 503
505          */
506         workers = (proxy_worker *)(*balancer)->workers->elts;
507         for (i = 0; i < (*balancer)->workers->nelts; i++) {
508             if (*(workers->s->route) && strcmp(workers->s->route, route) == 0) {
509                 member_of = 1;
510                 break;
511             }
512             workers++;
513         }
514         if (member_of) {
515             ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
516                          "proxy: BALANCER: (%s). All workers are in error state for route (%s)",
517                          (*balancer)->name, route);
518             if ((rv = PROXY_THREAD_UNLOCK(*balancer)) != APR_SUCCESS) {
519                 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
520                              "proxy: BALANCER: (%s). Unlock failed for pre_request",
521                              (*balancer)->name);
522             }
523             return HTTP_SERVICE_UNAVAILABLE;
524         }
525     }
526
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     if (!*worker) {
533         runtime = find_best_worker(*balancer, r);
534         if (!runtime) {
535             ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
536                          "proxy: BALANCER: (%s). All workers are in error state",
537                          (*balancer)->name);
538
539             return HTTP_SERVICE_UNAVAILABLE;
540         }
541         if ((*balancer)->sticky && runtime) {
542             /*
543              * This balancer has sticky sessions and the client either has not
544              * supplied any routing information or all workers for this route
545              * including possible redirect and hotstandby workers are in error
546              * state, but we have found another working worker for this
547              * balancer where we can send the request. Thus notice that we have
548              * changed the route to the backend.
549              */
550             apr_table_setn(r->subprocess_env, "BALANCER_ROUTE_CHANGED", "1");
551         }
552         *worker = runtime;
553     }
554
555     (*worker)->s->busy++;
556
557     /* Add balancer/worker info to env. */
558     apr_table_setn(r->subprocess_env,
559                    "BALANCER_NAME", (*balancer)->name);
560     apr_table_setn(r->subprocess_env,
561                    "BALANCER_WORKER_NAME", (*worker)->name);
562     apr_table_setn(r->subprocess_env,
563                    "BALANCER_WORKER_ROUTE", (*worker)->s->route);
564
565     /* Rewrite the url from 'balancer://url'
566      * to the 'worker_scheme://worker_hostname[:worker_port]/url'
567      * This replaces the balancers fictional name with the
568      * real hostname of the elected worker.
569      */
570     access_status = rewrite_url(r, *worker, url);
571     /* Add the session route to request notes if present */
572     if (route) {
573         apr_table_setn(r->notes, "session-sticky", sticky);
574         apr_table_setn(r->notes, "session-route", route);
575
576         /* Add session info to env. */
577         apr_table_setn(r->subprocess_env,
578                        "BALANCER_SESSION_STICKY", sticky);
579         apr_table_setn(r->subprocess_env,
580                        "BALANCER_SESSION_ROUTE", route);
581     }
582     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
583                  "proxy: BALANCER (%s) worker (%s) rewritten to %s",
584                  (*balancer)->name, (*worker)->name, *url);
585
586     return access_status;
587 }
588
589 static int proxy_balancer_post_request(proxy_worker *worker,
590                                        proxy_balancer *balancer,
591                                        request_rec *r,
592                                        proxy_server_conf *conf)
593 {
594
595 #if 0
596     apr_status_t rv;
597
598     if ((rv = PROXY_THREAD_LOCK(balancer)) != APR_SUCCESS) {
599         ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
600             "proxy: BALANCER: (%s). Lock failed for post_request",
601             balancer->name);
602         return HTTP_INTERNAL_SERVER_ERROR;
603     }
604     /* TODO: placeholder for post_request actions
605      */
606
607     if ((rv = PROXY_THREAD_UNLOCK(balancer)) != APR_SUCCESS) {
608         ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
609             "proxy: BALANCER: (%s). Unlock failed for post_request",
610             balancer->name);
611     }
612     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
613                  "proxy_balancer_post_request for (%s)", balancer->name);
614
615 #endif
616
617     if (worker && worker->s->busy)
618         worker->s->busy--;
619
620     return OK;
621
622 }
623
624 static void recalc_factors(proxy_balancer *balancer)
625 {
626     int i;
627     proxy_worker *workers;
628
629
630     /* Recalculate lbfactors */
631     workers = (proxy_worker *)balancer->workers->elts;
632     /* Special case if there is only one worker it's
633      * load factor will always be 1
634      */
635     if (balancer->workers->nelts == 1) {
636         workers->s->lbstatus = workers->s->lbfactor = 1;
637         return;
638     }
639     for (i = 0; i < balancer->workers->nelts; i++) {
640         /* Update the status entries */
641         workers[i].s->lbstatus = workers[i].s->lbfactor;
642     }
643 }
644
645 /* post_config hook: */
646 static int balancer_init(apr_pool_t *p, apr_pool_t *plog,
647                          apr_pool_t *ptemp, server_rec *s)
648 {
649     void *data;
650     const char *userdata_key = "mod_proxy_balancer_init";
651     apr_uuid_t uuid;
652
653     /* balancer_init() will be called twice during startup.  So, only
654      * set up the static data the second time through. */
655     apr_pool_userdata_get(&data, userdata_key, s->process->pool);
656     if (!data) {
657         apr_pool_userdata_set((const void *)1, userdata_key,
658                                apr_pool_cleanup_null, s->process->pool);
659         return OK;
660     }
661
662     /* Retrieve a UUID and store the nonce for the lifetime of
663      * the process. */
664     apr_uuid_get(&uuid);
665     apr_uuid_format(balancer_nonce, &uuid);
666
667     return OK;
668 }
669
670 /* Manages the loadfactors and member status
671  */
672 static int balancer_handler(request_rec *r)
673 {
674     void *sconf = r->server->module_config;
675     proxy_server_conf *conf = (proxy_server_conf *)
676         ap_get_module_config(sconf, &proxy_module);
677     proxy_balancer *balancer, *bsel = NULL;
678     proxy_worker *worker, *wsel = NULL;
679     apr_table_t *params = apr_table_make(r->pool, 10);
680     int access_status;
681     int i, n;
682     const char *name;
683
684     /* is this for us? */
685     if (strcmp(r->handler, "balancer-manager"))
686         return DECLINED;
687     r->allowed = (AP_METHOD_BIT << M_GET);
688     if (r->method_number != M_GET)
689         return DECLINED;
690
691     if (r->args) {
692         char *args = apr_pstrdup(r->pool, r->args);
693         char *tok, *val;
694         while (args && *args) {
695             if ((val = ap_strchr(args, '='))) {
696                 *val++ = '\0';
697                 if ((tok = ap_strchr(val, '&')))
698                     *tok++ = '\0';
699                 /*
700                  * Special case: workers are allowed path information
701                  */
702                 if ((access_status = ap_unescape_url(val)) != OK)
703                     if (strcmp(args, "w") || (access_status !=  HTTP_NOT_FOUND))
704                         return access_status;
705                 apr_table_setn(params, args, val);
706                 args = tok;
707             }
708             else
709                 return HTTP_BAD_REQUEST;
710         }
711     }
712     
713     /* Check that the supplied nonce matches this server's nonce;
714      * otherwise ignore all parameters, to prevent a CSRF attack. */
715     if ((name = apr_table_get(params, "nonce")) == NULL 
716         || strcmp(balancer_nonce, name) != 0) {
717         apr_table_clear(params);
718     }
719
720     if ((name = apr_table_get(params, "b")))
721         bsel = ap_proxy_get_balancer(r->pool, conf,
722             apr_pstrcat(r->pool, "balancer://", name, NULL));
723     if ((name = apr_table_get(params, "w"))) {
724         proxy_worker *ws;
725
726         ws = ap_proxy_get_worker(r->pool, conf, name);
727         if (bsel && ws) {
728             worker = (proxy_worker *)bsel->workers->elts;
729             for (n = 0; n < bsel->workers->nelts; n++) {
730                 if (strcasecmp(worker->name, ws->name) == 0) {
731                     wsel = worker;
732                     break;
733                 }
734                 ++worker;
735             }
736         }
737     }
738     /* First set the params */
739     /*
740      * Note that it is not possible set the proxy_balancer because it is not
741      * in shared memory.
742      */
743     if (wsel) {
744         const char *val;
745         if ((val = apr_table_get(params, "lf"))) {
746             int ival = atoi(val);
747             if (ival >= 1 && ival <= 100) {
748                 wsel->s->lbfactor = ival;
749                 if (bsel)
750                     recalc_factors(bsel);
751             }
752         }
753         if ((val = apr_table_get(params, "wr"))) {
754             if (strlen(val) && strlen(val) < PROXY_WORKER_MAX_ROUTE_SIZ)
755                 strcpy(wsel->s->route, val);
756             else
757                 *wsel->s->route = '\0';
758         }
759         if ((val = apr_table_get(params, "rr"))) {
760             if (strlen(val) && strlen(val) < PROXY_WORKER_MAX_ROUTE_SIZ)
761                 strcpy(wsel->s->redirect, val);
762             else
763                 *wsel->s->redirect = '\0';
764         }
765         if ((val = apr_table_get(params, "dw"))) {
766             if (!strcasecmp(val, "Disable"))
767                 wsel->s->status |= PROXY_WORKER_DISABLED;
768             else if (!strcasecmp(val, "Enable"))
769                 wsel->s->status &= ~PROXY_WORKER_DISABLED;
770         }
771         if ((val = apr_table_get(params, "ls"))) {
772             int ival = atoi(val);
773             if (ival >= 0 && ival <= 99) {
774                 wsel->s->lbset = ival;
775              }
776         }
777
778     }
779     if (apr_table_get(params, "xml")) {
780         ap_set_content_type(r, "text/xml");
781         ap_rputs("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n", r);
782         ap_rputs("<httpd:manager xmlns:httpd=\"http://httpd.apache.org\">\n", r);
783         ap_rputs("  <httpd:balancers>\n", r);
784         balancer = (proxy_balancer *)conf->balancers->elts;
785         for (i = 0; i < conf->balancers->nelts; i++) {
786             ap_rputs("    <httpd:balancer>\n", r);
787             ap_rvputs(r, "      <httpd:name>", balancer->name, "</httpd:name>\n", NULL);
788             ap_rputs("      <httpd:workers>\n", r);
789             worker = (proxy_worker *)balancer->workers->elts;
790             for (n = 0; n < balancer->workers->nelts; n++) {
791                 ap_rputs("        <httpd:worker>\n", r);
792                 ap_rvputs(r, "          <httpd:scheme>", worker->scheme,
793                           "</httpd:scheme>\n", NULL);
794                 ap_rvputs(r, "          <httpd:hostname>", worker->hostname,
795                           "</httpd:hostname>\n", NULL);
796                ap_rprintf(r, "          <httpd:loadfactor>%d</httpd:loadfactor>\n",
797                           worker->s->lbfactor);
798                 ap_rputs("        </httpd:worker>\n", r);
799                 ++worker;
800             }
801             ap_rputs("      </httpd:workers>\n", r);
802             ap_rputs("    </httpd:balancer>\n", r);
803             ++balancer;
804         }
805         ap_rputs("  </httpd:balancers>\n", r);
806         ap_rputs("</httpd:manager>", r);
807     }
808     else {
809         ap_set_content_type(r, "text/html; charset=ISO-8859-1");
810         ap_rputs(DOCTYPE_HTML_3_2
811                  "<html><head><title>Balancer Manager</title></head>\n", r);
812         ap_rputs("<body><h1>Load Balancer Manager for ", r);
813         ap_rvputs(r, ap_get_server_name(r), "</h1>\n\n", NULL);
814         ap_rvputs(r, "<dl><dt>Server Version: ",
815                   ap_get_server_description(), "</dt>\n", NULL);
816         ap_rvputs(r, "<dt>Server Built: ",
817                   ap_get_server_built(), "\n</dt></dl>\n", NULL);
818         balancer = (proxy_balancer *)conf->balancers->elts;
819         for (i = 0; i < conf->balancers->nelts; i++) {
820
821             ap_rputs("<hr />\n<h3>LoadBalancer Status for ", r);
822             ap_rvputs(r, balancer->name, "</h3>\n\n", NULL);
823             ap_rputs("\n\n<table border=\"0\" style=\"text-align: left;\"><tr>"
824                 "<th>StickySession</th><th>Timeout</th><th>FailoverAttempts</th><th>Method</th>"
825                 "</tr>\n<tr>", r);
826             if (balancer->sticky) {
827                 if (strcmp(balancer->sticky, balancer->sticky_path)) {
828                     ap_rvputs(r, "<td>", balancer->sticky, " | ",
829                               balancer->sticky_path, NULL);
830                 }
831                 else {
832                     ap_rvputs(r, "<td>", balancer->sticky, NULL);
833                 }
834             }
835             else {
836                 ap_rputs("<td> - ", r);
837             }
838             ap_rprintf(r, "</td><td>%" APR_TIME_T_FMT "</td>",
839                 apr_time_sec(balancer->timeout));
840             ap_rprintf(r, "<td>%d</td>\n", balancer->max_attempts);
841             ap_rprintf(r, "<td>%s</td>\n",
842                        balancer->lbmethod->name);
843             ap_rputs("</table>\n<br />", r);
844             ap_rputs("\n\n<table border=\"0\" style=\"text-align: left;\"><tr>"
845                 "<th>Worker URL</th>"
846                 "<th>Route</th><th>RouteRedir</th>"
847                 "<th>Factor</th><th>Set</th><th>Status</th>"
848                 "<th>Elected</th><th>To</th><th>From</th>"
849                 "</tr>\n", r);
850
851             worker = (proxy_worker *)balancer->workers->elts;
852             for (n = 0; n < balancer->workers->nelts; n++) {
853                 char fbuf[50];
854                 ap_rvputs(r, "<tr>\n<td><a href=\"", r->uri, "?b=",
855                           balancer->name + sizeof("balancer://") - 1, "&w=",
856                           ap_escape_uri(r->pool, worker->name),
857                           "&nonce=", balancer_nonce, 
858                           "\">", NULL);
859                 ap_rvputs(r, worker->name, "</a></td>", NULL);
860                 ap_rvputs(r, "<td>", ap_escape_html(r->pool, worker->s->route),
861                           NULL);
862                 ap_rvputs(r, "</td><td>",
863                           ap_escape_html(r->pool, worker->s->redirect), NULL);
864                 ap_rprintf(r, "</td><td>%d</td>", worker->s->lbfactor);
865                 ap_rprintf(r, "<td>%d</td><td>", worker->s->lbset);
866                 if (worker->s->status & PROXY_WORKER_DISABLED)
867                    ap_rputs("Dis ", r);
868                 if (worker->s->status & PROXY_WORKER_IN_ERROR)
869                    ap_rputs("Err ", r);
870                 if (worker->s->status & PROXY_WORKER_STOPPED)
871                    ap_rputs("Stop ", r);
872                 if (worker->s->status & PROXY_WORKER_HOT_STANDBY)
873                    ap_rputs("Stby ", r);
874                 if (PROXY_WORKER_IS_USABLE(worker))
875                     ap_rputs("Ok", r);
876                 if (!PROXY_WORKER_IS_INITIALIZED(worker))
877                     ap_rputs("-", r);
878                 ap_rputs("</td>", r);
879                 ap_rprintf(r, "<td>%" APR_SIZE_T_FMT "</td><td>", worker->s->elected);
880                 ap_rputs(apr_strfsize(worker->s->transferred, fbuf), r);
881                 ap_rputs("</td><td>", r);
882                 ap_rputs(apr_strfsize(worker->s->read, fbuf), r);
883                 ap_rputs("</td></tr>\n", r);
884
885                 ++worker;
886             }
887             ap_rputs("</table>\n", r);
888             ++balancer;
889         }
890         ap_rputs("<hr />\n", r);
891         if (wsel && bsel) {
892             ap_rputs("<h3>Edit worker settings for ", r);
893             ap_rvputs(r, wsel->name, "</h3>\n", NULL);
894             ap_rvputs(r, "<form method=\"GET\" action=\"", NULL);
895             ap_rvputs(r, r->uri, "\">\n<dl>", NULL);
896             ap_rputs("<table><tr><td>Load factor:</td><td><input name=\"lf\" type=text ", r);
897             ap_rprintf(r, "value=\"%d\"></td></tr>\n", wsel->s->lbfactor);
898             ap_rputs("<tr><td>LB Set:</td><td><input name=\"ls\" type=text ", r);
899             ap_rprintf(r, "value=\"%d\"></td></tr>\n", wsel->s->lbset);
900             ap_rputs("<tr><td>Route:</td><td><input name=\"wr\" type=text ", r);
901             ap_rvputs(r, "value=\"", ap_escape_html(r->pool, wsel->s->route),
902                       NULL);
903             ap_rputs("\"></td></tr>\n", r);
904             ap_rputs("<tr><td>Route Redirect:</td><td><input name=\"rr\" type=text ", r);
905             ap_rvputs(r, "value=\"", ap_escape_html(r->pool, wsel->s->redirect),
906                       NULL);
907             ap_rputs("\"></td></tr>\n", r);
908             ap_rputs("<tr><td>Status:</td><td>Disabled: <input name=\"dw\" value=\"Disable\" type=radio", r);
909             if (wsel->s->status & PROXY_WORKER_DISABLED)
910                 ap_rputs(" checked", r);
911             ap_rputs("> | Enabled: <input name=\"dw\" value=\"Enable\" type=radio", r);
912             if (!(wsel->s->status & PROXY_WORKER_DISABLED))
913                 ap_rputs(" checked", r);
914             ap_rputs("></td></tr>\n", r);
915             ap_rputs("<tr><td colspan=2><input type=submit value=\"Submit\"></td></tr>\n", r);
916             ap_rvputs(r, "</table>\n<input type=hidden name=\"w\" ",  NULL);
917             ap_rvputs(r, "value=\"", ap_escape_uri(r->pool, wsel->name), "\">\n", NULL);
918             ap_rvputs(r, "<input type=hidden name=\"b\" ", NULL);
919             ap_rvputs(r, "value=\"", bsel->name + sizeof("balancer://") - 1,
920                       "\">\n", NULL);
921             ap_rvputs(r, "<input type=hidden name=\"nonce\" value=\"", 
922                       balancer_nonce, "\">\n", NULL);
923             ap_rvputs(r, "</form>\n", NULL);
924             ap_rputs("<hr />\n", r);
925         }
926         ap_rputs(ap_psignature("",r), r);
927         ap_rputs("</body></html>\n", r);
928     }
929     return OK;
930 }
931
932 static void child_init(apr_pool_t *p, server_rec *s)
933 {
934     while (s) {
935         void *sconf = s->module_config;
936         proxy_server_conf *conf;
937         proxy_balancer *balancer;
938         int i;
939         conf = (proxy_server_conf *)ap_get_module_config(sconf, &proxy_module);
940
941         /* Initialize shared scoreboard data */
942         balancer = (proxy_balancer *)conf->balancers->elts;
943         for (i = 0; i < conf->balancers->nelts; i++) {
944             proxy_balancer_method *lbmethod = balancer->lbmethod;
945             if (balancer->lbmethod!=NULL && balancer->lbmethod->reset != NULL)
946                balancer->lbmethod->reset(balancer, s);
947             init_balancer_members(conf, s, balancer);
948             balancer++;
949         }
950         s = s->next;
951     }
952
953 }
954
955 static void ap_proxy_balancer_register_hook(apr_pool_t *p)
956 {
957     /* Only the mpm_winnt has child init hook handler.
958      * make sure that we are called after the mpm
959      * initializes
960      */
961     static const char *const aszPred[] = { "mpm_winnt.c", NULL};
962      /* manager handler */
963     ap_hook_post_config(balancer_init, NULL, NULL, APR_HOOK_MIDDLE);
964     ap_hook_handler(balancer_handler, NULL, NULL, APR_HOOK_FIRST);
965     ap_hook_child_init(child_init, aszPred, NULL, APR_HOOK_MIDDLE);
966     proxy_hook_pre_request(proxy_balancer_pre_request, NULL, NULL, APR_HOOK_FIRST);
967     proxy_hook_post_request(proxy_balancer_post_request, NULL, NULL, APR_HOOK_FIRST);
968     proxy_hook_canon_handler(proxy_balancer_canon, NULL, NULL, APR_HOOK_FIRST);
969 }
970
971 module AP_MODULE_DECLARE_DATA proxy_balancer_module = {
972     STANDARD20_MODULE_STUFF,
973     NULL,       /* create per-directory config structure */
974     NULL,       /* merge per-directory config structures */
975     NULL,       /* create per-server config structure */
976     NULL,       /* merge per-server config structures */
977     NULL,       /* command apr_table_t */
978     ap_proxy_balancer_register_hook /* register hooks */
979 };