1 /* Copyright 1999-2005 The Apache Software Foundation or its licensors, as
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 /* Load balancer module for Apache proxy */
21 #include "mod_proxy.h"
23 #include "apr_version.h"
24 #include "apr_hooks.h"
27 #include <unistd.h> /* for getpid() */
30 module AP_MODULE_DECLARE_DATA proxy_balancer_module;
32 static int proxy_balancer_canon(request_rec *r, char *url)
34 char *host, *path, *search;
38 if (strncasecmp(url, "balancer:", 9) == 0) {
45 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
46 "proxy: BALANCER: canonicalising URL %s", url);
49 * We break the URL into host, port, path, search
51 err = ap_proxy_canon_netloc(r->pool, &url, NULL, NULL, &host, &port);
53 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
54 "error parsing URL %s: %s",
56 return HTTP_BAD_REQUEST;
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.
63 if (r->uri == r->unparsed_uri) {
64 search = strchr(url, '?');
72 path = ap_proxy_canonenc(r->pool, url, strlen(url), enc_path, 0, r->proxyreq);
74 return HTTP_BAD_REQUEST;
76 r->filename = apr_pstrcat(r->pool, "proxy:balancer://", host,
77 "/", path, (search) ? "?" : "", (search) ? search : "", NULL);
81 static int init_balancer_members(proxy_server_conf *conf, server_rec *s,
82 proxy_balancer *balancer)
85 proxy_worker *workers;
87 workers = (proxy_worker *)balancer->workers->elts;
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,
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);
110 /* Set default number of attempts to the number of
113 if (!balancer->max_attempts_set && balancer->workers->nelts > 1) {
114 balancer->max_attempts = balancer->workers->nelts - 1;
115 balancer->max_attempts_set = 1;
120 /* Retrieve the parameter with the given name
121 * Something like 'JSESSIONID=12345...N'
123 static char *get_path_param(apr_pool_t *pool, char *url,
128 for (path = strstr(url, name); path; path = strstr(path + 1, name)) {
129 path += strlen(name);
132 * Session path was found, get it's value
137 path = apr_pstrdup(pool, path);
138 if ((q = strchr(path, '?')))
147 static char *get_cookie_param(request_rec *r, const char *name)
150 const char *start_cookie;
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])) {
160 start_cookie += strlen(name);
161 while(*start_cookie && isspace(*start_cookie))
163 if (*start_cookie == '=' && start_cookie[1]) {
165 * Session cookie was found, get it's value
167 char *end_cookie, *cookie;
169 cookie = apr_pstrdup(r->pool, start_cookie);
170 if ((end_cookie = strchr(cookie, ';')) != NULL)
172 if((end_cookie = strchr(cookie, ',')) != NULL)
182 /* Find the worker that has the 'route' defined
184 static proxy_worker *find_route_worker(proxy_balancer *balancer,
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) {
198 static proxy_worker *find_session_route(proxy_balancer *balancer,
203 proxy_worker *worker = NULL;
205 if (!balancer->sticky)
207 /* Try to find the sticky route inside url */
208 *route = get_path_param(r->pool, *url, balancer->sticky);
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);
215 * If we found a value for sticksession, find the first '.' within.
216 * Everything after '.' (if present) is our route.
218 if ((*route) && ((*route = strchr(*route, '.')) != NULL ))
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.
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.
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))
247 static proxy_worker *find_best_worker(proxy_balancer *balancer,
250 proxy_worker *candidate = NULL;
252 if (PROXY_THREAD_LOCK(balancer) != APR_SUCCESS)
255 candidate = (*balancer->lbmethod->finder)(balancer, r);
258 PROXY_THREAD_UNLOCK(balancer);
262 PROXY_THREAD_UNLOCK(balancer);
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.
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.
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
284 balancer->timeout = 0;
285 step = timeout / 100;
286 while (tval < timeout) {
289 if ((candidate = find_best_worker(balancer, r)))
293 /* restore the timeout */
294 balancer->timeout = timeout;
301 static int rewrite_url(request_rec *r, proxy_worker *worker,
304 const char *scheme = strstr(*url, "://");
305 const char *path = NULL;
308 path = ap_strchr_c(scheme + 3, '/');
310 /* we break the URL into host, port, uri */
312 return ap_proxyerror(r, HTTP_BAD_REQUEST, apr_pstrcat(r->pool,
313 "missing worker. URI cannot be parsed: ", *url,
317 *url = apr_pstrcat(r->pool, worker->name, path, NULL);
322 static int proxy_balancer_pre_request(proxy_worker **worker,
323 proxy_balancer **balancer,
325 proxy_server_conf *conf, char **url)
328 proxy_worker *runtime;
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.
339 !(*balancer = ap_proxy_get_balancer(r->pool, conf, *url)))
342 /* Step 2: find the session route */
344 runtime = find_session_route(*balancer, r, &route, url);
345 /* Lock the LoadBalancer
346 * XXX: perhaps we need the process lock here
348 if ((rv = PROXY_THREAD_LOCK(*balancer)) != APR_SUCCESS) {
349 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
350 "proxy: BALANCER: lock");
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
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.
366 if (PROXY_WORKER_IS_USABLE(workers)) {
367 workers->s->lbstatus += workers->s->lbfactor;
368 total_factor += workers->s->lbfactor;
372 runtime->s->lbstatus -= total_factor;
373 runtime->s->elected++;
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;
385 PROXY_THREAD_UNLOCK(*balancer);
387 runtime = find_best_worker(*balancer, r);
389 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
390 "proxy: BALANCER: (%s). All workers are in error state",
393 return HTTP_SERVICE_UNAVAILABLE;
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.
403 access_status = rewrite_url(r, *worker, url);
404 /* Add the session route to request notes if present */
406 apr_table_setn(r->notes, "session-sticky", (*balancer)->sticky);
407 apr_table_setn(r->notes, "session-route", route);
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);
413 return access_status;
416 static int proxy_balancer_post_request(proxy_worker *worker,
417 proxy_balancer *balancer,
419 proxy_server_conf *conf)
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;
428 /* TODO: calculate the bytes transferred
429 * This will enable to elect the worker that has
431 * The bytes transferred depends on the protocol
432 * used, so each protocol handler should keep the
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);
443 static void recalc_factors(proxy_balancer *balancer)
446 proxy_worker *workers;
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
454 if (balancer->workers->nelts == 1) {
455 workers->s->lbstatus = workers->s->lbfactor = 1;
458 for (i = 0; i < balancer->workers->nelts; i++) {
459 /* Update the status entries */
460 workers[i].s->lbstatus = workers[i].s->lbfactor;
464 /* Manages the loadfactors and member status
466 static int balancer_handler(request_rec *r)
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);
478 /* is this for us? */
479 if (strcmp(r->handler, "balancer-manager"))
481 r->allowed = (AP_METHOD_BIT << M_GET);
482 if (r->method_number != M_GET)
486 char *args = apr_pstrdup(r->pool, r->args);
488 while (args && *args) {
489 if ((val = ap_strchr(args, '='))) {
491 if ((tok = ap_strchr(val, '&')))
494 * Special case: workers are allowed path information
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);
503 return HTTP_BAD_REQUEST;
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"))) {
512 ws = ap_proxy_get_worker(r->pool, conf, name);
514 worker = (proxy_worker *)bsel->workers->elts;
515 for (n = 0; n < bsel->workers->nelts; n++) {
516 if (strcasecmp(worker->name, ws->name) == 0) {
524 /* First set the params */
527 if ((val = apr_table_get(params, "ss"))) {
529 bsel->sticky = apr_pstrdup(conf->pool, val);
533 if ((val = apr_table_get(params, "tm"))) {
534 int ival = atoi(val);
536 bsel->timeout = apr_time_from_sec(ival);
538 if ((val = apr_table_get(params, "fa"))) {
539 int ival = atoi(val);
541 bsel->max_attempts = ival;
542 bsel->max_attempts_set = 1;
544 if ((val = apr_table_get(params, "lm"))) {
545 proxy_balancer_method *provider;
546 provider = ap_lookup_provider(PROXY_LBMETHOD, val, "0");
548 bsel->lbmethod = provider;
554 if ((val = apr_table_get(params, "lf"))) {
555 int ival = atoi(val);
556 if (ival >= 1 && ival <= 100) {
557 wsel->s->lbfactor = ival;
559 recalc_factors(bsel);
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);
566 *wsel->s->route = '\0';
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);
572 *wsel->s->redirect = '\0';
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;
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);
604 ap_rputs(" </httpd:workers>\n", r);
605 ap_rputs(" </httpd:balancer>\n", r);
608 ap_rputs(" </httpd:balancers>\n", r);
609 ap_rputs("</httpd:manager>", r);
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++) {
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,
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>"
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>"
645 worker = (proxy_worker *)balancer->workers->elts;
646 for (n = 0; n < balancer->workers->nelts; n++) {
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),
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)
658 else if (worker->s->status & PROXY_WORKER_IN_ERROR)
660 else if (worker->s->status & PROXY_WORKER_INITIALIZED)
664 ap_rputs("</td></tr>\n", r);
668 ap_rputs("</table>\n", r);
671 ap_rputs("<hr />\n", r);
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);
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);
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",
714 ap_rputs("<tr><td>LB Method:</td><td><select name=\"lm\">", r);
716 apr_array_header_t *methods;
717 ap_list_provider_names_t *method;
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);
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);
735 ap_rputs(ap_psignature("",r), r);
736 ap_rputs("</body></html>\n", r);
741 static void child_init(apr_pool_t *p, server_rec *s)
744 void *sconf = s->module_config;
745 proxy_server_conf *conf;
746 proxy_balancer *balancer;
748 conf = (proxy_server_conf *)ap_get_module_config(sconf, &proxy_module);
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);
762 * The idea behind the find_best_byrequests scheduler is the following:
764 * lbfactor is "how much we expect this worker to work", or "the worker's
765 * normalized work quota".
767 * lbstatus is "how urgent this worker has to work to fulfill its quota
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.(*)
776 * If some workers are disabled, the others will
777 * still be scheduled correctly.
779 * If a balancer is configured as follows:
782 * lbfactor 25 25 25 25
784 * And b gets disabled, the following schedule is produced:
786 * a c d a c d a c d ...
788 * Note that the above lbfactor setting is the *exact* same as:
793 * Asymmetric configurations work as one would expect. For
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:
803 * b a d c d a c d b d ...
807 static proxy_worker *find_best_byrequests(proxy_balancer *balancer,
811 int total_factor = 0;
812 proxy_worker *worker = (proxy_worker *)balancer->workers->elts;
813 proxy_worker *mycandidate = NULL;
816 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
817 "proxy: Entering byrequests for BALANCER (%s)",
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
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.
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;
843 mycandidate->s->lbstatus -= total_factor;
844 mycandidate->s->elected++;
851 * The idea behind the find_best_bytraffic scheduler is the following:
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
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.
867 static proxy_worker *find_best_bytraffic(proxy_balancer *balancer,
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;
876 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
877 "proxy: Entering bytraffic for BALANCER (%s)",
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
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.
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;
905 mycandidate->s->elected++;
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.
917 static const proxy_balancer_method byrequests =
920 &find_best_byrequests,
924 static const proxy_balancer_method bytraffic =
927 &find_best_bytraffic,
931 static void ap_proxy_balancer_register_hook(apr_pool_t *p)
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
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);
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 */