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"
26 module AP_MODULE_DECLARE_DATA proxy_balancer_module;
28 static char balancer_nonce[APR_UUID_FORMATTED_LENGTH + 1];
30 static int proxy_balancer_canon(request_rec *r, char *url)
37 if (strncasecmp(url, "balancer:", 9) == 0) {
44 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
45 "proxy: BALANCER: canonicalising URL %s", url);
48 * We break the URL into host, port, path, search
50 err = ap_proxy_canon_netloc(r->pool, &url, NULL, NULL, &host, &port);
52 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
53 "error parsing URL %s: %s",
55 return HTTP_BAD_REQUEST;
58 * now parse path/search args, according to rfc1738:
59 * process the path. With proxy-noncanon set (by
60 * mod_proxy) we use the raw, unparsed uri
62 if (apr_table_get(r->notes, "proxy-nocanon")) {
63 path = url; /* this is the raw path */
66 path = ap_proxy_canonenc(r->pool, url, strlen(url), enc_path, 0,
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 /* post_config hook: */
626 static int balancer_init(apr_pool_t *p, apr_pool_t *plog,
627 apr_pool_t *ptemp, server_rec *s)
630 const char *userdata_key = "mod_proxy_balancer_init";
633 /* balancer_init() will be called twice during startup. So, only
634 * set up the static data the second time through. */
635 apr_pool_userdata_get(&data, userdata_key, s->process->pool);
637 apr_pool_userdata_set((const void *)1, userdata_key,
638 apr_pool_cleanup_null, s->process->pool);
642 /* Retrieve a UUID and store the nonce for the lifetime of
645 apr_uuid_format(balancer_nonce, &uuid);
650 /* Manages the loadfactors and member status
652 static int balancer_handler(request_rec *r)
654 void *sconf = r->server->module_config;
655 proxy_server_conf *conf = (proxy_server_conf *)
656 ap_get_module_config(sconf, &proxy_module);
657 proxy_balancer *balancer, *bsel = NULL;
658 proxy_worker *worker, *wsel = NULL;
659 apr_table_t *params = apr_table_make(r->pool, 10);
664 /* is this for us? */
665 if (strcmp(r->handler, "balancer-manager"))
667 r->allowed = (AP_METHOD_BIT << M_GET);
668 if (r->method_number != M_GET)
672 char *args = apr_pstrdup(r->pool, r->args);
674 while (args && *args) {
675 if ((val = ap_strchr(args, '='))) {
677 if ((tok = ap_strchr(val, '&')))
680 * Special case: workers are allowed path information
682 if ((access_status = ap_unescape_url(val)) != OK)
683 if (strcmp(args, "w") || (access_status != HTTP_NOT_FOUND))
684 return access_status;
685 apr_table_setn(params, args, val);
689 return HTTP_BAD_REQUEST;
693 /* Check that the supplied nonce matches this server's nonce;
694 * otherwise ignore all parameters, to prevent a CSRF attack. */
695 if ((name = apr_table_get(params, "nonce")) == NULL
696 || strcmp(balancer_nonce, name) != 0) {
697 apr_table_clear(params);
700 if ((name = apr_table_get(params, "b")))
701 bsel = ap_proxy_get_balancer(r->pool, conf,
702 apr_pstrcat(r->pool, "balancer://", name, NULL));
703 if ((name = apr_table_get(params, "w"))) {
706 ws = ap_proxy_get_worker(r->pool, conf, name);
708 worker = (proxy_worker *)bsel->workers->elts;
709 for (n = 0; n < bsel->workers->nelts; n++) {
710 if (strcasecmp(worker->name, ws->name) == 0) {
718 /* First set the params */
720 * Note that it is not possible set the proxy_balancer because it is not
725 if ((val = apr_table_get(params, "lf"))) {
726 int ival = atoi(val);
727 if (ival >= 1 && ival <= 100) {
728 wsel->s->lbfactor = ival;
730 recalc_factors(bsel);
733 if ((val = apr_table_get(params, "wr"))) {
734 if (strlen(val) && strlen(val) < PROXY_WORKER_MAX_ROUTE_SIZ)
735 strcpy(wsel->s->route, val);
737 *wsel->s->route = '\0';
739 if ((val = apr_table_get(params, "rr"))) {
740 if (strlen(val) && strlen(val) < PROXY_WORKER_MAX_ROUTE_SIZ)
741 strcpy(wsel->s->redirect, val);
743 *wsel->s->redirect = '\0';
745 if ((val = apr_table_get(params, "dw"))) {
746 if (!strcasecmp(val, "Disable"))
747 wsel->s->status |= PROXY_WORKER_DISABLED;
748 else if (!strcasecmp(val, "Enable"))
749 wsel->s->status &= ~PROXY_WORKER_DISABLED;
751 if ((val = apr_table_get(params, "ls"))) {
752 int ival = atoi(val);
753 if (ival >= 0 && ival <= 99) {
754 wsel->s->lbset = ival;
759 if (apr_table_get(params, "xml")) {
760 ap_set_content_type(r, "text/xml");
761 ap_rputs("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n", r);
762 ap_rputs("<httpd:manager xmlns:httpd=\"http://httpd.apache.org\">\n", r);
763 ap_rputs(" <httpd:balancers>\n", r);
764 balancer = (proxy_balancer *)conf->balancers->elts;
765 for (i = 0; i < conf->balancers->nelts; i++) {
766 ap_rputs(" <httpd:balancer>\n", r);
767 ap_rvputs(r, " <httpd:name>", balancer->name, "</httpd:name>\n", NULL);
768 ap_rputs(" <httpd:workers>\n", r);
769 worker = (proxy_worker *)balancer->workers->elts;
770 for (n = 0; n < balancer->workers->nelts; n++) {
771 ap_rputs(" <httpd:worker>\n", r);
772 ap_rvputs(r, " <httpd:scheme>", worker->scheme,
773 "</httpd:scheme>\n", NULL);
774 ap_rvputs(r, " <httpd:hostname>", worker->hostname,
775 "</httpd:hostname>\n", NULL);
776 ap_rprintf(r, " <httpd:loadfactor>%d</httpd:loadfactor>\n",
777 worker->s->lbfactor);
778 ap_rputs(" </httpd:worker>\n", r);
781 ap_rputs(" </httpd:workers>\n", r);
782 ap_rputs(" </httpd:balancer>\n", r);
785 ap_rputs(" </httpd:balancers>\n", r);
786 ap_rputs("</httpd:manager>", r);
789 ap_set_content_type(r, "text/html; charset=ISO-8859-1");
790 ap_rputs(DOCTYPE_HTML_3_2
791 "<html><head><title>Balancer Manager</title></head>\n", r);
792 ap_rputs("<body><h1>Load Balancer Manager for ", r);
793 ap_rvputs(r, ap_get_server_name(r), "</h1>\n\n", NULL);
794 ap_rvputs(r, "<dl><dt>Server Version: ",
795 ap_get_server_description(), "</dt>\n", NULL);
796 ap_rvputs(r, "<dt>Server Built: ",
797 ap_get_server_built(), "\n</dt></dl>\n", NULL);
798 balancer = (proxy_balancer *)conf->balancers->elts;
799 for (i = 0; i < conf->balancers->nelts; i++) {
801 ap_rputs("<hr />\n<h3>LoadBalancer Status for ", r);
802 ap_rvputs(r, balancer->name, "</h3>\n\n", NULL);
803 ap_rputs("\n\n<table border=\"0\" style=\"text-align: left;\"><tr>"
804 "<th>StickySession</th><th>Timeout</th><th>FailoverAttempts</th><th>Method</th>"
806 if (balancer->sticky) {
807 if (strcmp(balancer->sticky, balancer->sticky_path)) {
808 ap_rvputs(r, "<td>", balancer->sticky, " | ",
809 balancer->sticky_path, NULL);
812 ap_rvputs(r, "<td>", balancer->sticky, NULL);
816 ap_rputs("<td> - ", r);
818 ap_rprintf(r, "</td><td>%" APR_TIME_T_FMT "</td>",
819 apr_time_sec(balancer->timeout));
820 ap_rprintf(r, "<td>%d</td>\n", balancer->max_attempts);
821 ap_rprintf(r, "<td>%s</td>\n",
822 balancer->lbmethod->name);
823 ap_rputs("</table>\n<br />", r);
824 ap_rputs("\n\n<table border=\"0\" style=\"text-align: left;\"><tr>"
825 "<th>Worker URL</th>"
826 "<th>Route</th><th>RouteRedir</th>"
827 "<th>Factor</th><th>Set</th><th>Status</th>"
828 "<th>Elected</th><th>To</th><th>From</th>"
831 worker = (proxy_worker *)balancer->workers->elts;
832 for (n = 0; n < balancer->workers->nelts; n++) {
834 ap_rvputs(r, "<tr>\n<td><a href=\"", r->uri, "?b=",
835 balancer->name + sizeof("balancer://") - 1, "&w=",
836 ap_escape_uri(r->pool, worker->name),
837 "&nonce=", balancer_nonce,
839 ap_rvputs(r, worker->name, "</a></td>", NULL);
840 ap_rvputs(r, "<td>", ap_escape_html(r->pool, worker->s->route),
842 ap_rvputs(r, "</td><td>",
843 ap_escape_html(r->pool, worker->s->redirect), NULL);
844 ap_rprintf(r, "</td><td>%d</td>", worker->s->lbfactor);
845 ap_rprintf(r, "<td>%d</td><td>", worker->s->lbset);
846 if (worker->s->status & PROXY_WORKER_DISABLED)
848 if (worker->s->status & PROXY_WORKER_IN_ERROR)
850 if (worker->s->status & PROXY_WORKER_STOPPED)
851 ap_rputs("Stop ", r);
852 if (worker->s->status & PROXY_WORKER_HOT_STANDBY)
853 ap_rputs("Stby ", r);
854 if (PROXY_WORKER_IS_USABLE(worker))
856 if (!PROXY_WORKER_IS_INITIALIZED(worker))
858 ap_rputs("</td>", r);
859 ap_rprintf(r, "<td>%" APR_SIZE_T_FMT "</td><td>", worker->s->elected);
860 ap_rputs(apr_strfsize(worker->s->transferred, fbuf), r);
861 ap_rputs("</td><td>", r);
862 ap_rputs(apr_strfsize(worker->s->read, fbuf), r);
863 ap_rputs("</td></tr>\n", r);
867 ap_rputs("</table>\n", r);
870 ap_rputs("<hr />\n", r);
872 ap_rputs("<h3>Edit worker settings for ", r);
873 ap_rvputs(r, wsel->name, "</h3>\n", NULL);
874 ap_rvputs(r, "<form method=\"GET\" action=\"", NULL);
875 ap_rvputs(r, r->uri, "\">\n<dl>", NULL);
876 ap_rputs("<table><tr><td>Load factor:</td><td><input name=\"lf\" type=text ", r);
877 ap_rprintf(r, "value=\"%d\"></td></tr>\n", wsel->s->lbfactor);
878 ap_rputs("<tr><td>LB Set:</td><td><input name=\"ls\" type=text ", r);
879 ap_rprintf(r, "value=\"%d\"></td></tr>\n", wsel->s->lbset);
880 ap_rputs("<tr><td>Route:</td><td><input name=\"wr\" type=text ", r);
881 ap_rvputs(r, "value=\"", ap_escape_html(r->pool, wsel->s->route),
883 ap_rputs("\"></td></tr>\n", r);
884 ap_rputs("<tr><td>Route Redirect:</td><td><input name=\"rr\" type=text ", r);
885 ap_rvputs(r, "value=\"", ap_escape_html(r->pool, wsel->s->redirect),
887 ap_rputs("\"></td></tr>\n", r);
888 ap_rputs("<tr><td>Status:</td><td>Disabled: <input name=\"dw\" value=\"Disable\" type=radio", r);
889 if (wsel->s->status & PROXY_WORKER_DISABLED)
890 ap_rputs(" checked", r);
891 ap_rputs("> | Enabled: <input name=\"dw\" value=\"Enable\" type=radio", r);
892 if (!(wsel->s->status & PROXY_WORKER_DISABLED))
893 ap_rputs(" checked", r);
894 ap_rputs("></td></tr>\n", r);
895 ap_rputs("<tr><td colspan=2><input type=submit value=\"Submit\"></td></tr>\n", r);
896 ap_rvputs(r, "</table>\n<input type=hidden name=\"w\" ", NULL);
897 ap_rvputs(r, "value=\"", ap_escape_uri(r->pool, wsel->name), "\">\n", NULL);
898 ap_rvputs(r, "<input type=hidden name=\"b\" ", NULL);
899 ap_rvputs(r, "value=\"", bsel->name + sizeof("balancer://") - 1,
900 "\">\n</form>\n", NULL);
901 ap_rvputs(r, "<input type=hidden name=\"nonce\" value=\"",
902 balancer_nonce, "\">\n", NULL);
903 ap_rputs("<hr />\n", r);
905 ap_rputs(ap_psignature("",r), r);
906 ap_rputs("</body></html>\n", r);
911 static void child_init(apr_pool_t *p, server_rec *s)
914 void *sconf = s->module_config;
915 proxy_server_conf *conf;
916 proxy_balancer *balancer;
918 conf = (proxy_server_conf *)ap_get_module_config(sconf, &proxy_module);
920 /* Initialize shared scoreboard data */
921 balancer = (proxy_balancer *)conf->balancers->elts;
922 for (i = 0; i < conf->balancers->nelts; i++) {
923 init_balancer_members(conf, s, balancer);
932 * The idea behind the find_best_byrequests scheduler is the following:
934 * lbfactor is "how much we expect this worker to work", or "the worker's
935 * normalized work quota".
937 * lbstatus is "how urgent this worker has to work to fulfill its quota
940 * We distribute each worker's work quota to the worker, and then look
941 * which of them needs to work most urgently (biggest lbstatus). This
942 * worker is then selected for work, and its lbstatus reduced by the
943 * total work quota we distributed to all workers. Thus the sum of all
944 * lbstatus does not change.(*)
946 * If some workers are disabled, the others will
947 * still be scheduled correctly.
949 * If a balancer is configured as follows:
952 * lbfactor 25 25 25 25
954 * And b gets disabled, the following schedule is produced:
956 * a c d a c d a c d ...
958 * Note that the above lbfactor setting is the *exact* same as:
963 * Asymmetric configurations work as one would expect. For
969 * would have a, b and c all handling about the same
970 * amount of load with d handling twice what a or b
971 * or c handles individually. So we could see:
973 * b a d c d a c d b d ...
977 static proxy_worker *find_best_byrequests(proxy_balancer *balancer,
981 int total_factor = 0;
982 proxy_worker *worker;
983 proxy_worker *mycandidate = NULL;
986 int checking_standby;
989 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
990 "proxy: Entering byrequests for BALANCER (%s)",
993 /* First try to see if we have available candidate */
995 checking_standby = checked_standby = 0;
996 while (!mycandidate && !checked_standby) {
997 worker = (proxy_worker *)balancer->workers->elts;
998 for (i = 0; i < balancer->workers->nelts; i++, worker++) {
999 if (!checking_standby) { /* first time through */
1000 if (worker->s->lbset > max_lbset)
1001 max_lbset = worker->s->lbset;
1003 if (worker->s->lbset > cur_lbset)
1005 if ( (checking_standby ? !PROXY_WORKER_IS_STANDBY(worker) : PROXY_WORKER_IS_STANDBY(worker)) )
1007 /* If the worker is in error state run
1008 * retry on that worker. It will be marked as
1009 * operational if the retry timeout is elapsed.
1010 * The worker might still be unusable, but we try
1013 if (!PROXY_WORKER_IS_USABLE(worker))
1014 ap_proxy_retry_worker("BALANCER", worker, r->server);
1015 /* Take into calculation only the workers that are
1016 * not in error state or not disabled.
1018 if (PROXY_WORKER_IS_USABLE(worker)) {
1019 worker->s->lbstatus += worker->s->lbfactor;
1020 total_factor += worker->s->lbfactor;
1021 if (!mycandidate || worker->s->lbstatus > mycandidate->s->lbstatus)
1022 mycandidate = worker;
1025 checked_standby = checking_standby++;
1028 } while (cur_lbset <= max_lbset && !mycandidate);
1031 mycandidate->s->lbstatus -= total_factor;
1038 * The idea behind the find_best_bytraffic scheduler is the following:
1040 * We know the amount of traffic (bytes in and out) handled by each
1041 * worker. We normalize that traffic by each workers' weight. So assuming
1047 * the scheduler will allow worker c to handle 3 times the
1048 * traffic of a and b. If each request/response results in the
1049 * same amount of traffic, then c would be accessed 3 times as
1050 * often as a or b. If, for example, a handled a request that
1051 * resulted in a large i/o bytecount, then b and c would be
1052 * chosen more often, to even things out.
1054 static proxy_worker *find_best_bytraffic(proxy_balancer *balancer,
1058 apr_off_t mytraffic = 0;
1059 apr_off_t curmin = 0;
1060 proxy_worker *worker;
1061 proxy_worker *mycandidate = NULL;
1064 int checking_standby;
1065 int checked_standby;
1067 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1068 "proxy: Entering bytraffic for BALANCER (%s)",
1071 /* First try to see if we have available candidate */
1073 checking_standby = checked_standby = 0;
1074 while (!mycandidate && !checked_standby) {
1075 worker = (proxy_worker *)balancer->workers->elts;
1076 for (i = 0; i < balancer->workers->nelts; i++, worker++) {
1077 if (!checking_standby) { /* first time through */
1078 if (worker->s->lbset > max_lbset)
1079 max_lbset = worker->s->lbset;
1081 if (worker->s->lbset > cur_lbset)
1083 if ( (checking_standby ? !PROXY_WORKER_IS_STANDBY(worker) : PROXY_WORKER_IS_STANDBY(worker)) )
1085 /* If the worker is in error state run
1086 * retry on that worker. It will be marked as
1087 * operational if the retry timeout is elapsed.
1088 * The worker might still be unusable, but we try
1091 if (!PROXY_WORKER_IS_USABLE(worker))
1092 ap_proxy_retry_worker("BALANCER", worker, r->server);
1093 /* Take into calculation only the workers that are
1094 * not in error state or not disabled.
1096 if (PROXY_WORKER_IS_USABLE(worker)) {
1097 mytraffic = (worker->s->transferred/worker->s->lbfactor) +
1098 (worker->s->read/worker->s->lbfactor);
1099 if (!mycandidate || mytraffic < curmin) {
1100 mycandidate = worker;
1105 checked_standby = checking_standby++;
1108 } while (cur_lbset <= max_lbset && !mycandidate);
1114 * How to add additional lbmethods:
1115 * 1. Create func which determines "best" candidate worker
1116 * (eg: find_best_bytraffic, above)
1117 * 2. Register it as a provider.
1119 static const proxy_balancer_method byrequests =
1122 &find_best_byrequests,
1126 static const proxy_balancer_method bytraffic =
1129 &find_best_bytraffic,
1133 static void ap_proxy_balancer_register_hook(apr_pool_t *p)
1135 /* Only the mpm_winnt has child init hook handler.
1136 * make sure that we are called after the mpm
1137 * initializes and after the mod_proxy
1139 static const char *const aszPred[] = { "mpm_winnt.c", "mod_proxy.c", NULL};
1140 /* manager handler */
1141 ap_hook_post_config(balancer_init, NULL, NULL, APR_HOOK_MIDDLE);
1142 ap_hook_handler(balancer_handler, NULL, NULL, APR_HOOK_FIRST);
1143 ap_hook_child_init(child_init, aszPred, NULL, APR_HOOK_MIDDLE);
1144 proxy_hook_pre_request(proxy_balancer_pre_request, NULL, NULL, APR_HOOK_FIRST);
1145 proxy_hook_post_request(proxy_balancer_post_request, NULL, NULL, APR_HOOK_FIRST);
1146 proxy_hook_canon_handler(proxy_balancer_canon, NULL, NULL, APR_HOOK_FIRST);
1147 ap_register_provider(p, PROXY_LBMETHOD, "bytraffic", "0", &bytraffic);
1148 ap_register_provider(p, PROXY_LBMETHOD, "byrequests", "0", &byrequests);
1151 module AP_MODULE_DECLARE_DATA proxy_balancer_module = {
1152 STANDARD20_MODULE_STUFF,
1153 NULL, /* create per-directory config structure */
1154 NULL, /* merge per-directory config structures */
1155 NULL, /* create per-server config structure */
1156 NULL, /* merge per-server config structures */
1157 NULL, /* command apr_table_t */
1158 ap_proxy_balancer_register_hook /* register hooks */