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"
26 module AP_MODULE_DECLARE_DATA proxy_balancer_module;
28 static int proxy_balancer_canon(request_rec *r, char *url)
30 char *host, *path, *search;
34 if (strncasecmp(url, "balancer:", 9) == 0) {
41 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
42 "proxy: BALANCER: canonicalising URL %s", url);
45 * We break the URL into host, port, path, search
47 err = ap_proxy_canon_netloc(r->pool, &url, NULL, NULL, &host, &port);
49 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
50 "error parsing URL %s: %s",
52 return HTTP_BAD_REQUEST;
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.
59 if (r->uri == r->unparsed_uri) {
60 search = strchr(url, '?');
68 path = ap_proxy_canonenc(r->pool, url, strlen(url), enc_path, 0, r->proxyreq);
70 return HTTP_BAD_REQUEST;
72 r->filename = apr_pstrcat(r->pool, "proxy:balancer://", host,
73 "/", path, (search) ? "?" : "", (search) ? search : "", NULL);
77 static int init_balancer_members(proxy_server_conf *conf, server_rec *s,
78 proxy_balancer *balancer)
81 proxy_worker *workers;
83 workers = (proxy_worker *)balancer->workers->elts;
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,
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);
106 /* Set default number of attempts to the number of
109 if (!balancer->max_attempts_set && balancer->workers->nelts > 1) {
110 balancer->max_attempts = balancer->workers->nelts - 1;
111 balancer->max_attempts_set = 1;
116 /* Retrieve the parameter with the given name
117 * Something like 'JSESSIONID=12345...N'
119 static char *get_path_param(apr_pool_t *pool, char *url,
124 for (path = strstr(url, name); path; path = strstr(path + 1, name)) {
125 path += strlen(name);
128 * Session path was found, get it's value
133 path = apr_pstrdup(pool, path);
134 if ((q = strchr(path, '?')))
143 static char *get_cookie_param(request_rec *r, const char *name)
146 const char *start_cookie;
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])) {
156 start_cookie += strlen(name);
157 while(*start_cookie && isspace(*start_cookie))
159 if (*start_cookie == '=' && start_cookie[1]) {
161 * Session cookie was found, get it's value
163 char *end_cookie, *cookie;
165 cookie = apr_pstrdup(r->pool, start_cookie);
166 if ((end_cookie = strchr(cookie, ';')) != NULL)
168 if((end_cookie = strchr(cookie, ',')) != NULL)
178 /* Find the worker that has the 'route' defined
180 static proxy_worker *find_route_worker(proxy_balancer *balancer,
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) {
194 static proxy_worker *find_session_route(proxy_balancer *balancer,
199 proxy_worker *worker = NULL;
201 if (!balancer->sticky)
203 /* Try to find the sticky route inside url */
204 *route = get_path_param(r->pool, *url, balancer->sticky);
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);
211 * If we found a value for sticksession, find the first '.' within.
212 * Everything after '.' (if present) is our route.
214 if ((*route) && ((*route = strchr(*route, '.')) != NULL ))
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.
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.
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))
243 static proxy_worker *find_best_worker(proxy_balancer *balancer,
246 proxy_worker *candidate = NULL;
248 if (PROXY_THREAD_LOCK(balancer) != APR_SUCCESS)
251 candidate = (*balancer->lbmethod->finder)(balancer, r);
254 PROXY_THREAD_UNLOCK(balancer);
258 PROXY_THREAD_UNLOCK(balancer);
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.
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.
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
280 balancer->timeout = 0;
281 step = timeout / 100;
282 while (tval < timeout) {
285 if ((candidate = find_best_worker(balancer, r)))
289 /* restore the timeout */
290 balancer->timeout = timeout;
297 static int rewrite_url(request_rec *r, proxy_worker *worker,
300 const char *scheme = strstr(*url, "://");
301 const char *path = NULL;
304 path = ap_strchr_c(scheme + 3, '/');
306 /* we break the URL into host, port, uri */
308 return ap_proxyerror(r, HTTP_BAD_REQUEST, apr_pstrcat(r->pool,
309 "missing worker. URI cannot be parsed: ", *url,
313 *url = apr_pstrcat(r->pool, worker->name, path, NULL);
318 static int proxy_balancer_pre_request(proxy_worker **worker,
319 proxy_balancer **balancer,
321 proxy_server_conf *conf, char **url)
324 proxy_worker *runtime;
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.
335 !(*balancer = ap_proxy_get_balancer(r->pool, conf, *url)))
338 /* Step 2: find the session route */
340 runtime = find_session_route(*balancer, r, &route, url);
341 /* Lock the LoadBalancer
342 * XXX: perhaps we need the process lock here
344 if ((rv = PROXY_THREAD_LOCK(*balancer)) != APR_SUCCESS) {
345 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
346 "proxy: BALANCER: lock");
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
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.
362 if (PROXY_WORKER_IS_USABLE(workers)) {
363 workers->s->lbstatus += workers->s->lbfactor;
364 total_factor += workers->s->lbfactor;
368 runtime->s->lbstatus -= total_factor;
369 runtime->s->elected++;
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;
381 PROXY_THREAD_UNLOCK(*balancer);
383 runtime = find_best_worker(*balancer, r);
385 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
386 "proxy: BALANCER: (%s). All workers are in error state",
389 return HTTP_SERVICE_UNAVAILABLE;
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.
399 access_status = rewrite_url(r, *worker, url);
400 /* Add the session route to request notes if present */
402 apr_table_setn(r->notes, "session-sticky", (*balancer)->sticky);
403 apr_table_setn(r->notes, "session-route", route);
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);
409 return access_status;
412 static int proxy_balancer_post_request(proxy_worker *worker,
413 proxy_balancer *balancer,
415 proxy_server_conf *conf)
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;
424 /* TODO: calculate the bytes transferred
425 * This will enable to elect the worker that has
427 * The bytes transferred depends on the protocol
428 * used, so each protocol handler should keep the
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);
439 static void recalc_factors(proxy_balancer *balancer)
442 proxy_worker *workers;
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
450 if (balancer->workers->nelts == 1) {
451 workers->s->lbstatus = workers->s->lbfactor = 1;
454 for (i = 0; i < balancer->workers->nelts; i++) {
455 /* Update the status entries */
456 workers[i].s->lbstatus = workers[i].s->lbfactor;
460 /* Manages the loadfactors and member status
462 static int balancer_handler(request_rec *r)
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);
474 /* is this for us? */
475 if (strcmp(r->handler, "balancer-manager"))
477 r->allowed = (AP_METHOD_BIT << M_GET);
478 if (r->method_number != M_GET)
482 char *args = apr_pstrdup(r->pool, r->args);
484 while (args && *args) {
485 if ((val = ap_strchr(args, '='))) {
487 if ((tok = ap_strchr(val, '&')))
490 * Special case: workers are allowed path information
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);
499 return HTTP_BAD_REQUEST;
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"))) {
508 ws = ap_proxy_get_worker(r->pool, conf, name);
510 worker = (proxy_worker *)bsel->workers->elts;
511 for (n = 0; n < bsel->workers->nelts; n++) {
512 if (strcasecmp(worker->name, ws->name) == 0) {
520 /* First set the params */
523 if ((val = apr_table_get(params, "ss"))) {
525 bsel->sticky = apr_pstrdup(conf->pool, val);
529 if ((val = apr_table_get(params, "tm"))) {
530 int ival = atoi(val);
532 bsel->timeout = apr_time_from_sec(ival);
534 if ((val = apr_table_get(params, "fa"))) {
535 int ival = atoi(val);
537 bsel->max_attempts = ival;
538 bsel->max_attempts_set = 1;
540 if ((val = apr_table_get(params, "lm"))) {
541 proxy_balancer_method *provider;
542 provider = ap_lookup_provider(PROXY_LBMETHOD, val, "0");
544 bsel->lbmethod = provider;
550 if ((val = apr_table_get(params, "lf"))) {
551 int ival = atoi(val);
552 if (ival >= 1 && ival <= 100) {
553 wsel->s->lbfactor = ival;
555 recalc_factors(bsel);
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);
562 *wsel->s->route = '\0';
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);
568 *wsel->s->redirect = '\0';
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;
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);
600 ap_rputs(" </httpd:workers>\n", r);
601 ap_rputs(" </httpd:balancer>\n", r);
604 ap_rputs(" </httpd:balancers>\n", r);
605 ap_rputs("</httpd:manager>", r);
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++) {
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,
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>"
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>"
641 worker = (proxy_worker *)balancer->workers->elts;
642 for (n = 0; n < balancer->workers->nelts; n++) {
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),
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)
654 else if (worker->s->status & PROXY_WORKER_IN_ERROR)
656 else if (worker->s->status & PROXY_WORKER_INITIALIZED)
660 ap_rputs("</td></tr>\n", r);
664 ap_rputs("</table>\n", r);
667 ap_rputs("<hr />\n", r);
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);
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);
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",
710 ap_rputs("<tr><td>LB Method:</td><td><select name=\"lm\">", r);
712 apr_array_header_t *methods;
713 ap_list_provider_names_t *method;
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);
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);
731 ap_rputs(ap_psignature("",r), r);
732 ap_rputs("</body></html>\n", r);
737 static void child_init(apr_pool_t *p, server_rec *s)
740 void *sconf = s->module_config;
741 proxy_server_conf *conf;
742 proxy_balancer *balancer;
744 conf = (proxy_server_conf *)ap_get_module_config(sconf, &proxy_module);
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);
758 * The idea behind the find_best_byrequests scheduler is the following:
760 * lbfactor is "how much we expect this worker to work", or "the worker's
761 * normalized work quota".
763 * lbstatus is "how urgent this worker has to work to fulfill its quota
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.(*)
772 * If some workers are disabled, the others will
773 * still be scheduled correctly.
775 * If a balancer is configured as follows:
778 * lbfactor 25 25 25 25
780 * And b gets disabled, the following schedule is produced:
782 * a c d a c d a c d ...
784 * Note that the above lbfactor setting is the *exact* same as:
789 * Asymmetric configurations work as one would expect. For
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:
799 * b a d c d a c d b d ...
803 static proxy_worker *find_best_byrequests(proxy_balancer *balancer,
807 int total_factor = 0;
808 proxy_worker *worker = (proxy_worker *)balancer->workers->elts;
809 proxy_worker *mycandidate = NULL;
812 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
813 "proxy: Entering byrequests for BALANCER (%s)",
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
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.
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;
839 mycandidate->s->lbstatus -= total_factor;
840 mycandidate->s->elected++;
847 * The idea behind the find_best_bytraffic scheduler is the following:
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
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.
863 static proxy_worker *find_best_bytraffic(proxy_balancer *balancer,
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;
872 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
873 "proxy: Entering bytraffic for BALANCER (%s)",
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
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.
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;
901 mycandidate->s->elected++;
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.
913 static const proxy_balancer_method byrequests =
916 &find_best_byrequests,
920 static const proxy_balancer_method bytraffic =
923 &find_best_bytraffic,
927 static void ap_proxy_balancer_register_hook(apr_pool_t *p)
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
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);
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 */