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