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