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 */
21 #include "mod_proxy.h"
22 #include "scoreboard.h"
24 #include "apr_version.h"
25 #include "apr_hooks.h"
27 module AP_MODULE_DECLARE_DATA proxy_balancer_module;
29 static int proxy_balancer_canon(request_rec *r, char *url)
31 char *host, *path, *search;
35 if (strncasecmp(url, "balancer:", 9) == 0) {
42 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
43 "proxy: BALANCER: canonicalising URL %s", url);
46 * We break the URL into host, port, path, search
48 err = ap_proxy_canon_netloc(r->pool, &url, NULL, NULL, &host, &port);
50 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
51 "error parsing URL %s: %s",
53 return HTTP_BAD_REQUEST;
55 /* now parse path/search args, according to rfc1738 */
56 /* N.B. if this isn't a true proxy request, then the URL _path_
57 * has already been decoded. True proxy requests have r->uri
58 * == r->unparsed_uri, and no others have that property.
60 if (r->uri == r->unparsed_uri) {
61 search = strchr(url, '?');
69 path = ap_proxy_canonenc(r->pool, url, strlen(url), enc_path, 0, r->proxyreq);
71 return HTTP_BAD_REQUEST;
73 r->filename = apr_pstrcat(r->pool, "proxy:balancer://", host,
74 "/", path, (search) ? "?" : "", (search) ? search : "", NULL);
76 r->path_info = apr_pstrcat(r->pool, "/", path, 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 int worker_is_initialized;
91 worker_is_initialized = PROXY_WORKER_IS_INITIALIZED(workers);
92 if (!worker_is_initialized) {
93 proxy_worker_stat *slot;
95 * If the worker is not initialized check whether its scoreboard
96 * slot is already initialized.
98 slot = (proxy_worker_stat *) ap_get_scoreboard_lb(workers->id);
100 worker_is_initialized = slot->status & PROXY_WORKER_INITIALIZED;
103 worker_is_initialized = 0;
106 ap_proxy_initialize_worker_share(conf, workers, s);
107 ap_proxy_initialize_worker(workers, s);
108 if (!worker_is_initialized) {
109 /* Set to the original configuration */
110 workers->s->lbstatus = workers->s->lbfactor =
111 (workers->lbfactor ? workers->lbfactor : 1);
112 workers->s->lbset = workers->lbset;
117 /* Set default number of attempts to the number of
120 if (!balancer->max_attempts_set && balancer->workers->nelts > 1) {
121 balancer->max_attempts = balancer->workers->nelts - 1;
122 balancer->max_attempts_set = 1;
127 /* Retrieve the parameter with the given name
128 * Something like 'JSESSIONID=12345...N'
130 static char *get_path_param(apr_pool_t *pool, char *url,
135 for (path = strstr(url, name); path; path = strstr(path + 1, name)) {
136 path += strlen(name);
139 * Session path was found, get it's value
144 path = apr_strtok(apr_pstrdup(pool, path), "?&", &q);
152 static char *get_cookie_param(request_rec *r, const char *name)
155 const char *start_cookie;
157 if ((cookies = apr_table_get(r->headers_in, "Cookie"))) {
158 for (start_cookie = ap_strstr_c(cookies, name); start_cookie;
159 start_cookie = ap_strstr_c(start_cookie + 1, name)) {
160 if (start_cookie == cookies ||
161 start_cookie[-1] == ';' ||
162 start_cookie[-1] == ',' ||
163 isspace(start_cookie[-1])) {
165 start_cookie += strlen(name);
166 while(*start_cookie && isspace(*start_cookie))
168 if (*start_cookie == '=' && start_cookie[1]) {
170 * Session cookie was found, get it's value
172 char *end_cookie, *cookie;
174 cookie = apr_pstrdup(r->pool, start_cookie);
175 if ((end_cookie = strchr(cookie, ';')) != NULL)
177 if((end_cookie = strchr(cookie, ',')) != NULL)
187 /* Find the worker that has the 'route' defined
189 static proxy_worker *find_route_worker(proxy_balancer *balancer,
190 const char *route, request_rec *r)
193 int checking_standby;
196 proxy_worker *worker;
198 checking_standby = checked_standby = 0;
199 while (!checked_standby) {
200 worker = (proxy_worker *)balancer->workers->elts;
201 for (i = 0; i < balancer->workers->nelts; i++, worker++) {
202 if ( (checking_standby ? !PROXY_WORKER_IS_STANDBY(worker) : PROXY_WORKER_IS_STANDBY(worker)) )
204 if (*(worker->s->route) && strcmp(worker->s->route, route) == 0) {
205 if (worker && PROXY_WORKER_IS_USABLE(worker)) {
209 * If the worker is in error state run
210 * retry on that worker. It will be marked as
211 * operational if the retry timeout is elapsed.
212 * The worker might still be unusable, but we try
215 ap_proxy_retry_worker("BALANCER", worker, r->server);
216 if (PROXY_WORKER_IS_USABLE(worker)) {
220 * We have a worker that is unusable.
221 * It can be in error or disabled, but in case
222 * it has a redirection set use that redirection worker.
223 * This enables to safely remove the member from the
224 * balancer. Of course you will need some kind of
225 * session replication between those two remote.
227 if (*worker->s->redirect) {
228 proxy_worker *rworker = NULL;
229 rworker = find_route_worker(balancer, worker->s->redirect, r);
230 /* Check if the redirect worker is usable */
231 if (rworker && !PROXY_WORKER_IS_USABLE(rworker)) {
233 * If the worker is in error state run
234 * retry on that worker. It will be marked as
235 * operational if the retry timeout is elapsed.
236 * The worker might still be unusable, but we try
239 ap_proxy_retry_worker("BALANCER", rworker, r->server);
241 if (rworker && PROXY_WORKER_IS_USABLE(rworker))
248 checked_standby = checking_standby++;
253 static proxy_worker *find_session_route(proxy_balancer *balancer,
256 const char **sticky_used,
259 proxy_worker *worker = NULL;
261 if (!balancer->sticky)
263 /* Try to find the sticky route inside url */
264 *route = get_path_param(r->pool, *url, balancer->sticky_path);
266 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
267 "proxy: BALANCER: Found value %s for "
268 "stickysession %s", *route, balancer->sticky_path);
269 *sticky_used = balancer->sticky_path;
272 *route = get_cookie_param(r, balancer->sticky);
274 *sticky_used = balancer->sticky;
275 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
276 "proxy: BALANCER: Found value %s for "
277 "stickysession %s", *route, balancer->sticky);
281 * If we found a value for sticksession, find the first '.' within.
282 * Everything after '.' (if present) is our route.
284 if ((*route) && ((*route = strchr(*route, '.')) != NULL ))
286 if ((*route) && (**route)) {
287 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
288 "proxy: BALANCER: Found route %s", *route);
289 /* We have a route in path or in cookie
290 * Find the worker that has this route defined.
292 worker = find_route_worker(balancer, *route, r);
293 if (worker && strcmp(*route, worker->s->route)) {
295 * Notice that the route of the worker chosen is different from
296 * the route supplied by the client.
298 apr_table_setn(r->subprocess_env, "BALANCER_ROUTE_CHANGED", "1");
299 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
300 "proxy: BALANCER: Route changed from %s to %s",
301 *route, worker->s->route);
309 static proxy_worker *find_best_worker(proxy_balancer *balancer,
312 proxy_worker *candidate = NULL;
315 if ((rv = PROXY_THREAD_LOCK(balancer)) != APR_SUCCESS) {
316 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
317 "proxy: BALANCER: (%s). Lock failed for find_best_worker()", balancer->name);
321 candidate = (*balancer->lbmethod->finder)(balancer, r);
324 candidate->s->elected++;
327 PROXY_THREAD_UNLOCK(balancer);
331 if ((rv = PROXY_THREAD_UNLOCK(balancer)) != APR_SUCCESS) {
332 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
333 "proxy: BALANCER: (%s). Unlock failed for find_best_worker()", balancer->name);
336 if (candidate == NULL) {
337 /* All the workers are in error state or disabled.
338 * If the balancer has a timeout sleep for a while
339 * and try again to find the worker. The chances are
340 * that some other thread will release a connection.
341 * By default the timeout is not set, and the server
342 * returns SERVER_BUSY.
345 if (balancer->timeout) {
346 /* XXX: This can perhaps be build using some
347 * smarter mechanism, like tread_cond.
348 * But since the statuses can came from
349 * different childs, use the provided algo.
351 apr_interval_time_t timeout = balancer->timeout;
352 apr_interval_time_t step, tval = 0;
353 /* Set the timeout to 0 so that we don't
354 * end in infinite loop
356 balancer->timeout = 0;
357 step = timeout / 100;
358 while (tval < timeout) {
361 if ((candidate = find_best_worker(balancer, r)))
365 /* restore the timeout */
366 balancer->timeout = timeout;
373 static int rewrite_url(request_rec *r, proxy_worker *worker,
376 const char *scheme = strstr(*url, "://");
377 const char *path = NULL;
380 path = ap_strchr_c(scheme + 3, '/');
382 /* we break the URL into host, port, uri */
384 return ap_proxyerror(r, HTTP_BAD_REQUEST, apr_pstrcat(r->pool,
385 "missing worker. URI cannot be parsed: ", *url,
389 *url = apr_pstrcat(r->pool, worker->name, path, NULL);
394 static void force_recovery(proxy_balancer *balancer, server_rec *s)
398 proxy_worker *worker;
400 worker = (proxy_worker *)balancer->workers->elts;
401 for (i = 0; i < balancer->workers->nelts; i++, worker++) {
402 if (!(worker->s->status & PROXY_WORKER_IN_ERROR)) {
408 /* If all workers are in error state force the recovery.
410 worker = (proxy_worker *)balancer->workers->elts;
411 for (i = 0; i < balancer->workers->nelts; i++, worker++) {
412 ++worker->s->retries;
413 worker->s->status &= ~PROXY_WORKER_IN_ERROR;
414 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
415 "proxy: BALANCER: (%s). Forcing recovery for worker (%s)",
416 balancer->name, worker->hostname);
421 static int proxy_balancer_pre_request(proxy_worker **worker,
422 proxy_balancer **balancer,
424 proxy_server_conf *conf, char **url)
427 proxy_worker *runtime;
429 const char *sticky = NULL;
433 /* Step 1: check if the url is for us
434 * The url we can handle starts with 'balancer://'
435 * If balancer is already provided skip the search
436 * for balancer, because this is failover attempt.
439 !(*balancer = ap_proxy_get_balancer(r->pool, conf, *url)))
442 /* Step 2: Lock the LoadBalancer
443 * XXX: perhaps we need the process lock here
445 if ((rv = PROXY_THREAD_LOCK(*balancer)) != APR_SUCCESS) {
446 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
447 "proxy: BALANCER: (%s). Lock failed for pre_request",
452 /* Step 3: force recovery */
453 force_recovery(*balancer, r->server);
455 /* Step 4: find the session route */
456 runtime = find_session_route(*balancer, r, &route, &sticky, url);
458 int i, total_factor = 0;
459 proxy_worker *workers;
460 /* We have a sticky load balancer
461 * Update the workers status
462 * so that even session routes get
465 workers = (proxy_worker *)(*balancer)->workers->elts;
466 for (i = 0; i < (*balancer)->workers->nelts; i++) {
467 /* Take into calculation only the workers that are
468 * not in error state or not disabled.
470 * TODO: Abstract the below, since this is dependent
471 * on the LB implementation
473 if (PROXY_WORKER_IS_USABLE(workers)) {
474 workers->s->lbstatus += workers->s->lbfactor;
475 total_factor += workers->s->lbfactor;
479 runtime->s->lbstatus -= total_factor;
480 runtime->s->elected++;
484 else if (route && (*balancer)->sticky_force) {
485 int i, member_of = 0;
486 proxy_worker *workers;
488 * We have a route provided that doesn't match the
489 * balancer name. See if the provider route is the
490 * member of the same balancer in which case return 503
492 workers = (proxy_worker *)(*balancer)->workers->elts;
493 for (i = 0; i < (*balancer)->workers->nelts; i++) {
494 if (*(workers->s->route) && strcmp(workers->s->route, route) == 0) {
501 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
502 "proxy: BALANCER: (%s). All workers are in error state for route (%s)",
503 (*balancer)->name, route);
504 if ((rv = PROXY_THREAD_UNLOCK(*balancer)) != APR_SUCCESS) {
505 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
506 "proxy: BALANCER: (%s). Unlock failed for pre_request",
509 return HTTP_SERVICE_UNAVAILABLE;
513 if ((rv = PROXY_THREAD_UNLOCK(*balancer)) != APR_SUCCESS) {
514 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
515 "proxy: BALANCER: (%s). Unlock failed for pre_request",
519 runtime = find_best_worker(*balancer, r);
521 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
522 "proxy: BALANCER: (%s). All workers are in error state",
525 return HTTP_SERVICE_UNAVAILABLE;
527 if ((*balancer)->sticky && runtime) {
529 * This balancer has sticky sessions and the client either has not
530 * supplied any routing information or all workers for this route
531 * including possible redirect and hotstandby workers are in error
532 * state, but we have found another working worker for this
533 * balancer where we can send the request. Thus notice that we have
534 * changed the route to the backend.
536 apr_table_setn(r->subprocess_env, "BALANCER_ROUTE_CHANGED", "1");
541 /* Add balancer/worker info to env. */
542 apr_table_setn(r->subprocess_env,
543 "BALANCER_NAME", (*balancer)->name);
544 apr_table_setn(r->subprocess_env,
545 "BALANCER_WORKER_NAME", (*worker)->name);
546 apr_table_setn(r->subprocess_env,
547 "BALANCER_WORKER_ROUTE", (*worker)->s->route);
549 /* Rewrite the url from 'balancer://url'
550 * to the 'worker_scheme://worker_hostname[:worker_port]/url'
551 * This replaces the balancers fictional name with the
552 * real hostname of the elected worker.
554 access_status = rewrite_url(r, *worker, url);
555 /* Add the session route to request notes if present */
557 apr_table_setn(r->notes, "session-sticky", sticky);
558 apr_table_setn(r->notes, "session-route", route);
560 /* Add session info to env. */
561 apr_table_setn(r->subprocess_env,
562 "BALANCER_SESSION_STICKY", sticky);
563 apr_table_setn(r->subprocess_env,
564 "BALANCER_SESSION_ROUTE", route);
566 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
567 "proxy: BALANCER (%s) worker (%s) rewritten to %s",
568 (*balancer)->name, (*worker)->name, *url);
570 return access_status;
573 static int proxy_balancer_post_request(proxy_worker *worker,
574 proxy_balancer *balancer,
576 proxy_server_conf *conf)
582 if ((rv = PROXY_THREAD_LOCK(balancer)) != APR_SUCCESS) {
583 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
584 "proxy: BALANCER: (%s). Lock failed for post_request",
586 return HTTP_INTERNAL_SERVER_ERROR;
588 /* TODO: placeholder for post_request actions
591 if ((rv = PROXY_THREAD_UNLOCK(balancer)) != APR_SUCCESS) {
592 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
593 "proxy: BALANCER: (%s). Unlock failed for post_request",
596 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
597 "proxy_balancer_post_request for (%s)", balancer->name);
604 static void recalc_factors(proxy_balancer *balancer)
607 proxy_worker *workers;
610 /* Recalculate lbfactors */
611 workers = (proxy_worker *)balancer->workers->elts;
612 /* Special case if there is only one worker it's
613 * load factor will always be 1
615 if (balancer->workers->nelts == 1) {
616 workers->s->lbstatus = workers->s->lbfactor = 1;
619 for (i = 0; i < balancer->workers->nelts; i++) {
620 /* Update the status entries */
621 workers[i].s->lbstatus = workers[i].s->lbfactor;
625 /* Manages the loadfactors and member status
627 static int balancer_handler(request_rec *r)
629 void *sconf = r->server->module_config;
630 proxy_server_conf *conf = (proxy_server_conf *)
631 ap_get_module_config(sconf, &proxy_module);
632 proxy_balancer *balancer, *bsel = NULL;
633 proxy_worker *worker, *wsel = NULL;
634 apr_table_t *params = apr_table_make(r->pool, 10);
639 /* is this for us? */
640 if (strcmp(r->handler, "balancer-manager"))
642 r->allowed = (AP_METHOD_BIT << M_GET);
643 if (r->method_number != M_GET)
647 char *args = apr_pstrdup(r->pool, r->args);
649 while (args && *args) {
650 if ((val = ap_strchr(args, '='))) {
652 if ((tok = ap_strchr(val, '&')))
655 * Special case: workers are allowed path information
657 if ((access_status = ap_unescape_url(val)) != OK)
658 if (strcmp(args, "w") || (access_status != HTTP_NOT_FOUND))
659 return access_status;
660 apr_table_setn(params, args, val);
664 return HTTP_BAD_REQUEST;
667 if ((name = apr_table_get(params, "b")))
668 bsel = ap_proxy_get_balancer(r->pool, conf,
669 apr_pstrcat(r->pool, "balancer://", name, NULL));
670 if ((name = apr_table_get(params, "w"))) {
673 ws = ap_proxy_get_worker(r->pool, conf, name);
675 worker = (proxy_worker *)bsel->workers->elts;
676 for (n = 0; n < bsel->workers->nelts; n++) {
677 if (strcasecmp(worker->name, ws->name) == 0) {
685 /* First set the params */
687 * Note that it is not possible set the proxy_balancer because it is not
692 if ((val = apr_table_get(params, "lf"))) {
693 int ival = atoi(val);
694 if (ival >= 1 && ival <= 100) {
695 wsel->s->lbfactor = ival;
697 recalc_factors(bsel);
700 if ((val = apr_table_get(params, "wr"))) {
701 if (strlen(val) && strlen(val) < PROXY_WORKER_MAX_ROUTE_SIZ)
702 strcpy(wsel->s->route, val);
704 *wsel->s->route = '\0';
706 if ((val = apr_table_get(params, "rr"))) {
707 if (strlen(val) && strlen(val) < PROXY_WORKER_MAX_ROUTE_SIZ)
708 strcpy(wsel->s->redirect, val);
710 *wsel->s->redirect = '\0';
712 if ((val = apr_table_get(params, "dw"))) {
713 if (!strcasecmp(val, "Disable"))
714 wsel->s->status |= PROXY_WORKER_DISABLED;
715 else if (!strcasecmp(val, "Enable"))
716 wsel->s->status &= ~PROXY_WORKER_DISABLED;
718 if ((val = apr_table_get(params, "ls"))) {
719 int ival = atoi(val);
720 if (ival >= 0 && ival <= 99) {
721 wsel->s->lbset = ival;
726 if (apr_table_get(params, "xml")) {
727 ap_set_content_type(r, "text/xml");
728 ap_rputs("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n", r);
729 ap_rputs("<httpd:manager xmlns:httpd=\"http://httpd.apache.org\">\n", r);
730 ap_rputs(" <httpd:balancers>\n", r);
731 balancer = (proxy_balancer *)conf->balancers->elts;
732 for (i = 0; i < conf->balancers->nelts; i++) {
733 ap_rputs(" <httpd:balancer>\n", r);
734 ap_rvputs(r, " <httpd:name>", balancer->name, "</httpd:name>\n", NULL);
735 ap_rputs(" <httpd:workers>\n", r);
736 worker = (proxy_worker *)balancer->workers->elts;
737 for (n = 0; n < balancer->workers->nelts; n++) {
738 ap_rputs(" <httpd:worker>\n", r);
739 ap_rvputs(r, " <httpd:scheme>", worker->scheme,
740 "</httpd:scheme>\n", NULL);
741 ap_rvputs(r, " <httpd:hostname>", worker->hostname,
742 "</httpd:hostname>\n", NULL);
743 ap_rprintf(r, " <httpd:loadfactor>%d</httpd:loadfactor>\n",
744 worker->s->lbfactor);
745 ap_rputs(" </httpd:worker>\n", r);
748 ap_rputs(" </httpd:workers>\n", r);
749 ap_rputs(" </httpd:balancer>\n", r);
752 ap_rputs(" </httpd:balancers>\n", r);
753 ap_rputs("</httpd:manager>", r);
756 ap_set_content_type(r, "text/html; charset=ISO-8859-1");
757 ap_rputs(DOCTYPE_HTML_3_2
758 "<html><head><title>Balancer Manager</title></head>\n", r);
759 ap_rputs("<body><h1>Load Balancer Manager for ", r);
760 ap_rvputs(r, ap_get_server_name(r), "</h1>\n\n", NULL);
761 ap_rvputs(r, "<dl><dt>Server Version: ",
762 ap_get_server_description(), "</dt>\n", NULL);
763 ap_rvputs(r, "<dt>Server Built: ",
764 ap_get_server_built(), "\n</dt></dl>\n", NULL);
765 balancer = (proxy_balancer *)conf->balancers->elts;
766 for (i = 0; i < conf->balancers->nelts; i++) {
768 ap_rputs("<hr />\n<h3>LoadBalancer Status for ", r);
769 ap_rvputs(r, balancer->name, "</h3>\n\n", NULL);
770 ap_rputs("\n\n<table border=\"0\" style=\"text-align: left;\"><tr>"
771 "<th>StickySession</th><th>Timeout</th><th>FailoverAttempts</th><th>Method</th>"
773 if (balancer->sticky) {
774 if (strcmp(balancer->sticky, balancer->sticky_path)) {
775 ap_rvputs(r, "<td>", balancer->sticky, " | ",
776 balancer->sticky_path, NULL);
779 ap_rvputs(r, "<td>", balancer->sticky, NULL);
783 ap_rputs("<td> - ", r);
785 ap_rprintf(r, "</td><td>%" APR_TIME_T_FMT "</td>",
786 apr_time_sec(balancer->timeout));
787 ap_rprintf(r, "<td>%d</td>\n", balancer->max_attempts);
788 ap_rprintf(r, "<td>%s</td>\n",
789 balancer->lbmethod->name);
790 ap_rputs("</table>\n<br />", r);
791 ap_rputs("\n\n<table border=\"0\" style=\"text-align: left;\"><tr>"
792 "<th>Worker URL</th>"
793 "<th>Route</th><th>RouteRedir</th>"
794 "<th>Factor</th><th>Set</th><th>Status</th>"
795 "<th>Elected</th><th>To</th><th>From</th>"
798 worker = (proxy_worker *)balancer->workers->elts;
799 for (n = 0; n < balancer->workers->nelts; n++) {
801 ap_rvputs(r, "<tr>\n<td><a href=\"", r->uri, "?b=",
802 balancer->name + sizeof("balancer://") - 1, "&w=",
803 ap_escape_uri(r->pool, worker->name),
805 ap_rvputs(r, worker->name, "</a></td>", NULL);
806 ap_rvputs(r, "<td>", worker->s->route, NULL);
807 ap_rvputs(r, "</td><td>", worker->s->redirect, NULL);
808 ap_rprintf(r, "</td><td>%d</td>", worker->s->lbfactor);
809 ap_rprintf(r, "<td>%d</td><td>", worker->s->lbset);
810 if (worker->s->status & PROXY_WORKER_DISABLED)
812 if (worker->s->status & PROXY_WORKER_IN_ERROR)
814 if (worker->s->status & PROXY_WORKER_STOPPED)
815 ap_rputs("Stop ", r);
816 if (worker->s->status & PROXY_WORKER_HOT_STANDBY)
817 ap_rputs("Stby ", r);
818 if (PROXY_WORKER_IS_USABLE(worker))
820 if (!PROXY_WORKER_IS_INITIALIZED(worker))
822 ap_rputs("</td>", r);
823 ap_rprintf(r, "<td>%" APR_SIZE_T_FMT "</td><td>", worker->s->elected);
824 ap_rputs(apr_strfsize(worker->s->transferred, fbuf), r);
825 ap_rputs("</td><td>", r);
826 ap_rputs(apr_strfsize(worker->s->read, fbuf), r);
827 ap_rputs("</td></tr>\n", r);
831 ap_rputs("</table>\n", r);
834 ap_rputs("<hr />\n", r);
836 ap_rputs("<h3>Edit worker settings for ", r);
837 ap_rvputs(r, wsel->name, "</h3>\n", NULL);
838 ap_rvputs(r, "<form method=\"GET\" action=\"", NULL);
839 ap_rvputs(r, r->uri, "\">\n<dl>", NULL);
840 ap_rputs("<table><tr><td>Load factor:</td><td><input name=\"lf\" type=text ", r);
841 ap_rprintf(r, "value=\"%d\"></td></tr>\n", wsel->s->lbfactor);
842 ap_rputs("<tr><td>LB Set:</td><td><input name=\"ls\" type=text ", r);
843 ap_rprintf(r, "value=\"%d\"></td></tr>\n", wsel->s->lbset);
844 ap_rputs("<tr><td>Route:</td><td><input name=\"wr\" type=text ", r);
845 ap_rvputs(r, "value=\"", wsel->s->route, NULL);
846 ap_rputs("\"></td></tr>\n", r);
847 ap_rputs("<tr><td>Route Redirect:</td><td><input name=\"rr\" type=text ", r);
848 ap_rvputs(r, "value=\"", wsel->s->redirect, NULL);
849 ap_rputs("\"></td></tr>\n", r);
850 ap_rputs("<tr><td>Status:</td><td>Disabled: <input name=\"dw\" value=\"Disable\" type=radio", r);
851 if (wsel->s->status & PROXY_WORKER_DISABLED)
852 ap_rputs(" checked", r);
853 ap_rputs("> | Enabled: <input name=\"dw\" value=\"Enable\" type=radio", r);
854 if (!(wsel->s->status & PROXY_WORKER_DISABLED))
855 ap_rputs(" checked", r);
856 ap_rputs("></td></tr>\n", r);
857 ap_rputs("<tr><td colspan=2><input type=submit value=\"Submit\"></td></tr>\n", r);
858 ap_rvputs(r, "</table>\n<input type=hidden name=\"w\" ", NULL);
859 ap_rvputs(r, "value=\"", ap_escape_uri(r->pool, wsel->name), "\">\n", NULL);
860 ap_rvputs(r, "<input type=hidden name=\"b\" ", NULL);
861 ap_rvputs(r, "value=\"", bsel->name + sizeof("balancer://") - 1,
862 "\">\n</form>\n", NULL);
863 ap_rputs("<hr />\n", r);
865 ap_rputs(ap_psignature("",r), r);
866 ap_rputs("</body></html>\n", r);
871 static void child_init(apr_pool_t *p, server_rec *s)
874 void *sconf = s->module_config;
875 proxy_server_conf *conf;
876 proxy_balancer *balancer;
878 conf = (proxy_server_conf *)ap_get_module_config(sconf, &proxy_module);
880 /* Initialize shared scoreboard data */
881 balancer = (proxy_balancer *)conf->balancers->elts;
882 for (i = 0; i < conf->balancers->nelts; i++) {
883 init_balancer_members(conf, s, balancer);
892 * The idea behind the find_best_byrequests scheduler is the following:
894 * lbfactor is "how much we expect this worker to work", or "the worker's
895 * normalized work quota".
897 * lbstatus is "how urgent this worker has to work to fulfill its quota
900 * We distribute each worker's work quota to the worker, and then look
901 * which of them needs to work most urgently (biggest lbstatus). This
902 * worker is then selected for work, and its lbstatus reduced by the
903 * total work quota we distributed to all workers. Thus the sum of all
904 * lbstatus does not change.(*)
906 * If some workers are disabled, the others will
907 * still be scheduled correctly.
909 * If a balancer is configured as follows:
912 * lbfactor 25 25 25 25
914 * And b gets disabled, the following schedule is produced:
916 * a c d a c d a c d ...
918 * Note that the above lbfactor setting is the *exact* same as:
923 * Asymmetric configurations work as one would expect. For
929 * would have a, b and c all handling about the same
930 * amount of load with d handling twice what a or b
931 * or c handles individually. So we could see:
933 * b a d c d a c d b d ...
937 static proxy_worker *find_best_byrequests(proxy_balancer *balancer,
941 int total_factor = 0;
942 proxy_worker *worker;
943 proxy_worker *mycandidate = NULL;
946 int checking_standby;
949 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
950 "proxy: Entering byrequests for BALANCER (%s)",
953 /* First try to see if we have available candidate */
955 checking_standby = checked_standby = 0;
956 while (!mycandidate && !checked_standby) {
957 worker = (proxy_worker *)balancer->workers->elts;
958 for (i = 0; i < balancer->workers->nelts; i++, worker++) {
959 if (!checking_standby) { /* first time through */
960 if (worker->s->lbset > max_lbset)
961 max_lbset = worker->s->lbset;
963 if (worker->s->lbset > cur_lbset)
965 if ( (checking_standby ? !PROXY_WORKER_IS_STANDBY(worker) : PROXY_WORKER_IS_STANDBY(worker)) )
967 /* If the worker is in error state run
968 * retry on that worker. It will be marked as
969 * operational if the retry timeout is elapsed.
970 * The worker might still be unusable, but we try
973 if (!PROXY_WORKER_IS_USABLE(worker))
974 ap_proxy_retry_worker("BALANCER", worker, r->server);
975 /* Take into calculation only the workers that are
976 * not in error state or not disabled.
978 if (PROXY_WORKER_IS_USABLE(worker)) {
979 worker->s->lbstatus += worker->s->lbfactor;
980 total_factor += worker->s->lbfactor;
981 if (!mycandidate || worker->s->lbstatus > mycandidate->s->lbstatus)
982 mycandidate = worker;
985 checked_standby = checking_standby++;
988 } while (cur_lbset <= max_lbset && !mycandidate);
991 mycandidate->s->lbstatus -= total_factor;
998 * The idea behind the find_best_bytraffic scheduler is the following:
1000 * We know the amount of traffic (bytes in and out) handled by each
1001 * worker. We normalize that traffic by each workers' weight. So assuming
1007 * the scheduler will allow worker c to handle 3 times the
1008 * traffic of a and b. If each request/response results in the
1009 * same amount of traffic, then c would be accessed 3 times as
1010 * often as a or b. If, for example, a handled a request that
1011 * resulted in a large i/o bytecount, then b and c would be
1012 * chosen more often, to even things out.
1014 static proxy_worker *find_best_bytraffic(proxy_balancer *balancer,
1018 apr_off_t mytraffic = 0;
1019 apr_off_t curmin = 0;
1020 proxy_worker *worker;
1021 proxy_worker *mycandidate = NULL;
1024 int checking_standby;
1025 int checked_standby;
1027 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1028 "proxy: Entering bytraffic for BALANCER (%s)",
1031 /* First try to see if we have available candidate */
1033 checking_standby = checked_standby = 0;
1034 while (!mycandidate && !checked_standby) {
1035 worker = (proxy_worker *)balancer->workers->elts;
1036 for (i = 0; i < balancer->workers->nelts; i++, worker++) {
1037 if (!checking_standby) { /* first time through */
1038 if (worker->s->lbset > max_lbset)
1039 max_lbset = worker->s->lbset;
1041 if (worker->s->lbset > cur_lbset)
1043 if ( (checking_standby ? !PROXY_WORKER_IS_STANDBY(worker) : PROXY_WORKER_IS_STANDBY(worker)) )
1045 /* If the worker is in error state run
1046 * retry on that worker. It will be marked as
1047 * operational if the retry timeout is elapsed.
1048 * The worker might still be unusable, but we try
1051 if (!PROXY_WORKER_IS_USABLE(worker))
1052 ap_proxy_retry_worker("BALANCER", worker, r->server);
1053 /* Take into calculation only the workers that are
1054 * not in error state or not disabled.
1056 if (PROXY_WORKER_IS_USABLE(worker)) {
1057 mytraffic = (worker->s->transferred/worker->s->lbfactor) +
1058 (worker->s->read/worker->s->lbfactor);
1059 if (!mycandidate || mytraffic < curmin) {
1060 mycandidate = worker;
1065 checked_standby = checking_standby++;
1068 } while (cur_lbset <= max_lbset && !mycandidate);
1074 * How to add additional lbmethods:
1075 * 1. Create func which determines "best" candidate worker
1076 * (eg: find_best_bytraffic, above)
1077 * 2. Register it as a provider.
1079 static const proxy_balancer_method byrequests =
1082 &find_best_byrequests,
1086 static const proxy_balancer_method bytraffic =
1089 &find_best_bytraffic,
1093 static void ap_proxy_balancer_register_hook(apr_pool_t *p)
1095 /* Only the mpm_winnt has child init hook handler.
1096 * make sure that we are called after the mpm
1097 * initializes and after the mod_proxy
1099 static const char *const aszPred[] = { "mpm_winnt.c", "mod_proxy.c", NULL};
1100 /* manager handler */
1101 ap_hook_handler(balancer_handler, NULL, NULL, APR_HOOK_FIRST);
1102 ap_hook_child_init(child_init, aszPred, NULL, APR_HOOK_MIDDLE);
1103 proxy_hook_pre_request(proxy_balancer_pre_request, NULL, NULL, APR_HOOK_FIRST);
1104 proxy_hook_post_request(proxy_balancer_post_request, NULL, NULL, APR_HOOK_FIRST);
1105 proxy_hook_canon_handler(proxy_balancer_canon, NULL, NULL, APR_HOOK_FIRST);
1106 ap_register_provider(p, PROXY_LBMETHOD, "bytraffic", "0", &bytraffic);
1107 ap_register_provider(p, PROXY_LBMETHOD, "byrequests", "0", &byrequests);
1110 module AP_MODULE_DECLARE_DATA proxy_balancer_module = {
1111 STANDARD20_MODULE_STUFF,
1112 NULL, /* create per-directory config structure */
1113 NULL, /* merge per-directory config structures */
1114 NULL, /* create per-server config structure */
1115 NULL, /* merge per-server config structures */
1116 NULL, /* command apr_table_t */
1117 ap_proxy_balancer_register_hook /* register hooks */