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 static const char *balancer_mutex_type = "proxy-balancer-shm";
27 ap_slotmem_provider_t *storage = NULL;
29 module AP_MODULE_DECLARE_DATA proxy_balancer_module;
32 * Register our mutex type before the config is read so we
33 * can adjust the mutex settings using the Mutex directive.
35 static int balancer_pre_config(apr_pool_t *pconf, apr_pool_t *plog,
41 rv = ap_mutex_register(pconf, balancer_mutex_type, NULL,
43 if (rv != APR_SUCCESS) {
51 extern void proxy_update_members(proxy_balancer **balancer, request_rec *r,
52 proxy_server_conf *conf);
55 static int proxy_balancer_canon(request_rec *r, char *url)
62 /* TODO: offset of BALANCER_PREFIX ?? */
63 if (strncasecmp(url, "balancer:", 9) == 0) {
70 ap_log_error(APLOG_MARK, APLOG_TRACE1, 0, r->server,
71 "proxy: BALANCER: canonicalising URL %s", url);
74 * We break the URL into host, port, path, search
76 err = ap_proxy_canon_netloc(r->pool, &url, NULL, NULL, &host, &port);
78 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
79 "error parsing URL %s: %s",
81 return HTTP_BAD_REQUEST;
84 * now parse path/search args, according to rfc1738:
85 * process the path. With proxy-noncanon set (by
86 * mod_proxy) we use the raw, unparsed uri
88 if (apr_table_get(r->notes, "proxy-nocanon")) {
89 path = url; /* this is the raw path */
92 path = ap_proxy_canonenc(r->pool, url, strlen(url), enc_path, 0,
97 return HTTP_BAD_REQUEST;
99 r->filename = apr_pstrcat(r->pool, "proxy:", BALANCER_PREFIX, host,
100 "/", path, (search) ? "?" : "", (search) ? search : "", NULL);
102 r->path_info = apr_pstrcat(r->pool, "/", path, NULL);
107 static void init_balancer_members(proxy_server_conf *conf, server_rec *s,
108 proxy_balancer *balancer)
111 proxy_worker **workers;
113 workers = (proxy_worker **)balancer->workers->elts;
115 for (i = 0; i < balancer->workers->nelts; i++) {
116 int worker_is_initialized;
117 proxy_worker *worker = *workers;
118 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
119 "Looking at %s -> %s initialized?", balancer->name, worker->s->name);
120 worker_is_initialized = PROXY_WORKER_IS_INITIALIZED(worker);
121 if (!worker_is_initialized) {
122 ap_proxy_initialize_worker(worker, s, conf->pool);
127 /* Set default number of attempts to the number of
130 if (!balancer->max_attempts_set && balancer->workers->nelts > 1) {
131 balancer->max_attempts = balancer->workers->nelts - 1;
132 balancer->max_attempts_set = 1;
136 /* Retrieve the parameter with the given name
137 * Something like 'JSESSIONID=12345...N'
139 static char *get_path_param(apr_pool_t *pool, char *url,
140 const char *name, int scolon_sep)
143 char *pathdelims = "?&";
148 for (path = strstr(url, name); path; path = strstr(path + 1, name)) {
149 path += strlen(name);
152 * Session path was found, get it's value
157 path = apr_strtok(apr_pstrdup(pool, path), pathdelims, &q);
165 static char *get_cookie_param(request_rec *r, const char *name)
168 const char *start_cookie;
170 if ((cookies = apr_table_get(r->headers_in, "Cookie"))) {
171 for (start_cookie = ap_strstr_c(cookies, name); start_cookie;
172 start_cookie = ap_strstr_c(start_cookie + 1, name)) {
173 if (start_cookie == cookies ||
174 start_cookie[-1] == ';' ||
175 start_cookie[-1] == ',' ||
176 isspace(start_cookie[-1])) {
178 start_cookie += strlen(name);
179 while(*start_cookie && isspace(*start_cookie))
181 if (*start_cookie++ == '=' && *start_cookie) {
183 * Session cookie was found, get it's value
185 char *end_cookie, *cookie;
186 cookie = apr_pstrdup(r->pool, start_cookie);
187 if ((end_cookie = strchr(cookie, ';')) != NULL)
189 if((end_cookie = strchr(cookie, ',')) != NULL)
199 /* Find the worker that has the 'route' defined
201 static proxy_worker *find_route_worker(proxy_balancer *balancer,
202 const char *route, request_rec *r)
205 int checking_standby;
208 proxy_worker **workers;
210 checking_standby = checked_standby = 0;
211 while (!checked_standby) {
212 workers = (proxy_worker **)balancer->workers->elts;
213 for (i = 0; i < balancer->workers->nelts; i++, workers++) {
214 proxy_worker *worker = *workers;
215 if ( (checking_standby ? !PROXY_WORKER_IS_STANDBY(worker) : PROXY_WORKER_IS_STANDBY(worker)) )
217 if (*(worker->s->route) && strcmp(worker->s->route, route) == 0) {
218 if (worker && PROXY_WORKER_IS_USABLE(worker)) {
222 * If the worker is in error state run
223 * retry on that worker. It will be marked as
224 * operational if the retry timeout is elapsed.
225 * The worker might still be unusable, but we try
228 ap_proxy_retry_worker("BALANCER", worker, r->server);
229 if (PROXY_WORKER_IS_USABLE(worker)) {
233 * We have a worker that is unusable.
234 * It can be in error or disabled, but in case
235 * it has a redirection set use that redirection worker.
236 * This enables to safely remove the member from the
237 * balancer. Of course you will need some kind of
238 * session replication between those two remote.
240 if (*worker->s->redirect) {
241 proxy_worker *rworker = NULL;
242 rworker = find_route_worker(balancer, worker->s->redirect, r);
243 /* Check if the redirect worker is usable */
244 if (rworker && !PROXY_WORKER_IS_USABLE(rworker)) {
246 * If the worker is in error state run
247 * retry on that worker. It will be marked as
248 * operational if the retry timeout is elapsed.
249 * The worker might still be unusable, but we try
252 ap_proxy_retry_worker("BALANCER", rworker, r->server);
254 if (rworker && PROXY_WORKER_IS_USABLE(rworker))
261 checked_standby = checking_standby++;
266 static proxy_worker *find_session_route(proxy_balancer *balancer,
269 const char **sticky_used,
272 proxy_worker *worker = NULL;
274 if (!balancer->sticky)
276 /* Try to find the sticky route inside url */
277 *route = get_path_param(r->pool, *url, balancer->sticky_path, balancer->scolonsep);
279 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
280 "proxy: BALANCER: Found value %s for "
281 "stickysession %s", *route, balancer->sticky_path);
282 *sticky_used = balancer->sticky_path;
285 *route = get_cookie_param(r, balancer->sticky);
287 *sticky_used = balancer->sticky;
288 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
289 "proxy: BALANCER: Found value %s for "
290 "stickysession %s", *route, balancer->sticky);
294 * If we found a value for sticksession, find the first '.' within.
295 * Everything after '.' (if present) is our route.
297 if ((*route) && ((*route = strchr(*route, '.')) != NULL ))
299 if ((*route) && (**route)) {
300 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
301 "proxy: BALANCER: Found route %s", *route);
302 /* We have a route in path or in cookie
303 * Find the worker that has this route defined.
305 worker = find_route_worker(balancer, *route, r);
306 if (worker && strcmp(*route, worker->s->route)) {
308 * Notice that the route of the worker chosen is different from
309 * the route supplied by the client.
311 apr_table_setn(r->subprocess_env, "BALANCER_ROUTE_CHANGED", "1");
312 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
313 "proxy: BALANCER: Route changed from %s to %s",
314 *route, worker->s->route);
322 static proxy_worker *find_best_worker(proxy_balancer *balancer,
325 proxy_worker *candidate = NULL;
328 if ((rv = PROXY_GLOBAL_LOCK(balancer)) != APR_SUCCESS) {
329 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
330 "proxy: BALANCER: (%s). Lock failed for find_best_worker()", balancer->name);
334 candidate = (*balancer->lbmethod->finder)(balancer, r);
337 candidate->s->elected++;
340 PROXY_GLOBAL_UNLOCK(conf);
344 if ((rv = PROXY_GLOBAL_UNLOCK(balancer)) != APR_SUCCESS) {
345 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
346 "proxy: BALANCER: (%s). Unlock failed for find_best_worker()", balancer->name);
349 if (candidate == NULL) {
350 /* All the workers are in error state or disabled.
351 * If the balancer has a timeout sleep for a while
352 * and try again to find the worker. The chances are
353 * that some other thread will release a connection.
354 * By default the timeout is not set, and the server
355 * returns SERVER_BUSY.
357 if (balancer->timeout) {
358 /* XXX: This can perhaps be build using some
359 * smarter mechanism, like tread_cond.
360 * But since the statuses can came from
361 * different childs, use the provided algo.
363 apr_interval_time_t timeout = balancer->timeout;
364 apr_interval_time_t step, tval = 0;
365 /* Set the timeout to 0 so that we don't
366 * end in infinite loop
368 balancer->timeout = 0;
369 step = timeout / 100;
370 while (tval < timeout) {
373 if ((candidate = find_best_worker(balancer, r)))
377 /* restore the timeout */
378 balancer->timeout = timeout;
386 static int rewrite_url(request_rec *r, proxy_worker *worker,
389 const char *scheme = strstr(*url, "://");
390 const char *path = NULL;
393 path = ap_strchr_c(scheme + 3, '/');
395 /* we break the URL into host, port, uri */
397 return ap_proxyerror(r, HTTP_BAD_REQUEST, apr_pstrcat(r->pool,
398 "missing worker. URI cannot be parsed: ", *url,
402 *url = apr_pstrcat(r->pool, worker->s->name, path, NULL);
407 static void force_recovery(proxy_balancer *balancer, server_rec *s)
411 proxy_worker **worker;
413 worker = (proxy_worker **)balancer->workers->elts;
414 for (i = 0; i < balancer->workers->nelts; i++, worker++) {
415 if (!((*worker)->s->status & PROXY_WORKER_IN_ERROR)) {
420 /* Try if we can recover */
421 ap_proxy_retry_worker("BALANCER", *worker, s);
422 if (!((*worker)->s->status & PROXY_WORKER_IN_ERROR)) {
429 /* If all workers are in error state force the recovery.
431 worker = (proxy_worker **)balancer->workers->elts;
432 for (i = 0; i < balancer->workers->nelts; i++, worker++) {
433 ++(*worker)->s->retries;
434 (*worker)->s->status &= ~PROXY_WORKER_IN_ERROR;
435 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
436 "proxy: BALANCER: (%s). Forcing recovery for worker (%s)",
437 balancer->name, (*worker)->s->hostname);
442 static int proxy_balancer_pre_request(proxy_worker **worker,
443 proxy_balancer **balancer,
445 proxy_server_conf *conf, char **url)
448 proxy_worker *runtime;
450 const char *sticky = NULL;
454 /* Step 1: check if the url is for us
455 * The url we can handle starts with 'balancer://'
456 * If balancer is already provided skip the search
457 * for balancer, because this is failover attempt.
460 !(*balancer = ap_proxy_get_balancer(r->pool, conf, *url)))
463 /* Step 2: Lock the LoadBalancer
464 * XXX: perhaps we need the process lock here
466 if ((rv = PROXY_GLOBAL_LOCK(*balancer)) != APR_SUCCESS) {
467 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
468 "proxy: BALANCER: (%s). Lock failed for pre_request",
473 /* Step 3: force recovery */
474 force_recovery(*balancer, r->server);
476 /* Step 3.5: Update member list for the balancer */
477 /* TODO: Implement as provider! */
478 /* proxy_update_members(balancer, r, conf); */
480 /* Step 4: find the session route */
481 runtime = find_session_route(*balancer, r, &route, &sticky, url);
483 if ((*balancer)->lbmethod && (*balancer)->lbmethod->updatelbstatus) {
484 /* Call the LB implementation */
485 (*balancer)->lbmethod->updatelbstatus(*balancer, runtime, r->server);
487 else { /* Use the default one */
488 int i, total_factor = 0;
489 proxy_worker **workers;
490 /* We have a sticky load balancer
491 * Update the workers status
492 * so that even session routes get
495 workers = (proxy_worker **)(*balancer)->workers->elts;
496 for (i = 0; i < (*balancer)->workers->nelts; i++) {
497 /* Take into calculation only the workers that are
498 * not in error state or not disabled.
500 if (PROXY_WORKER_IS_USABLE(*workers)) {
501 (*workers)->s->lbstatus += (*workers)->s->lbfactor;
502 total_factor += (*workers)->s->lbfactor;
506 runtime->s->lbstatus -= total_factor;
508 runtime->s->elected++;
512 else if (route && (*balancer)->sticky_force) {
513 int i, member_of = 0;
514 proxy_worker **workers;
516 * We have a route provided that doesn't match the
517 * balancer name. See if the provider route is the
518 * member of the same balancer in which case return 503
520 workers = (proxy_worker **)(*balancer)->workers->elts;
521 for (i = 0; i < (*balancer)->workers->nelts; i++) {
522 if (*((*workers)->s->route) && strcmp((*workers)->s->route, route) == 0) {
529 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
530 "proxy: BALANCER: (%s). All workers are in error state for route (%s)",
531 (*balancer)->name, route);
532 if ((rv = PROXY_GLOBAL_UNLOCK(*balancer)) != APR_SUCCESS) {
533 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
534 "proxy: BALANCER: (%s). Unlock failed for pre_request",
537 return HTTP_SERVICE_UNAVAILABLE;
541 if ((rv = PROXY_GLOBAL_UNLOCK(*balancer)) != APR_SUCCESS) {
542 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
543 "proxy: BALANCER: (%s). Unlock failed for pre_request",
547 runtime = find_best_worker(*balancer, r);
549 if ((*balancer)->workers->nelts) {
550 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
551 "proxy: BALANCER: (%s). All workers are in error state",
554 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
555 "proxy: BALANCER: (%s). No workers in balancer",
559 return HTTP_SERVICE_UNAVAILABLE;
561 if ((*balancer)->sticky && runtime) {
563 * This balancer has sticky sessions and the client either has not
564 * supplied any routing information or all workers for this route
565 * including possible redirect and hotstandby workers are in error
566 * state, but we have found another working worker for this
567 * balancer where we can send the request. Thus notice that we have
568 * changed the route to the backend.
570 apr_table_setn(r->subprocess_env, "BALANCER_ROUTE_CHANGED", "1");
575 (*worker)->s->busy++;
577 /* Add balancer/worker info to env. */
578 apr_table_setn(r->subprocess_env,
579 "BALANCER_NAME", (*balancer)->name);
580 apr_table_setn(r->subprocess_env,
581 "BALANCER_WORKER_NAME", (*worker)->s->name);
582 apr_table_setn(r->subprocess_env,
583 "BALANCER_WORKER_ROUTE", (*worker)->s->route);
585 /* Rewrite the url from 'balancer://url'
586 * to the 'worker_scheme://worker_hostname[:worker_port]/url'
587 * This replaces the balancers fictional name with the
588 * real hostname of the elected worker.
590 access_status = rewrite_url(r, *worker, url);
591 /* Add the session route to request notes if present */
593 apr_table_setn(r->notes, "session-sticky", sticky);
594 apr_table_setn(r->notes, "session-route", route);
596 /* Add session info to env. */
597 apr_table_setn(r->subprocess_env,
598 "BALANCER_SESSION_STICKY", sticky);
599 apr_table_setn(r->subprocess_env,
600 "BALANCER_SESSION_ROUTE", route);
602 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
603 "proxy: BALANCER (%s) worker (%s) rewritten to %s",
604 (*balancer)->name, (*worker)->s->name, *url);
606 return access_status;
609 static int proxy_balancer_post_request(proxy_worker *worker,
610 proxy_balancer *balancer,
612 proxy_server_conf *conf)
617 if ((rv = PROXY_GLOBAL_LOCK(balancer)) != APR_SUCCESS) {
618 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
619 "proxy: BALANCER: (%s). Lock failed for post_request",
621 return HTTP_INTERNAL_SERVER_ERROR;
624 if (!apr_is_empty_array(balancer->errstatuses)) {
626 for (i = 0; i < balancer->errstatuses->nelts; i++) {
627 int val = ((int *)balancer->errstatuses->elts)[i];
628 if (r->status == val) {
629 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
630 "proxy: BALANCER: (%s). Forcing recovery for worker (%s), failonstatus %d",
631 balancer->name, worker->s->name, val);
632 worker->s->status |= PROXY_WORKER_IN_ERROR;
633 worker->s->error_time = apr_time_now();
639 if ((rv = PROXY_GLOBAL_UNLOCK(balancer)) != APR_SUCCESS) {
640 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
641 "proxy: BALANCER: (%s). Unlock failed for post_request",
644 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
645 "proxy_balancer_post_request for (%s)", balancer->name);
647 if (worker && worker->s->busy)
654 static void recalc_factors(proxy_balancer *balancer)
657 proxy_worker **workers;
660 /* Recalculate lbfactors */
661 workers = (proxy_worker **)balancer->workers->elts;
662 /* Special case if there is only one worker it's
663 * load factor will always be 1
665 if (balancer->workers->nelts == 1) {
666 (*workers)->s->lbstatus = (*workers)->s->lbfactor = 1;
669 for (i = 0; i < balancer->workers->nelts; i++) {
670 /* Update the status entries */
671 workers[i]->s->lbstatus = workers[i]->s->lbfactor;
675 static apr_status_t lock_remove(void *data)
678 proxy_balancer *balancer;
679 server_rec *s = data;
680 void *sconf = s->module_config;
681 proxy_server_conf *conf = (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
683 balancer = (proxy_balancer *)conf->balancers->elts;
684 for (i = 0; i < conf->balancers->nelts; i++, balancer++) {
685 if (balancer->mutex) {
686 apr_global_mutex_destroy(balancer->mutex);
687 balancer->mutex = NULL;
693 /* post_config hook: */
694 static int balancer_post_config(apr_pool_t *pconf, apr_pool_t *plog,
695 apr_pool_t *ptemp, server_rec *s)
698 void *sconf = s->module_config;
699 proxy_server_conf *conf = (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
700 const char *userdata_key = "mod_proxy_balancer_init";
702 /* balancer_post_config() will be called twice during startup. So, only
703 * set up the static data the 1st time through. */
704 apr_pool_userdata_get(&data, userdata_key, s->process->pool);
706 apr_pool_userdata_set((const void *)1, userdata_key,
707 apr_pool_cleanup_null, s->process->pool);
712 * Get worker slotmem setup
714 storage = ap_lookup_provider(AP_SLOTMEM_PROVIDER_GROUP, "shared", "0");
716 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_EMERG, 0, s,
717 "ap_lookup_provider %s failed", AP_SLOTMEM_PROVIDER_GROUP);
721 * Go thru each Vhost and create the shared mem slotmem for
722 * each balancer's workers
727 proxy_balancer *balancer;
728 sconf = s->module_config;
729 conf = (proxy_server_conf *)ap_get_module_config(sconf, &proxy_module);
731 /* Initialize shared scoreboard data */
732 balancer = (proxy_balancer *)conf->balancers->elts;
733 for (i = 0; i < conf->balancers->nelts; i++, balancer++) {
734 proxy_worker **workers;
735 proxy_worker *worker;
736 ap_slotmem_instance_t *new = NULL;
738 balancer->max_workers = balancer->workers->nelts + balancer->growth;
739 balancer->sname = ap_md5(pconf, (const unsigned char *)balancer->name);
741 /* Create global mutex */
742 rv = ap_global_mutex_create(&(balancer->mutex), NULL, balancer_mutex_type,
743 balancer->sname, s, pconf, 0);
744 if (rv != APR_SUCCESS || !balancer->mutex) {
745 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
746 "mutex creation of %s : %s failed", balancer_mutex_type,
748 return HTTP_INTERNAL_SERVER_ERROR;
751 apr_pool_cleanup_register(pconf, (void *)s, lock_remove,
752 apr_pool_cleanup_null);
754 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, "Doing create: %s (%s), %d, %d",
755 balancer->name, balancer->sname,
756 (int)sizeof(proxy_worker_shared),
757 (int)balancer->max_workers);
759 rv = storage->create(&new, balancer->sname, sizeof(proxy_worker_shared),
760 balancer->max_workers, AP_SLOTMEM_TYPE_PREGRAB, pconf);
761 if (rv != APR_SUCCESS) {
762 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s, "slotmem_create failed");
765 balancer->slot = new;
767 workers = (proxy_worker **)balancer->workers->elts;
768 for (j = 0; j < balancer->workers->nelts; j++, workers++) {
769 proxy_worker_shared *shm;
773 if ((rv = storage->grab(balancer->slot, &index)) != APR_SUCCESS) {
774 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s, "slotmem_grab failed");
778 if ((rv = storage->dptr(balancer->slot, index, (void *)&shm)) != APR_SUCCESS) {
779 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s, "slotmem_dptr failed");
782 if ((rv = ap_proxy_share_worker(worker, shm, index)) != APR_SUCCESS) {
783 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s, "Cannot share worker");
794 /* Manages the loadfactors and member status
796 static int balancer_handler(request_rec *r)
799 proxy_server_conf *conf;
800 proxy_balancer *balancer, *bsel = NULL;
801 proxy_worker *worker, *wsel = NULL;
802 proxy_worker **workers = NULL;
808 /* is this for us? */
809 if (strcmp(r->handler, "balancer-manager")) {
813 r->allowed = (AP_METHOD_BIT << M_GET);
814 if (r->method_number != M_GET) {
818 sconf = r->server->module_config;
819 conf = (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
820 params = apr_table_make(r->pool, 10);
823 char *args = apr_pstrdup(r->pool, r->args);
825 while (args && *args) {
826 if ((val = ap_strchr(args, '='))) {
828 if ((tok = ap_strchr(val, '&')))
831 * Special case: workers are allowed path information
833 if ((access_status = ap_unescape_url(val)) != OK)
834 if (strcmp(args, "w") || (access_status != HTTP_NOT_FOUND))
835 return access_status;
836 apr_table_setn(params, args, val);
840 return HTTP_BAD_REQUEST;
844 if ((name = apr_table_get(params, "b")))
845 bsel = ap_proxy_get_balancer(r->pool, conf,
846 apr_pstrcat(r->pool, BALANCER_PREFIX, name, NULL));
848 if ((name = apr_table_get(params, "w"))) {
849 wsel = ap_proxy_get_worker(r->pool, bsel, conf, name);
853 /* Check that the supplied nonce matches this server's nonce;
854 * otherwise ignore all parameters, to prevent a CSRF attack. */
855 if (*balancer_nonce &&
856 ((name = apr_table_get(params, "nonce")) == NULL
857 || strcmp(balancer_nonce, name) != 0)) {
858 apr_table_clear(params);
861 /* First set the params */
863 * Note that it is not possible set the proxy_balancer because it is not
868 if ((val = apr_table_get(params, "lf"))) {
869 int ival = atoi(val);
870 if (ival >= 1 && ival <= 100) {
871 wsel->s->lbfactor = ival;
873 recalc_factors(bsel);
876 if ((val = apr_table_get(params, "wr"))) {
877 if (strlen(val) && strlen(val) < sizeof(wsel->s->route))
878 strcpy(wsel->s->route, val);
880 *wsel->s->route = '\0';
882 if ((val = apr_table_get(params, "rr"))) {
883 if (strlen(val) && strlen(val) < sizeof(wsel->s->redirect))
884 strcpy(wsel->s->redirect, val);
886 *wsel->s->redirect = '\0';
888 if ((val = apr_table_get(params, "dw"))) {
889 if (!strcasecmp(val, "Disable"))
890 wsel->s->status |= PROXY_WORKER_DISABLED;
891 else if (!strcasecmp(val, "Enable"))
892 wsel->s->status &= ~PROXY_WORKER_DISABLED;
894 if ((val = apr_table_get(params, "ls"))) {
895 int ival = atoi(val);
896 if (ival >= 0 && ival <= 99) {
897 wsel->s->lbset = ival;
902 if (apr_table_get(params, "xml")) {
903 ap_set_content_type(r, "text/xml");
904 ap_rputs("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n", r);
905 ap_rputs("<httpd:manager xmlns:httpd=\"http://httpd.apache.org\">\n", r);
906 ap_rputs(" <httpd:balancers>\n", r);
907 balancer = (proxy_balancer *)conf->balancers->elts;
908 for (i = 0; i < conf->balancers->nelts; i++) {
909 ap_rputs(" <httpd:balancer>\n", r);
910 ap_rvputs(r, " <httpd:name>", balancer->name, "</httpd:name>\n", NULL);
911 ap_rputs(" <httpd:workers>\n", r);
912 workers = (proxy_worker **)balancer->workers->elts;
913 for (n = 0; n < balancer->workers->nelts; n++) {
915 ap_rputs(" <httpd:worker>\n", r);
916 ap_rvputs(r, " <httpd:scheme>", worker->s->scheme,
917 "</httpd:scheme>\n", NULL);
918 ap_rvputs(r, " <httpd:hostname>", worker->s->hostname,
919 "</httpd:hostname>\n", NULL);
920 ap_rprintf(r, " <httpd:loadfactor>%d</httpd:loadfactor>\n",
921 worker->s->lbfactor);
922 ap_rputs(" </httpd:worker>\n", r);
925 ap_rputs(" </httpd:workers>\n", r);
926 ap_rputs(" </httpd:balancer>\n", r);
929 ap_rputs(" </httpd:balancers>\n", r);
930 ap_rputs("</httpd:manager>", r);
933 ap_set_content_type(r, "text/html; charset=ISO-8859-1");
934 ap_rputs(DOCTYPE_HTML_3_2
935 "<html><head><title>Balancer Manager</title></head>\n", r);
936 ap_rputs("<body><h1>Load Balancer Manager for ", r);
937 ap_rvputs(r, ap_get_server_name(r), "</h1>\n\n", NULL);
938 ap_rvputs(r, "<dl><dt>Server Version: ",
939 ap_get_server_description(), "</dt>\n", NULL);
940 ap_rvputs(r, "<dt>Server Built: ",
941 ap_get_server_built(), "\n</dt></dl>\n", NULL);
942 balancer = (proxy_balancer *)conf->balancers->elts;
943 for (i = 0; i < conf->balancers->nelts; i++) {
945 ap_rputs("<hr />\n<h3>LoadBalancer Status for ", r);
946 ap_rvputs(r, balancer->name, "</h3>\n\n", NULL);
947 ap_rputs("\n\n<table border=\"0\" style=\"text-align: left;\"><tr>"
948 "<th>StickySession</th><th>Timeout</th><th>FailoverAttempts</th><th>Method</th>"
950 if (balancer->sticky) {
951 if (strcmp(balancer->sticky, balancer->sticky_path)) {
952 ap_rvputs(r, "<td>", balancer->sticky, " | ",
953 balancer->sticky_path, NULL);
956 ap_rvputs(r, "<td>", balancer->sticky, NULL);
960 ap_rputs("<td> - ", r);
962 ap_rprintf(r, "</td><td>%" APR_TIME_T_FMT "</td>",
963 apr_time_sec(balancer->timeout));
964 ap_rprintf(r, "<td>%d</td>\n", balancer->max_attempts);
965 ap_rprintf(r, "<td>%s</td>\n",
966 balancer->lbmethod->name);
967 ap_rputs("</table>\n<br />", r);
968 ap_rputs("\n\n<table border=\"0\" style=\"text-align: left;\"><tr>"
969 "<th>Worker URL</th>"
970 "<th>Route</th><th>RouteRedir</th>"
971 "<th>Factor</th><th>Set</th><th>Status</th>"
972 "<th>Elected</th><th>To</th><th>From</th>"
975 workers = (proxy_worker **)balancer->workers->elts;
976 for (n = 0; n < balancer->workers->nelts; n++) {
979 ap_rvputs(r, "<tr>\n<td><a href=\"", r->uri, "?b=",
980 balancer->name + sizeof(BALANCER_PREFIX) - 1, "&w=",
981 ap_escape_uri(r->pool, worker->s->name),
982 "&nonce=", balancer->nonce,
984 ap_rvputs(r, worker->s->name, "</a></td>", NULL);
985 ap_rvputs(r, "<td>", ap_escape_html(r->pool, worker->s->route),
987 ap_rvputs(r, "</td><td>",
988 ap_escape_html(r->pool, worker->s->redirect), NULL);
989 ap_rprintf(r, "</td><td>%d</td>", worker->s->lbfactor);
990 ap_rprintf(r, "<td>%d</td><td>", worker->s->lbset);
991 if (worker->s->status & PROXY_WORKER_DISABLED)
993 if (worker->s->status & PROXY_WORKER_IN_ERROR)
995 if (worker->s->status & PROXY_WORKER_STOPPED)
996 ap_rputs("Stop ", r);
997 if (worker->s->status & PROXY_WORKER_HOT_STANDBY)
998 ap_rputs("Stby ", r);
999 if (PROXY_WORKER_IS_USABLE(worker))
1001 if (!PROXY_WORKER_IS_INITIALIZED(worker))
1003 ap_rputs("</td>", r);
1004 ap_rprintf(r, "<td>%" APR_SIZE_T_FMT "</td><td>", worker->s->elected);
1005 ap_rputs(apr_strfsize(worker->s->transferred, fbuf), r);
1006 ap_rputs("</td><td>", r);
1007 ap_rputs(apr_strfsize(worker->s->read, fbuf), r);
1008 ap_rputs("</td></tr>\n", r);
1012 ap_rputs("</table>\n", r);
1015 ap_rputs("<hr />\n", r);
1017 ap_rputs("<h3>Edit worker settings for ", r);
1018 ap_rvputs(r, wsel->s->name, "</h3>\n", NULL);
1019 ap_rvputs(r, "<form method=\"GET\" action=\"", NULL);
1020 ap_rvputs(r, r->uri, "\">\n<dl>", NULL);
1021 ap_rputs("<table><tr><td>Load factor:</td><td><input name=\"lf\" type=text ", r);
1022 ap_rprintf(r, "value=\"%d\"></td></tr>\n", wsel->s->lbfactor);
1023 ap_rputs("<tr><td>LB Set:</td><td><input name=\"ls\" type=text ", r);
1024 ap_rprintf(r, "value=\"%d\"></td></tr>\n", wsel->s->lbset);
1025 ap_rputs("<tr><td>Route:</td><td><input name=\"wr\" type=text ", r);
1026 ap_rvputs(r, "value=\"", ap_escape_html(r->pool, wsel->s->route),
1028 ap_rputs("\"></td></tr>\n", r);
1029 ap_rputs("<tr><td>Route Redirect:</td><td><input name=\"rr\" type=text ", r);
1030 ap_rvputs(r, "value=\"", ap_escape_html(r->pool, wsel->s->redirect),
1032 ap_rputs("\"></td></tr>\n", r);
1033 ap_rputs("<tr><td>Status:</td><td>Disabled: <input name=\"dw\" value=\"Disable\" type=radio", r);
1034 if (wsel->s->status & PROXY_WORKER_DISABLED)
1035 ap_rputs(" checked", r);
1036 ap_rputs("> | Enabled: <input name=\"dw\" value=\"Enable\" type=radio", r);
1037 if (!(wsel->s->status & PROXY_WORKER_DISABLED))
1038 ap_rputs(" checked", r);
1039 ap_rputs("></td></tr>\n", r);
1040 ap_rputs("<tr><td colspan=2><input type=submit value=\"Submit\"></td></tr>\n", r);
1041 ap_rvputs(r, "</table>\n<input type=hidden name=\"w\" ", NULL);
1042 ap_rvputs(r, "value=\"", ap_escape_uri(r->pool, wsel->s->name), "\">\n", NULL);
1043 ap_rvputs(r, "<input type=hidden name=\"b\" ", NULL);
1044 ap_rvputs(r, "value=\"", bsel->name + sizeof(BALANCER_PREFIX) - 1,
1046 ap_rvputs(r, "<input type=hidden name=\"nonce\" value=\"",
1047 bsel->nonce, "\">\n", NULL);
1048 ap_rvputs(r, "</form>\n", NULL);
1049 ap_rputs("<hr />\n", r);
1051 ap_rputs(ap_psignature("",r), r);
1052 ap_rputs("</body></html>\n", r);
1057 static void balancer_child_init(apr_pool_t *p, server_rec *s)
1060 proxy_balancer *balancer;
1062 void *sconf = s->module_config;
1063 proxy_server_conf *conf = (proxy_server_conf *)ap_get_module_config(sconf, &proxy_module);
1066 balancer = (proxy_balancer *)conf->balancers->elts;
1067 for (i = 0; i < conf->balancers->nelts; i++) {
1072 * for each balancer we need to init the global
1073 * mutex and then attach to the shared worker shm
1075 if (!balancer->mutex) {
1076 ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
1077 "no mutex %s: %s", balancer->name,
1078 balancer_mutex_type);
1082 /* Re-open the mutex for the child. */
1083 rv = apr_global_mutex_child_init(&(balancer->mutex),
1084 apr_global_mutex_lockfile(balancer->mutex),
1086 if (rv != APR_SUCCESS) {
1087 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, s,
1088 "Failed to reopen mutex %s: %s in child",
1089 balancer->name, balancer_mutex_type);
1090 exit(1); /* Ugly, but what else? */
1094 storage->attach(&(balancer->slot), balancer->sname, &size, &num, p);
1095 if (!balancer->slot) {
1096 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_EMERG, 0, s, "slotmem_attach failed");
1097 exit(1); /* Ugly, but what else? */
1099 if (balancer->lbmethod && balancer->lbmethod->reset)
1100 balancer->lbmethod->reset(balancer, s);
1101 init_balancer_members(conf, s, balancer);
1109 static void ap_proxy_balancer_register_hook(apr_pool_t *p)
1111 /* Only the mpm_winnt has child init hook handler.
1112 * make sure that we are called after the mpm
1115 static const char *const aszPred[] = { "mpm_winnt.c", NULL};
1116 /* manager handler */
1117 ap_hook_post_config(balancer_post_config, NULL, NULL, APR_HOOK_MIDDLE);
1118 ap_hook_pre_config(balancer_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
1119 ap_hook_handler(balancer_handler, NULL, NULL, APR_HOOK_FIRST);
1120 ap_hook_child_init(balancer_child_init, aszPred, NULL, APR_HOOK_MIDDLE);
1121 proxy_hook_pre_request(proxy_balancer_pre_request, NULL, NULL, APR_HOOK_FIRST);
1122 proxy_hook_post_request(proxy_balancer_post_request, NULL, NULL, APR_HOOK_FIRST);
1123 proxy_hook_canon_handler(proxy_balancer_canon, NULL, NULL, APR_HOOK_FIRST);
1126 AP_DECLARE_MODULE(proxy_balancer) = {
1127 STANDARD20_MODULE_STUFF,
1128 NULL, /* create per-directory config structure */
1129 NULL, /* merge per-directory config structures */
1130 NULL, /* create per-server config structure */
1131 NULL, /* merge per-server config structures */
1132 NULL, /* command apr_table_t */
1133 ap_proxy_balancer_register_hook /* register hooks */