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
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 */
19 #include "mod_proxy.h"
20 #include "scoreboard.h"
22 #include "apr_version.h"
23 #include "apr_hooks.h"
25 module AP_MODULE_DECLARE_DATA proxy_balancer_module;
27 static int proxy_balancer_canon(request_rec *r, char *url)
29 char *host, *path, *search;
33 if (strncasecmp(url, "balancer:", 9) == 0) {
40 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
41 "proxy: BALANCER: canonicalising URL %s", url);
44 * We break the URL into host, port, path, search
46 err = ap_proxy_canon_netloc(r->pool, &url, NULL, NULL, &host, &port);
48 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
49 "error parsing URL %s: %s",
51 return HTTP_BAD_REQUEST;
53 /* now parse path/search args, according to rfc1738 */
57 if (apr_table_get(r->notes, "proxy-nocanon")) {
58 path = url; /* this is the raw path */
61 path = ap_proxy_canonenc(r->pool, url, strlen(url), enc_path, 0,
66 return HTTP_BAD_REQUEST;
68 r->filename = apr_pstrcat(r->pool, "proxy:balancer://", host,
69 "/", path, (search) ? "?" : "", (search) ? search : "", NULL);
71 r->path_info = apr_pstrcat(r->pool, "/", path, NULL);
76 static int init_balancer_members(proxy_server_conf *conf, server_rec *s,
77 proxy_balancer *balancer)
80 proxy_worker *workers;
82 workers = (proxy_worker *)balancer->workers->elts;
84 for (i = 0; i < balancer->workers->nelts; i++) {
85 int worker_is_initialized;
86 worker_is_initialized = PROXY_WORKER_IS_INITIALIZED(workers);
87 if (!worker_is_initialized) {
88 proxy_worker_stat *slot;
90 * If the worker is not initialized check whether its scoreboard
91 * slot is already initialized.
93 slot = (proxy_worker_stat *) ap_get_scoreboard_lb(workers->id);
95 worker_is_initialized = slot->status & PROXY_WORKER_INITIALIZED;
98 worker_is_initialized = 0;
101 ap_proxy_initialize_worker_share(conf, workers, s);
102 ap_proxy_initialize_worker(workers, s);
103 if (!worker_is_initialized) {
104 /* Set to the original configuration */
105 workers->s->lbstatus = workers->s->lbfactor =
106 (workers->lbfactor ? workers->lbfactor : 1);
107 workers->s->lbset = workers->lbset;
112 /* Set default number of attempts to the number of
115 if (!balancer->max_attempts_set && balancer->workers->nelts > 1) {
116 balancer->max_attempts = balancer->workers->nelts - 1;
117 balancer->max_attempts_set = 1;
122 /* Retrieve the parameter with the given name
123 * Something like 'JSESSIONID=12345...N'
125 static char *get_path_param(apr_pool_t *pool, char *url,
130 for (path = strstr(url, name); path; path = strstr(path + 1, name)) {
131 path += strlen(name);
134 * Session path was found, get it's value
139 path = apr_strtok(apr_pstrdup(pool, path), "?&", &q);
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,
185 const char *route, request_rec *r)
188 int checking_standby;
191 proxy_worker *worker;
193 checking_standby = checked_standby = 0;
194 while (!checked_standby) {
195 worker = (proxy_worker *)balancer->workers->elts;
196 for (i = 0; i < balancer->workers->nelts; i++, worker++) {
197 if ( (checking_standby ? !PROXY_WORKER_IS_STANDBY(worker) : PROXY_WORKER_IS_STANDBY(worker)) )
199 if (*(worker->s->route) && strcmp(worker->s->route, route) == 0) {
200 if (worker && PROXY_WORKER_IS_USABLE(worker)) {
204 * If the worker is in error state run
205 * retry on that worker. It will be marked as
206 * operational if the retry timeout is elapsed.
207 * The worker might still be unusable, but we try
210 ap_proxy_retry_worker("BALANCER", worker, r->server);
211 if (PROXY_WORKER_IS_USABLE(worker)) {
215 * We have a worker that is unusable.
216 * It can be in error or disabled, but in case
217 * it has a redirection set use that redirection worker.
218 * This enables to safely remove the member from the
219 * balancer. Of course you will need some kind of
220 * session replication between those two remote.
222 if (*worker->s->redirect) {
223 proxy_worker *rworker = NULL;
224 rworker = find_route_worker(balancer, worker->s->redirect, r);
225 /* Check if the redirect worker is usable */
226 if (rworker && !PROXY_WORKER_IS_USABLE(rworker)) {
228 * If the worker is in error state run
229 * retry on that worker. It will be marked as
230 * operational if the retry timeout is elapsed.
231 * The worker might still be unusable, but we try
234 ap_proxy_retry_worker("BALANCER", rworker, r->server);
236 if (rworker && PROXY_WORKER_IS_USABLE(rworker))
243 checked_standby = checking_standby++;
248 static proxy_worker *find_session_route(proxy_balancer *balancer,
251 const char **sticky_used,
254 proxy_worker *worker = NULL;
256 if (!balancer->sticky)
258 /* Try to find the sticky route inside url */
259 *route = get_path_param(r->pool, *url, balancer->sticky_path);
261 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
262 "proxy: BALANCER: Found value %s for "
263 "stickysession %s", *route, balancer->sticky_path);
264 *sticky_used = balancer->sticky_path;
267 *route = get_cookie_param(r, balancer->sticky);
269 *sticky_used = balancer->sticky;
270 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
271 "proxy: BALANCER: Found value %s for "
272 "stickysession %s", *route, balancer->sticky);
276 * If we found a value for sticksession, find the first '.' within.
277 * Everything after '.' (if present) is our route.
279 if ((*route) && ((*route = strchr(*route, '.')) != NULL ))
281 if ((*route) && (**route)) {
282 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
283 "proxy: BALANCER: Found route %s", *route);
284 /* We have a route in path or in cookie
285 * Find the worker that has this route defined.
287 worker = find_route_worker(balancer, *route, r);
288 if (worker && strcmp(*route, worker->s->route)) {
290 * Notice that the route of the worker chosen is different from
291 * the route supplied by the client.
293 apr_table_setn(r->subprocess_env, "BALANCER_ROUTE_CHANGED", "1");
294 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
295 "proxy: BALANCER: Route changed from %s to %s",
296 *route, worker->s->route);
304 static proxy_worker *find_best_worker(proxy_balancer *balancer,
307 proxy_worker *candidate = NULL;
310 if ((rv = PROXY_THREAD_LOCK(balancer)) != APR_SUCCESS) {
311 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
312 "proxy: BALANCER: (%s). Lock failed for find_best_worker()", balancer->name);
316 candidate = (*balancer->lbmethod->finder)(balancer, r);
319 candidate->s->elected++;
322 PROXY_THREAD_UNLOCK(balancer);
326 if ((rv = PROXY_THREAD_UNLOCK(balancer)) != APR_SUCCESS) {
327 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
328 "proxy: BALANCER: (%s). Unlock failed for find_best_worker()", balancer->name);
331 if (candidate == NULL) {
332 /* All the workers are in error state or disabled.
333 * If the balancer has a timeout sleep for a while
334 * and try again to find the worker. The chances are
335 * that some other thread will release a connection.
336 * By default the timeout is not set, and the server
337 * returns SERVER_BUSY.
340 if (balancer->timeout) {
341 /* XXX: This can perhaps be build using some
342 * smarter mechanism, like tread_cond.
343 * But since the statuses can came from
344 * different childs, use the provided algo.
346 apr_interval_time_t timeout = balancer->timeout;
347 apr_interval_time_t step, tval = 0;
348 /* Set the timeout to 0 so that we don't
349 * end in infinite loop
351 balancer->timeout = 0;
352 step = timeout / 100;
353 while (tval < timeout) {
356 if ((candidate = find_best_worker(balancer, r)))
360 /* restore the timeout */
361 balancer->timeout = timeout;
368 static int rewrite_url(request_rec *r, proxy_worker *worker,
371 const char *scheme = strstr(*url, "://");
372 const char *path = NULL;
375 path = ap_strchr_c(scheme + 3, '/');
377 /* we break the URL into host, port, uri */
379 return ap_proxyerror(r, HTTP_BAD_REQUEST, apr_pstrcat(r->pool,
380 "missing worker. URI cannot be parsed: ", *url,
384 *url = apr_pstrcat(r->pool, worker->name, path, NULL);
389 static void force_recovery(proxy_balancer *balancer, server_rec *s)
393 proxy_worker *worker;
395 worker = (proxy_worker *)balancer->workers->elts;
396 for (i = 0; i < balancer->workers->nelts; i++, worker++) {
397 if (!(worker->s->status & PROXY_WORKER_IN_ERROR)) {
403 /* If all workers are in error state force the recovery.
405 worker = (proxy_worker *)balancer->workers->elts;
406 for (i = 0; i < balancer->workers->nelts; i++, worker++) {
407 ++worker->s->retries;
408 worker->s->status &= ~PROXY_WORKER_IN_ERROR;
409 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
410 "proxy: BALANCER: (%s). Forcing recovery for worker (%s)",
411 balancer->name, worker->hostname);
416 static int proxy_balancer_pre_request(proxy_worker **worker,
417 proxy_balancer **balancer,
419 proxy_server_conf *conf, char **url)
422 proxy_worker *runtime;
424 const char *sticky = NULL;
428 /* Step 1: check if the url is for us
429 * The url we can handle starts with 'balancer://'
430 * If balancer is already provided skip the search
431 * for balancer, because this is failover attempt.
434 !(*balancer = ap_proxy_get_balancer(r->pool, conf, *url)))
437 /* Step 2: Lock the LoadBalancer
438 * XXX: perhaps we need the process lock here
440 if ((rv = PROXY_THREAD_LOCK(*balancer)) != APR_SUCCESS) {
441 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
442 "proxy: BALANCER: (%s). Lock failed for pre_request",
447 /* Step 3: force recovery */
448 force_recovery(*balancer, r->server);
450 /* Step 4: find the session route */
451 runtime = find_session_route(*balancer, r, &route, &sticky, url);
453 int i, total_factor = 0;
454 proxy_worker *workers;
455 /* We have a sticky load balancer
456 * Update the workers status
457 * so that even session routes get
460 workers = (proxy_worker *)(*balancer)->workers->elts;
461 for (i = 0; i < (*balancer)->workers->nelts; i++) {
462 /* Take into calculation only the workers that are
463 * not in error state or not disabled.
465 * TODO: Abstract the below, since this is dependent
466 * on the LB implementation
468 if (PROXY_WORKER_IS_USABLE(workers)) {
469 workers->s->lbstatus += workers->s->lbfactor;
470 total_factor += workers->s->lbfactor;
474 runtime->s->lbstatus -= total_factor;
475 runtime->s->elected++;
479 else if (route && (*balancer)->sticky_force) {
480 int i, member_of = 0;
481 proxy_worker *workers;
483 * We have a route provided that doesn't match the
484 * balancer name. See if the provider route is the
485 * member of the same balancer in which case return 503
487 workers = (proxy_worker *)(*balancer)->workers->elts;
488 for (i = 0; i < (*balancer)->workers->nelts; i++) {
489 if (*(workers->s->route) && strcmp(workers->s->route, route) == 0) {
496 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
497 "proxy: BALANCER: (%s). All workers are in error state for route (%s)",
498 (*balancer)->name, route);
499 if ((rv = PROXY_THREAD_UNLOCK(*balancer)) != APR_SUCCESS) {
500 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
501 "proxy: BALANCER: (%s). Unlock failed for pre_request",
504 return HTTP_SERVICE_UNAVAILABLE;
508 if ((rv = PROXY_THREAD_UNLOCK(*balancer)) != APR_SUCCESS) {
509 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
510 "proxy: BALANCER: (%s). Unlock failed for pre_request",
514 runtime = find_best_worker(*balancer, r);
516 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
517 "proxy: BALANCER: (%s). All workers are in error state",
520 return HTTP_SERVICE_UNAVAILABLE;
522 if ((*balancer)->sticky && runtime) {
524 * This balancer has sticky sessions and the client either has not
525 * supplied any routing information or all workers for this route
526 * including possible redirect and hotstandby workers are in error
527 * state, but we have found another working worker for this
528 * balancer where we can send the request. Thus notice that we have
529 * changed the route to the backend.
531 apr_table_setn(r->subprocess_env, "BALANCER_ROUTE_CHANGED", "1");
536 /* Add balancer/worker info to env. */
537 apr_table_setn(r->subprocess_env,
538 "BALANCER_NAME", (*balancer)->name);
539 apr_table_setn(r->subprocess_env,
540 "BALANCER_WORKER_NAME", (*worker)->name);
541 apr_table_setn(r->subprocess_env,
542 "BALANCER_WORKER_ROUTE", (*worker)->s->route);
544 /* Rewrite the url from 'balancer://url'
545 * to the 'worker_scheme://worker_hostname[:worker_port]/url'
546 * This replaces the balancers fictional name with the
547 * real hostname of the elected worker.
549 access_status = rewrite_url(r, *worker, url);
550 /* Add the session route to request notes if present */
552 apr_table_setn(r->notes, "session-sticky", sticky);
553 apr_table_setn(r->notes, "session-route", route);
555 /* Add session info to env. */
556 apr_table_setn(r->subprocess_env,
557 "BALANCER_SESSION_STICKY", sticky);
558 apr_table_setn(r->subprocess_env,
559 "BALANCER_SESSION_ROUTE", route);
561 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
562 "proxy: BALANCER (%s) worker (%s) rewritten to %s",
563 (*balancer)->name, (*worker)->name, *url);
565 return access_status;
568 static int proxy_balancer_post_request(proxy_worker *worker,
569 proxy_balancer *balancer,
571 proxy_server_conf *conf)
577 if ((rv = PROXY_THREAD_LOCK(balancer)) != APR_SUCCESS) {
578 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
579 "proxy: BALANCER: (%s). Lock failed for post_request",
581 return HTTP_INTERNAL_SERVER_ERROR;
583 /* TODO: placeholder for post_request actions
586 if ((rv = PROXY_THREAD_UNLOCK(balancer)) != APR_SUCCESS) {
587 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
588 "proxy: BALANCER: (%s). Unlock failed for post_request",
591 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
592 "proxy_balancer_post_request for (%s)", balancer->name);
599 static void recalc_factors(proxy_balancer *balancer)
602 proxy_worker *workers;
605 /* Recalculate lbfactors */
606 workers = (proxy_worker *)balancer->workers->elts;
607 /* Special case if there is only one worker it's
608 * load factor will always be 1
610 if (balancer->workers->nelts == 1) {
611 workers->s->lbstatus = workers->s->lbfactor = 1;
614 for (i = 0; i < balancer->workers->nelts; i++) {
615 /* Update the status entries */
616 workers[i].s->lbstatus = workers[i].s->lbfactor;
620 /* Manages the loadfactors and member status
622 static int balancer_handler(request_rec *r)
624 void *sconf = r->server->module_config;
625 proxy_server_conf *conf = (proxy_server_conf *)
626 ap_get_module_config(sconf, &proxy_module);
627 proxy_balancer *balancer, *bsel = NULL;
628 proxy_worker *worker, *wsel = NULL;
629 apr_table_t *params = apr_table_make(r->pool, 10);
634 /* is this for us? */
635 if (strcmp(r->handler, "balancer-manager"))
637 r->allowed = (AP_METHOD_BIT << M_GET);
638 if (r->method_number != M_GET)
642 char *args = apr_pstrdup(r->pool, r->args);
644 while (args && *args) {
645 if ((val = ap_strchr(args, '='))) {
647 if ((tok = ap_strchr(val, '&')))
650 * Special case: workers are allowed path information
652 if ((access_status = ap_unescape_url(val)) != OK)
653 if (strcmp(args, "w") || (access_status != HTTP_NOT_FOUND))
654 return access_status;
655 apr_table_setn(params, args, val);
659 return HTTP_BAD_REQUEST;
662 if ((name = apr_table_get(params, "b")))
663 bsel = ap_proxy_get_balancer(r->pool, conf,
664 apr_pstrcat(r->pool, "balancer://", name, NULL));
665 if ((name = apr_table_get(params, "w"))) {
668 ws = ap_proxy_get_worker(r->pool, conf, name);
670 worker = (proxy_worker *)bsel->workers->elts;
671 for (n = 0; n < bsel->workers->nelts; n++) {
672 if (strcasecmp(worker->name, ws->name) == 0) {
680 /* First set the params */
682 * Note that it is not possible set the proxy_balancer because it is not
687 if ((val = apr_table_get(params, "lf"))) {
688 int ival = atoi(val);
689 if (ival >= 1 && ival <= 100) {
690 wsel->s->lbfactor = ival;
692 recalc_factors(bsel);
695 if ((val = apr_table_get(params, "wr"))) {
696 if (strlen(val) && strlen(val) < PROXY_WORKER_MAX_ROUTE_SIZ)
697 strcpy(wsel->s->route, val);
699 *wsel->s->route = '\0';
701 if ((val = apr_table_get(params, "rr"))) {
702 if (strlen(val) && strlen(val) < PROXY_WORKER_MAX_ROUTE_SIZ)
703 strcpy(wsel->s->redirect, val);
705 *wsel->s->redirect = '\0';
707 if ((val = apr_table_get(params, "dw"))) {
708 if (!strcasecmp(val, "Disable"))
709 wsel->s->status |= PROXY_WORKER_DISABLED;
710 else if (!strcasecmp(val, "Enable"))
711 wsel->s->status &= ~PROXY_WORKER_DISABLED;
713 if ((val = apr_table_get(params, "ls"))) {
714 int ival = atoi(val);
715 if (ival >= 0 && ival <= 99) {
716 wsel->s->lbset = ival;
721 if (apr_table_get(params, "xml")) {
722 ap_set_content_type(r, "text/xml");
723 ap_rputs("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n", r);
724 ap_rputs("<httpd:manager xmlns:httpd=\"http://httpd.apache.org\">\n", r);
725 ap_rputs(" <httpd:balancers>\n", r);
726 balancer = (proxy_balancer *)conf->balancers->elts;
727 for (i = 0; i < conf->balancers->nelts; i++) {
728 ap_rputs(" <httpd:balancer>\n", r);
729 ap_rvputs(r, " <httpd:name>", balancer->name, "</httpd:name>\n", NULL);
730 ap_rputs(" <httpd:workers>\n", r);
731 worker = (proxy_worker *)balancer->workers->elts;
732 for (n = 0; n < balancer->workers->nelts; n++) {
733 ap_rputs(" <httpd:worker>\n", r);
734 ap_rvputs(r, " <httpd:scheme>", worker->scheme,
735 "</httpd:scheme>\n", NULL);
736 ap_rvputs(r, " <httpd:hostname>", worker->hostname,
737 "</httpd:hostname>\n", NULL);
738 ap_rprintf(r, " <httpd:loadfactor>%d</httpd:loadfactor>\n",
739 worker->s->lbfactor);
740 ap_rputs(" </httpd:worker>\n", r);
743 ap_rputs(" </httpd:workers>\n", r);
744 ap_rputs(" </httpd:balancer>\n", r);
747 ap_rputs(" </httpd:balancers>\n", r);
748 ap_rputs("</httpd:manager>", r);
751 ap_set_content_type(r, "text/html; charset=ISO-8859-1");
752 ap_rputs(DOCTYPE_HTML_3_2
753 "<html><head><title>Balancer Manager</title></head>\n", r);
754 ap_rputs("<body><h1>Load Balancer Manager for ", r);
755 ap_rvputs(r, ap_get_server_name(r), "</h1>\n\n", NULL);
756 ap_rvputs(r, "<dl><dt>Server Version: ",
757 ap_get_server_description(), "</dt>\n", NULL);
758 ap_rvputs(r, "<dt>Server Built: ",
759 ap_get_server_built(), "\n</dt></dl>\n", NULL);
760 balancer = (proxy_balancer *)conf->balancers->elts;
761 for (i = 0; i < conf->balancers->nelts; i++) {
763 ap_rputs("<hr />\n<h3>LoadBalancer Status for ", r);
764 ap_rvputs(r, balancer->name, "</h3>\n\n", NULL);
765 ap_rputs("\n\n<table border=\"0\" style=\"text-align: left;\"><tr>"
766 "<th>StickySession</th><th>Timeout</th><th>FailoverAttempts</th><th>Method</th>"
768 if (balancer->sticky) {
769 if (strcmp(balancer->sticky, balancer->sticky_path)) {
770 ap_rvputs(r, "<td>", balancer->sticky, " | ",
771 balancer->sticky_path, NULL);
774 ap_rvputs(r, "<td>", balancer->sticky, NULL);
778 ap_rputs("<td> - ", r);
780 ap_rprintf(r, "</td><td>%" APR_TIME_T_FMT "</td>",
781 apr_time_sec(balancer->timeout));
782 ap_rprintf(r, "<td>%d</td>\n", balancer->max_attempts);
783 ap_rprintf(r, "<td>%s</td>\n",
784 balancer->lbmethod->name);
785 ap_rputs("</table>\n<br />", r);
786 ap_rputs("\n\n<table border=\"0\" style=\"text-align: left;\"><tr>"
787 "<th>Worker URL</th>"
788 "<th>Route</th><th>RouteRedir</th>"
789 "<th>Factor</th><th>Set</th><th>Status</th>"
790 "<th>Elected</th><th>To</th><th>From</th>"
793 worker = (proxy_worker *)balancer->workers->elts;
794 for (n = 0; n < balancer->workers->nelts; n++) {
796 ap_rvputs(r, "<tr>\n<td><a href=\"", r->uri, "?b=",
797 balancer->name + sizeof("balancer://") - 1, "&w=",
798 ap_escape_uri(r->pool, worker->name),
800 ap_rvputs(r, worker->name, "</a></td>", NULL);
801 ap_rvputs(r, "<td>", ap_escape_html(r->pool, worker->s->route),
803 ap_rvputs(r, "</td><td>",
804 ap_escape_html(r->pool, worker->s->redirect), NULL);
805 ap_rprintf(r, "</td><td>%d</td>", worker->s->lbfactor);
806 ap_rprintf(r, "<td>%d</td><td>", worker->s->lbset);
807 if (worker->s->status & PROXY_WORKER_DISABLED)
809 if (worker->s->status & PROXY_WORKER_IN_ERROR)
811 if (worker->s->status & PROXY_WORKER_STOPPED)
812 ap_rputs("Stop ", r);
813 if (worker->s->status & PROXY_WORKER_HOT_STANDBY)
814 ap_rputs("Stby ", r);
815 if (PROXY_WORKER_IS_USABLE(worker))
817 if (!PROXY_WORKER_IS_INITIALIZED(worker))
819 ap_rputs("</td>", r);
820 ap_rprintf(r, "<td>%" APR_SIZE_T_FMT "</td><td>", worker->s->elected);
821 ap_rputs(apr_strfsize(worker->s->transferred, fbuf), r);
822 ap_rputs("</td><td>", r);
823 ap_rputs(apr_strfsize(worker->s->read, fbuf), r);
824 ap_rputs("</td></tr>\n", r);
828 ap_rputs("</table>\n", r);
831 ap_rputs("<hr />\n", r);
833 ap_rputs("<h3>Edit worker settings for ", r);
834 ap_rvputs(r, wsel->name, "</h3>\n", NULL);
835 ap_rvputs(r, "<form method=\"GET\" action=\"", NULL);
836 ap_rvputs(r, r->uri, "\">\n<dl>", NULL);
837 ap_rputs("<table><tr><td>Load factor:</td><td><input name=\"lf\" type=text ", r);
838 ap_rprintf(r, "value=\"%d\"></td></tr>\n", wsel->s->lbfactor);
839 ap_rputs("<tr><td>LB Set:</td><td><input name=\"ls\" type=text ", r);
840 ap_rprintf(r, "value=\"%d\"></td></tr>\n", wsel->s->lbset);
841 ap_rputs("<tr><td>Route:</td><td><input name=\"wr\" type=text ", r);
842 ap_rvputs(r, "value=\"", ap_escape_html(r->pool, wsel->s->route),
844 ap_rputs("\"></td></tr>\n", r);
845 ap_rputs("<tr><td>Route Redirect:</td><td><input name=\"rr\" type=text ", r);
846 ap_rvputs(r, "value=\"", ap_escape_html(r->pool, wsel->s->redirect),
848 ap_rputs("\"></td></tr>\n", r);
849 ap_rputs("<tr><td>Status:</td><td>Disabled: <input name=\"dw\" value=\"Disable\" type=radio", r);
850 if (wsel->s->status & PROXY_WORKER_DISABLED)
851 ap_rputs(" checked", r);
852 ap_rputs("> | Enabled: <input name=\"dw\" value=\"Enable\" type=radio", r);
853 if (!(wsel->s->status & PROXY_WORKER_DISABLED))
854 ap_rputs(" checked", r);
855 ap_rputs("></td></tr>\n", r);
856 ap_rputs("<tr><td colspan=2><input type=submit value=\"Submit\"></td></tr>\n", r);
857 ap_rvputs(r, "</table>\n<input type=hidden name=\"w\" ", NULL);
858 ap_rvputs(r, "value=\"", ap_escape_uri(r->pool, wsel->name), "\">\n", NULL);
859 ap_rvputs(r, "<input type=hidden name=\"b\" ", NULL);
860 ap_rvputs(r, "value=\"", bsel->name + sizeof("balancer://") - 1,
861 "\">\n</form>\n", NULL);
862 ap_rputs("<hr />\n", r);
864 ap_rputs(ap_psignature("",r), r);
865 ap_rputs("</body></html>\n", r);
870 static void child_init(apr_pool_t *p, server_rec *s)
873 void *sconf = s->module_config;
874 proxy_server_conf *conf;
875 proxy_balancer *balancer;
877 conf = (proxy_server_conf *)ap_get_module_config(sconf, &proxy_module);
879 /* Initialize shared scoreboard data */
880 balancer = (proxy_balancer *)conf->balancers->elts;
881 for (i = 0; i < conf->balancers->nelts; i++) {
882 init_balancer_members(conf, s, balancer);
891 * The idea behind the find_best_byrequests scheduler is the following:
893 * lbfactor is "how much we expect this worker to work", or "the worker's
894 * normalized work quota".
896 * lbstatus is "how urgent this worker has to work to fulfill its quota
899 * We distribute each worker's work quota to the worker, and then look
900 * which of them needs to work most urgently (biggest lbstatus). This
901 * worker is then selected for work, and its lbstatus reduced by the
902 * total work quota we distributed to all workers. Thus the sum of all
903 * lbstatus does not change.(*)
905 * If some workers are disabled, the others will
906 * still be scheduled correctly.
908 * If a balancer is configured as follows:
911 * lbfactor 25 25 25 25
913 * And b gets disabled, the following schedule is produced:
915 * a c d a c d a c d ...
917 * Note that the above lbfactor setting is the *exact* same as:
922 * Asymmetric configurations work as one would expect. For
928 * would have a, b and c all handling about the same
929 * amount of load with d handling twice what a or b
930 * or c handles individually. So we could see:
932 * b a d c d a c d b d ...
936 static proxy_worker *find_best_byrequests(proxy_balancer *balancer,
940 int total_factor = 0;
941 proxy_worker *worker;
942 proxy_worker *mycandidate = NULL;
945 int checking_standby;
948 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
949 "proxy: Entering byrequests for BALANCER (%s)",
952 /* First try to see if we have available candidate */
954 checking_standby = checked_standby = 0;
955 while (!mycandidate && !checked_standby) {
956 worker = (proxy_worker *)balancer->workers->elts;
957 for (i = 0; i < balancer->workers->nelts; i++, worker++) {
958 if (!checking_standby) { /* first time through */
959 if (worker->s->lbset > max_lbset)
960 max_lbset = worker->s->lbset;
962 if (worker->s->lbset > cur_lbset)
964 if ( (checking_standby ? !PROXY_WORKER_IS_STANDBY(worker) : PROXY_WORKER_IS_STANDBY(worker)) )
966 /* If the worker is in error state run
967 * retry on that worker. It will be marked as
968 * operational if the retry timeout is elapsed.
969 * The worker might still be unusable, but we try
972 if (!PROXY_WORKER_IS_USABLE(worker))
973 ap_proxy_retry_worker("BALANCER", worker, r->server);
974 /* Take into calculation only the workers that are
975 * not in error state or not disabled.
977 if (PROXY_WORKER_IS_USABLE(worker)) {
978 worker->s->lbstatus += worker->s->lbfactor;
979 total_factor += worker->s->lbfactor;
980 if (!mycandidate || worker->s->lbstatus > mycandidate->s->lbstatus)
981 mycandidate = worker;
984 checked_standby = checking_standby++;
987 } while (cur_lbset <= max_lbset && !mycandidate);
990 mycandidate->s->lbstatus -= total_factor;
997 * The idea behind the find_best_bytraffic scheduler is the following:
999 * We know the amount of traffic (bytes in and out) handled by each
1000 * worker. We normalize that traffic by each workers' weight. So assuming
1006 * the scheduler will allow worker c to handle 3 times the
1007 * traffic of a and b. If each request/response results in the
1008 * same amount of traffic, then c would be accessed 3 times as
1009 * often as a or b. If, for example, a handled a request that
1010 * resulted in a large i/o bytecount, then b and c would be
1011 * chosen more often, to even things out.
1013 static proxy_worker *find_best_bytraffic(proxy_balancer *balancer,
1017 apr_off_t mytraffic = 0;
1018 apr_off_t curmin = 0;
1019 proxy_worker *worker;
1020 proxy_worker *mycandidate = NULL;
1023 int checking_standby;
1024 int checked_standby;
1026 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1027 "proxy: Entering bytraffic for BALANCER (%s)",
1030 /* First try to see if we have available candidate */
1032 checking_standby = checked_standby = 0;
1033 while (!mycandidate && !checked_standby) {
1034 worker = (proxy_worker *)balancer->workers->elts;
1035 for (i = 0; i < balancer->workers->nelts; i++, worker++) {
1036 if (!checking_standby) { /* first time through */
1037 if (worker->s->lbset > max_lbset)
1038 max_lbset = worker->s->lbset;
1040 if (worker->s->lbset > cur_lbset)
1042 if ( (checking_standby ? !PROXY_WORKER_IS_STANDBY(worker) : PROXY_WORKER_IS_STANDBY(worker)) )
1044 /* If the worker is in error state run
1045 * retry on that worker. It will be marked as
1046 * operational if the retry timeout is elapsed.
1047 * The worker might still be unusable, but we try
1050 if (!PROXY_WORKER_IS_USABLE(worker))
1051 ap_proxy_retry_worker("BALANCER", worker, r->server);
1052 /* Take into calculation only the workers that are
1053 * not in error state or not disabled.
1055 if (PROXY_WORKER_IS_USABLE(worker)) {
1056 mytraffic = (worker->s->transferred/worker->s->lbfactor) +
1057 (worker->s->read/worker->s->lbfactor);
1058 if (!mycandidate || mytraffic < curmin) {
1059 mycandidate = worker;
1064 checked_standby = checking_standby++;
1067 } while (cur_lbset <= max_lbset && !mycandidate);
1073 * How to add additional lbmethods:
1074 * 1. Create func which determines "best" candidate worker
1075 * (eg: find_best_bytraffic, above)
1076 * 2. Register it as a provider.
1078 static const proxy_balancer_method byrequests =
1081 &find_best_byrequests,
1085 static const proxy_balancer_method bytraffic =
1088 &find_best_bytraffic,
1092 static void ap_proxy_balancer_register_hook(apr_pool_t *p)
1094 /* Only the mpm_winnt has child init hook handler.
1095 * make sure that we are called after the mpm
1096 * initializes and after the mod_proxy
1098 static const char *const aszPred[] = { "mpm_winnt.c", "mod_proxy.c", NULL};
1099 /* manager handler */
1100 ap_hook_handler(balancer_handler, NULL, NULL, APR_HOOK_FIRST);
1101 ap_hook_child_init(child_init, aszPred, NULL, APR_HOOK_MIDDLE);
1102 proxy_hook_pre_request(proxy_balancer_pre_request, NULL, NULL, APR_HOOK_FIRST);
1103 proxy_hook_post_request(proxy_balancer_post_request, NULL, NULL, APR_HOOK_FIRST);
1104 proxy_hook_canon_handler(proxy_balancer_canon, NULL, NULL, APR_HOOK_FIRST);
1105 ap_register_provider(p, PROXY_LBMETHOD, "bytraffic", "0", &bytraffic);
1106 ap_register_provider(p, PROXY_LBMETHOD, "byrequests", "0", &byrequests);
1109 module AP_MODULE_DECLARE_DATA proxy_balancer_module = {
1110 STANDARD20_MODULE_STUFF,
1111 NULL, /* create per-directory config structure */
1112 NULL, /* merge per-directory config structures */
1113 NULL, /* create per-server config structure */
1114 NULL, /* merge per-server config structures */
1115 NULL, /* command apr_table_t */
1116 ap_proxy_balancer_register_hook /* register hooks */