]> granicus.if.org Git - apache/blob - modules/proxy/mod_proxy_balancer.c
In the case where we have no members, they aren't in error
[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             if ((*balancer)->workers->nelts) {
536                 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
537                             "proxy: BALANCER: (%s). All workers are in error state",
538                             (*balancer)->name);
539             } else {
540                 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
541                             "proxy: BALANCER: (%s). No workers in balancer",
542                             (*balancer)->name);
543             }
544
545             return HTTP_SERVICE_UNAVAILABLE;
546         }
547         if ((*balancer)->sticky && runtime) {
548             /*
549              * This balancer has sticky sessions and the client either has not
550              * supplied any routing information or all workers for this route
551              * including possible redirect and hotstandby workers are in error
552              * state, but we have found another working worker for this
553              * balancer where we can send the request. Thus notice that we have
554              * changed the route to the backend.
555              */
556             apr_table_setn(r->subprocess_env, "BALANCER_ROUTE_CHANGED", "1");
557         }
558         *worker = runtime;
559     }
560
561     (*worker)->s->busy++;
562
563     /* Add balancer/worker info to env. */
564     apr_table_setn(r->subprocess_env,
565                    "BALANCER_NAME", (*balancer)->name);
566     apr_table_setn(r->subprocess_env,
567                    "BALANCER_WORKER_NAME", (*worker)->name);
568     apr_table_setn(r->subprocess_env,
569                    "BALANCER_WORKER_ROUTE", (*worker)->s->route);
570
571     /* Rewrite the url from 'balancer://url'
572      * to the 'worker_scheme://worker_hostname[:worker_port]/url'
573      * This replaces the balancers fictional name with the
574      * real hostname of the elected worker.
575      */
576     access_status = rewrite_url(r, *worker, url);
577     /* Add the session route to request notes if present */
578     if (route) {
579         apr_table_setn(r->notes, "session-sticky", sticky);
580         apr_table_setn(r->notes, "session-route", route);
581
582         /* Add session info to env. */
583         apr_table_setn(r->subprocess_env,
584                        "BALANCER_SESSION_STICKY", sticky);
585         apr_table_setn(r->subprocess_env,
586                        "BALANCER_SESSION_ROUTE", route);
587     }
588     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
589                  "proxy: BALANCER (%s) worker (%s) rewritten to %s",
590                  (*balancer)->name, (*worker)->name, *url);
591
592     return access_status;
593 }
594
595 static int proxy_balancer_post_request(proxy_worker *worker,
596                                        proxy_balancer *balancer,
597                                        request_rec *r,
598                                        proxy_server_conf *conf)
599 {
600
601 #if 0
602     apr_status_t rv;
603
604     if ((rv = PROXY_THREAD_LOCK(balancer)) != APR_SUCCESS) {
605         ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
606             "proxy: BALANCER: (%s). Lock failed for post_request",
607             balancer->name);
608         return HTTP_INTERNAL_SERVER_ERROR;
609     }
610     /* TODO: placeholder for post_request actions
611      */
612
613     if ((rv = PROXY_THREAD_UNLOCK(balancer)) != APR_SUCCESS) {
614         ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
615             "proxy: BALANCER: (%s). Unlock failed for post_request",
616             balancer->name);
617     }
618     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
619                  "proxy_balancer_post_request for (%s)", balancer->name);
620
621 #endif
622
623     if (worker && worker->s->busy)
624         worker->s->busy--;
625
626     return OK;
627
628 }
629
630 static void recalc_factors(proxy_balancer *balancer)
631 {
632     int i;
633     proxy_worker *workers;
634
635
636     /* Recalculate lbfactors */
637     workers = (proxy_worker *)balancer->workers->elts;
638     /* Special case if there is only one worker it's
639      * load factor will always be 1
640      */
641     if (balancer->workers->nelts == 1) {
642         workers->s->lbstatus = workers->s->lbfactor = 1;
643         return;
644     }
645     for (i = 0; i < balancer->workers->nelts; i++) {
646         /* Update the status entries */
647         workers[i].s->lbstatus = workers[i].s->lbfactor;
648     }
649 }
650
651 /* post_config hook: */
652 static int balancer_init(apr_pool_t *p, apr_pool_t *plog,
653                          apr_pool_t *ptemp, server_rec *s)
654 {
655     void *data;
656     const char *userdata_key = "mod_proxy_balancer_init";
657     apr_uuid_t uuid;
658
659     /* balancer_init() will be called twice during startup.  So, only
660      * set up the static data the second time through. */
661     apr_pool_userdata_get(&data, userdata_key, s->process->pool);
662     if (!data) {
663         apr_pool_userdata_set((const void *)1, userdata_key,
664                                apr_pool_cleanup_null, s->process->pool);
665         return OK;
666     }
667
668     /* Retrieve a UUID and store the nonce for the lifetime of
669      * the process. */
670     apr_uuid_get(&uuid);
671     apr_uuid_format(balancer_nonce, &uuid);
672
673     return OK;
674 }
675
676 /* Manages the loadfactors and member status
677  */
678 static int balancer_handler(request_rec *r)
679 {
680     void *sconf = r->server->module_config;
681     proxy_server_conf *conf = (proxy_server_conf *)
682         ap_get_module_config(sconf, &proxy_module);
683     proxy_balancer *balancer, *bsel = NULL;
684     proxy_worker *worker, *wsel = NULL;
685     apr_table_t *params = apr_table_make(r->pool, 10);
686     int access_status;
687     int i, n;
688     const char *name;
689
690     /* is this for us? */
691     if (strcmp(r->handler, "balancer-manager"))
692         return DECLINED;
693     r->allowed = (AP_METHOD_BIT << M_GET);
694     if (r->method_number != M_GET)
695         return DECLINED;
696
697     if (r->args) {
698         char *args = apr_pstrdup(r->pool, r->args);
699         char *tok, *val;
700         while (args && *args) {
701             if ((val = ap_strchr(args, '='))) {
702                 *val++ = '\0';
703                 if ((tok = ap_strchr(val, '&')))
704                     *tok++ = '\0';
705                 /*
706                  * Special case: workers are allowed path information
707                  */
708                 if ((access_status = ap_unescape_url(val)) != OK)
709                     if (strcmp(args, "w") || (access_status !=  HTTP_NOT_FOUND))
710                         return access_status;
711                 apr_table_setn(params, args, val);
712                 args = tok;
713             }
714             else
715                 return HTTP_BAD_REQUEST;
716         }
717     }
718     
719     /* Check that the supplied nonce matches this server's nonce;
720      * otherwise ignore all parameters, to prevent a CSRF attack. */
721     if ((name = apr_table_get(params, "nonce")) == NULL 
722         || strcmp(balancer_nonce, name) != 0) {
723         apr_table_clear(params);
724     }
725
726     if ((name = apr_table_get(params, "b")))
727         bsel = ap_proxy_get_balancer(r->pool, conf,
728             apr_pstrcat(r->pool, "balancer://", name, NULL));
729     if ((name = apr_table_get(params, "w"))) {
730         proxy_worker *ws;
731
732         ws = ap_proxy_get_worker(r->pool, conf, name);
733         if (bsel && ws) {
734             worker = (proxy_worker *)bsel->workers->elts;
735             for (n = 0; n < bsel->workers->nelts; n++) {
736                 if (strcasecmp(worker->name, ws->name) == 0) {
737                     wsel = worker;
738                     break;
739                 }
740                 ++worker;
741             }
742         }
743     }
744     /* First set the params */
745     /*
746      * Note that it is not possible set the proxy_balancer because it is not
747      * in shared memory.
748      */
749     if (wsel) {
750         const char *val;
751         if ((val = apr_table_get(params, "lf"))) {
752             int ival = atoi(val);
753             if (ival >= 1 && ival <= 100) {
754                 wsel->s->lbfactor = ival;
755                 if (bsel)
756                     recalc_factors(bsel);
757             }
758         }
759         if ((val = apr_table_get(params, "wr"))) {
760             if (strlen(val) && strlen(val) < PROXY_WORKER_MAX_ROUTE_SIZ)
761                 strcpy(wsel->s->route, val);
762             else
763                 *wsel->s->route = '\0';
764         }
765         if ((val = apr_table_get(params, "rr"))) {
766             if (strlen(val) && strlen(val) < PROXY_WORKER_MAX_ROUTE_SIZ)
767                 strcpy(wsel->s->redirect, val);
768             else
769                 *wsel->s->redirect = '\0';
770         }
771         if ((val = apr_table_get(params, "dw"))) {
772             if (!strcasecmp(val, "Disable"))
773                 wsel->s->status |= PROXY_WORKER_DISABLED;
774             else if (!strcasecmp(val, "Enable"))
775                 wsel->s->status &= ~PROXY_WORKER_DISABLED;
776         }
777         if ((val = apr_table_get(params, "ls"))) {
778             int ival = atoi(val);
779             if (ival >= 0 && ival <= 99) {
780                 wsel->s->lbset = ival;
781              }
782         }
783
784     }
785     if (apr_table_get(params, "xml")) {
786         ap_set_content_type(r, "text/xml");
787         ap_rputs("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n", r);
788         ap_rputs("<httpd:manager xmlns:httpd=\"http://httpd.apache.org\">\n", r);
789         ap_rputs("  <httpd:balancers>\n", r);
790         balancer = (proxy_balancer *)conf->balancers->elts;
791         for (i = 0; i < conf->balancers->nelts; i++) {
792             ap_rputs("    <httpd:balancer>\n", r);
793             ap_rvputs(r, "      <httpd:name>", balancer->name, "</httpd:name>\n", NULL);
794             ap_rputs("      <httpd:workers>\n", r);
795             worker = (proxy_worker *)balancer->workers->elts;
796             for (n = 0; n < balancer->workers->nelts; n++) {
797                 ap_rputs("        <httpd:worker>\n", r);
798                 ap_rvputs(r, "          <httpd:scheme>", worker->scheme,
799                           "</httpd:scheme>\n", NULL);
800                 ap_rvputs(r, "          <httpd:hostname>", worker->hostname,
801                           "</httpd:hostname>\n", NULL);
802                ap_rprintf(r, "          <httpd:loadfactor>%d</httpd:loadfactor>\n",
803                           worker->s->lbfactor);
804                 ap_rputs("        </httpd:worker>\n", r);
805                 ++worker;
806             }
807             ap_rputs("      </httpd:workers>\n", r);
808             ap_rputs("    </httpd:balancer>\n", r);
809             ++balancer;
810         }
811         ap_rputs("  </httpd:balancers>\n", r);
812         ap_rputs("</httpd:manager>", r);
813     }
814     else {
815         ap_set_content_type(r, "text/html; charset=ISO-8859-1");
816         ap_rputs(DOCTYPE_HTML_3_2
817                  "<html><head><title>Balancer Manager</title></head>\n", r);
818         ap_rputs("<body><h1>Load Balancer Manager for ", r);
819         ap_rvputs(r, ap_get_server_name(r), "</h1>\n\n", NULL);
820         ap_rvputs(r, "<dl><dt>Server Version: ",
821                   ap_get_server_description(), "</dt>\n", NULL);
822         ap_rvputs(r, "<dt>Server Built: ",
823                   ap_get_server_built(), "\n</dt></dl>\n", NULL);
824         balancer = (proxy_balancer *)conf->balancers->elts;
825         for (i = 0; i < conf->balancers->nelts; i++) {
826
827             ap_rputs("<hr />\n<h3>LoadBalancer Status for ", r);
828             ap_rvputs(r, balancer->name, "</h3>\n\n", NULL);
829             ap_rputs("\n\n<table border=\"0\" style=\"text-align: left;\"><tr>"
830                 "<th>StickySession</th><th>Timeout</th><th>FailoverAttempts</th><th>Method</th>"
831                 "</tr>\n<tr>", r);
832             if (balancer->sticky) {
833                 if (strcmp(balancer->sticky, balancer->sticky_path)) {
834                     ap_rvputs(r, "<td>", balancer->sticky, " | ",
835                               balancer->sticky_path, NULL);
836                 }
837                 else {
838                     ap_rvputs(r, "<td>", balancer->sticky, NULL);
839                 }
840             }
841             else {
842                 ap_rputs("<td> - ", r);
843             }
844             ap_rprintf(r, "</td><td>%" APR_TIME_T_FMT "</td>",
845                 apr_time_sec(balancer->timeout));
846             ap_rprintf(r, "<td>%d</td>\n", balancer->max_attempts);
847             ap_rprintf(r, "<td>%s</td>\n",
848                        balancer->lbmethod->name);
849             ap_rputs("</table>\n<br />", r);
850             ap_rputs("\n\n<table border=\"0\" style=\"text-align: left;\"><tr>"
851                 "<th>Worker URL</th>"
852                 "<th>Route</th><th>RouteRedir</th>"
853                 "<th>Factor</th><th>Set</th><th>Status</th>"
854                 "<th>Elected</th><th>To</th><th>From</th>"
855                 "</tr>\n", r);
856
857             worker = (proxy_worker *)balancer->workers->elts;
858             for (n = 0; n < balancer->workers->nelts; n++) {
859                 char fbuf[50];
860                 ap_rvputs(r, "<tr>\n<td><a href=\"", r->uri, "?b=",
861                           balancer->name + sizeof("balancer://") - 1, "&w=",
862                           ap_escape_uri(r->pool, worker->name),
863                           "&nonce=", balancer_nonce, 
864                           "\">", NULL);
865                 ap_rvputs(r, worker->name, "</a></td>", NULL);
866                 ap_rvputs(r, "<td>", ap_escape_html(r->pool, worker->s->route),
867                           NULL);
868                 ap_rvputs(r, "</td><td>",
869                           ap_escape_html(r->pool, worker->s->redirect), NULL);
870                 ap_rprintf(r, "</td><td>%d</td>", worker->s->lbfactor);
871                 ap_rprintf(r, "<td>%d</td><td>", worker->s->lbset);
872                 if (worker->s->status & PROXY_WORKER_DISABLED)
873                    ap_rputs("Dis ", r);
874                 if (worker->s->status & PROXY_WORKER_IN_ERROR)
875                    ap_rputs("Err ", r);
876                 if (worker->s->status & PROXY_WORKER_STOPPED)
877                    ap_rputs("Stop ", r);
878                 if (worker->s->status & PROXY_WORKER_HOT_STANDBY)
879                    ap_rputs("Stby ", r);
880                 if (PROXY_WORKER_IS_USABLE(worker))
881                     ap_rputs("Ok", r);
882                 if (!PROXY_WORKER_IS_INITIALIZED(worker))
883                     ap_rputs("-", r);
884                 ap_rputs("</td>", r);
885                 ap_rprintf(r, "<td>%" APR_SIZE_T_FMT "</td><td>", worker->s->elected);
886                 ap_rputs(apr_strfsize(worker->s->transferred, fbuf), r);
887                 ap_rputs("</td><td>", r);
888                 ap_rputs(apr_strfsize(worker->s->read, fbuf), r);
889                 ap_rputs("</td></tr>\n", r);
890
891                 ++worker;
892             }
893             ap_rputs("</table>\n", r);
894             ++balancer;
895         }
896         ap_rputs("<hr />\n", r);
897         if (wsel && bsel) {
898             ap_rputs("<h3>Edit worker settings for ", r);
899             ap_rvputs(r, wsel->name, "</h3>\n", NULL);
900             ap_rvputs(r, "<form method=\"GET\" action=\"", NULL);
901             ap_rvputs(r, r->uri, "\">\n<dl>", NULL);
902             ap_rputs("<table><tr><td>Load factor:</td><td><input name=\"lf\" type=text ", r);
903             ap_rprintf(r, "value=\"%d\"></td></tr>\n", wsel->s->lbfactor);
904             ap_rputs("<tr><td>LB Set:</td><td><input name=\"ls\" type=text ", r);
905             ap_rprintf(r, "value=\"%d\"></td></tr>\n", wsel->s->lbset);
906             ap_rputs("<tr><td>Route:</td><td><input name=\"wr\" type=text ", r);
907             ap_rvputs(r, "value=\"", ap_escape_html(r->pool, wsel->s->route),
908                       NULL);
909             ap_rputs("\"></td></tr>\n", r);
910             ap_rputs("<tr><td>Route Redirect:</td><td><input name=\"rr\" type=text ", r);
911             ap_rvputs(r, "value=\"", ap_escape_html(r->pool, wsel->s->redirect),
912                       NULL);
913             ap_rputs("\"></td></tr>\n", r);
914             ap_rputs("<tr><td>Status:</td><td>Disabled: <input name=\"dw\" value=\"Disable\" type=radio", r);
915             if (wsel->s->status & PROXY_WORKER_DISABLED)
916                 ap_rputs(" checked", r);
917             ap_rputs("> | Enabled: <input name=\"dw\" value=\"Enable\" type=radio", r);
918             if (!(wsel->s->status & PROXY_WORKER_DISABLED))
919                 ap_rputs(" checked", r);
920             ap_rputs("></td></tr>\n", r);
921             ap_rputs("<tr><td colspan=2><input type=submit value=\"Submit\"></td></tr>\n", r);
922             ap_rvputs(r, "</table>\n<input type=hidden name=\"w\" ",  NULL);
923             ap_rvputs(r, "value=\"", ap_escape_uri(r->pool, wsel->name), "\">\n", NULL);
924             ap_rvputs(r, "<input type=hidden name=\"b\" ", NULL);
925             ap_rvputs(r, "value=\"", bsel->name + sizeof("balancer://") - 1,
926                       "\">\n", NULL);
927             ap_rvputs(r, "<input type=hidden name=\"nonce\" value=\"", 
928                       balancer_nonce, "\">\n", NULL);
929             ap_rvputs(r, "</form>\n", NULL);
930             ap_rputs("<hr />\n", r);
931         }
932         ap_rputs(ap_psignature("",r), r);
933         ap_rputs("</body></html>\n", r);
934     }
935     return OK;
936 }
937
938 static void child_init(apr_pool_t *p, server_rec *s)
939 {
940     while (s) {
941         void *sconf = s->module_config;
942         proxy_server_conf *conf;
943         proxy_balancer *balancer;
944         int i;
945         conf = (proxy_server_conf *)ap_get_module_config(sconf, &proxy_module);
946
947         /* Initialize shared scoreboard data */
948         balancer = (proxy_balancer *)conf->balancers->elts;
949         for (i = 0; i < conf->balancers->nelts; i++) {
950             if (balancer->lbmethod && balancer->lbmethod->reset)
951                balancer->lbmethod->reset(balancer, s);
952             init_balancer_members(conf, s, balancer);
953             balancer++;
954         }
955         s = s->next;
956     }
957
958 }
959
960 static void ap_proxy_balancer_register_hook(apr_pool_t *p)
961 {
962     /* Only the mpm_winnt has child init hook handler.
963      * make sure that we are called after the mpm
964      * initializes
965      */
966     static const char *const aszPred[] = { "mpm_winnt.c", NULL};
967      /* manager handler */
968     ap_hook_post_config(balancer_init, NULL, NULL, APR_HOOK_MIDDLE);
969     ap_hook_handler(balancer_handler, NULL, NULL, APR_HOOK_FIRST);
970     ap_hook_child_init(child_init, aszPred, NULL, APR_HOOK_MIDDLE);
971     proxy_hook_pre_request(proxy_balancer_pre_request, NULL, NULL, APR_HOOK_FIRST);
972     proxy_hook_post_request(proxy_balancer_post_request, NULL, NULL, APR_HOOK_FIRST);
973     proxy_hook_canon_handler(proxy_balancer_canon, NULL, NULL, APR_HOOK_FIRST);
974 }
975
976 module AP_MODULE_DECLARE_DATA proxy_balancer_module = {
977     STANDARD20_MODULE_STUFF,
978     NULL,       /* create per-directory config structure */
979     NULL,       /* merge per-directory config structures */
980     NULL,       /* create per-server config structure */
981     NULL,       /* merge per-server config structures */
982     NULL,       /* command apr_table_t */
983     ap_proxy_balancer_register_hook /* register hooks */
984 };