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