], [], [ap_have_apr_siphash=yes], [ap_have_apr_siphash=no])
+ CPPFLAGS="$saved_CPPFLAGS"
+ if test "$ap_have_apr_siphash" = "no"; then
+ AC_MSG_WARN([mod_proxy_beacon needs apr_siphash.h, from APR-util 1.6 or later])
+ enable_proxy_beacon=no
+ fi
+], [proxy,watchdog,proxy_balancer])
+
APR_ADDTO(INCLUDES, [-I\$(top_srcdir)/$modpath_current -I\$(top_srcdir)/modules/http2])
module_selection=$save_module_selection
diff --git a/modules/proxy/mod_proxy.c b/modules/proxy/mod_proxy.c
index 521e8f21837..836219a44bf 100644
--- a/modules/proxy/mod_proxy.c
+++ b/modules/proxy/mod_proxy.c
@@ -71,11 +71,11 @@ proxy_wstat_t PROXY_DECLARE_DATA proxy_wstat_tbl[] = {
{PROXY_WORKER_HOT_SPARE, PROXY_WORKER_HOT_SPARE_FLAG, "Spar "},
{PROXY_WORKER_FREE, PROXY_WORKER_FREE_FLAG, "Free "},
{PROXY_WORKER_HC_FAIL, PROXY_WORKER_HC_FAIL_FLAG, "HcFl "},
+ {PROXY_WORKER_BEACON, PROXY_WORKER_BEACON_FLAG, "Bcn "},
{0x0, '\0', NULL}
};
static const char * const proxy_id = "proxy";
-apr_global_mutex_t *proxy_mutex = NULL;
/*
* A Web proxy module. Stages:
@@ -1480,7 +1480,7 @@ static int proxy_handler(request_rec *r)
*/
if (balancer
&& !(worker->s->status & PROXY_WORKER_IGNORE_ERRORS)) {
- worker->s->status |= PROXY_WORKER_IN_ERROR;
+ ap_proxy_set_wstatus(PROXY_WORKER_IN_ERROR_FLAG, 1, worker);
worker->s->error_time = apr_time_now();
}
break;
@@ -1492,7 +1492,7 @@ static int proxy_handler(request_rec *r)
*/
if (balancer
&& !(worker->s->status & PROXY_WORKER_IGNORE_ERRORS)) {
- worker->s->status |= PROXY_WORKER_IN_ERROR;
+ ap_proxy_set_wstatus(PROXY_WORKER_IN_ERROR_FLAG, 1, worker);
worker->s->error_time = apr_time_now();
}
}
@@ -3095,12 +3095,11 @@ static int proxy_post_config(apr_pool_t *pconf, apr_pool_t *plog,
apr_pool_t *ptemp, server_rec *main_s)
{
server_rec *s = main_s;
- apr_status_t rv = ap_global_mutex_create(&proxy_mutex, NULL,
- proxy_id, NULL, s, pconf, 0);
- if (rv != APR_SUCCESS) {
- ap_log_perror(APLOG_MARK, APLOG_CRIT, rv, plog, APLOGNO(02478)
- "failed to create %s mutex", proxy_id);
- return rv;
+ int rc;
+
+ rc = proxy_util_post_config(pconf, plog, ptemp, main_s);
+ if (rc != OK) {
+ return rc;
}
proxy_ssl_enable = APR_RETRIEVE_OPTIONAL_FN(ssl_proxy_enable);
@@ -3110,7 +3109,7 @@ static int proxy_post_config(apr_pool_t *pconf, apr_pool_t *plog,
ap_proxy_strmatch_domain = apr_strmatch_precompile(pconf, "domain=", 0);
for (; s; s = s->next) {
- int rc, i;
+ int i;
proxy_server_conf *sconf =
ap_get_module_config(s->module_config, &proxy_module);
ap_conf_vector_t **sections =
@@ -3139,6 +3138,7 @@ static int proxy_status_hook(request_rec *r, int flags)
ap_get_module_config(sconf, &proxy_module);
proxy_balancer *balancer = NULL;
proxy_worker **worker = NULL;
+ const apr_array_header_t *members;
if (conf->balancers->nelts == 0 ||
conf->proxy_status == status_off)
@@ -3179,8 +3179,14 @@ static int proxy_status_hook(request_rec *r, int flags)
ap_rprintf(r, "ProxyBalancer[%d]Name: %s\n", i, balancer->s->name);
}
- worker = (proxy_worker **)balancer->workers->elts;
- for (n = 0; n < balancer->workers->nelts; n++) {
+ /* The workers array grows at run time (balancer-manager, sync of the
+ * workers other children added): walk the snapshot of
+ * ap_proxy_balancer_snap_workers(), not to hold the balancer's lock
+ * while writing the response.
+ */
+ members = ap_proxy_balancer_snap_workers(balancer, r->pool);
+ worker = (proxy_worker **)members->elts;
+ for (n = 0; n < members->nelts; n++) {
char fbuf[50];
if (!(flags & AP_STATUS_SHORT)) {
ap_rvputs(r, "\n| ", (*worker)->s->scheme, " | ", NULL);
@@ -3253,15 +3259,6 @@ static void child_init(apr_pool_t *p, server_rec *s)
{
proxy_worker *reverse = NULL;
- apr_status_t rv = apr_global_mutex_child_init(&proxy_mutex,
- apr_global_mutex_lockfile(proxy_mutex),
- p);
- if (rv != APR_SUCCESS) {
- ap_log_error(APLOG_MARK, APLOG_CRIT, rv, s, APLOGNO(02479)
- "could not init proxy_mutex in child");
- exit(1); /* Ugly, but what else? */
- }
-
/* TODO */
while (s) {
void *sconf = s->module_config;
@@ -3334,6 +3331,10 @@ static void child_init(apr_pool_t *p, server_rec *s)
static int proxy_pre_config(apr_pool_t *pconf, apr_pool_t *plog,
apr_pool_t *ptemp)
{
+ /* The "proxy" mutex is a thread mutex now (see proxy_util.c), but the
+ * type stays registered so that existing Mutex directives naming it are
+ * still accepted; they have no effect.
+ */
apr_status_t rv = ap_mutex_register(pconf, proxy_id, NULL,
APR_LOCK_DEFAULT, 0);
if (rv != APR_SUCCESS) {
diff --git a/modules/proxy/mod_proxy.h b/modules/proxy/mod_proxy.h
index 329d10fdaa9..d94163f1f7c 100644
--- a/modules/proxy/mod_proxy.h
+++ b/modules/proxy/mod_proxy.h
@@ -329,6 +329,7 @@ struct proxy_conn_pool {
#define PROXY_WORKER_FREE 0x0200
#define PROXY_WORKER_HC_FAIL 0x0400
#define PROXY_WORKER_HOT_SPARE 0x0800
+#define PROXY_WORKER_BEACON 0x1000 /* created and managed by mod_proxy_beacon */
/* worker status flags */
#define PROXY_WORKER_INITIALIZED_FLAG 'O'
@@ -343,6 +344,7 @@ struct proxy_conn_pool {
#define PROXY_WORKER_FREE_FLAG 'F'
#define PROXY_WORKER_HC_FAIL_FLAG 'C'
#define PROXY_WORKER_HOT_SPARE_FLAG 'R'
+#define PROXY_WORKER_BEACON_FLAG 'B'
#define PROXY_WORKER_NOT_USABLE_BITMAP ( PROXY_WORKER_IN_SHUTDOWN | \
PROXY_WORKER_DISABLED | PROXY_WORKER_STOPPED | PROXY_WORKER_IN_ERROR | \
@@ -577,6 +579,11 @@ struct proxy_balancer {
unsigned int failontimeout_set:1;
unsigned int growth_set:1;
unsigned int lbmethod_set:1;
+ unsigned int ungrowable:1; /* no worker can be added at run time (no
+ * growth in any copy of the balancer),
+ * so the workers array never changes
+ * (enforced by ap_proxy_sync_balancer()
+ * and balancer_add_worker()) */
ap_conf_vector_t *section_config; /* -section wherein defined */
};
@@ -590,8 +597,21 @@ struct proxy_balancer_method {
apr_status_t (*updatelbstatus)(proxy_balancer *balancer, proxy_worker *elected, server_rec *s);
};
+#if APR_HAS_THREADS
#define PROXY_THREAD_LOCK(x) ( (x) && (x)->tmutex ? apr_thread_mutex_lock((x)->tmutex) : APR_SUCCESS)
#define PROXY_THREAD_UNLOCK(x) ( (x) && (x)->tmutex ? apr_thread_mutex_unlock((x)->tmutex) : APR_SUCCESS)
+#else
+/* Without threads, a function call rather than a constant so that the macros
+ * can be used as statements without "statement with no effect" warnings
+ * (internal to these macros, not API).
+ */
+static APR_INLINE apr_status_t ap_proxy__nolock(void)
+{
+ return APR_SUCCESS;
+}
+#define PROXY_THREAD_LOCK(x) ((void)(x), ap_proxy__nolock())
+#define PROXY_THREAD_UNLOCK(x) ((void)(x), ap_proxy__nolock())
+#endif
#define PROXY_GLOBAL_LOCK(x) ( (x) && (x)->gmutex ? apr_global_mutex_lock((x)->gmutex) : APR_SUCCESS)
#define PROXY_GLOBAL_UNLOCK(x) ( (x) && (x)->gmutex ? apr_global_mutex_unlock((x)->gmutex) : APR_SUCCESS)
@@ -785,6 +805,9 @@ PROXY_DECLARE(int) ap_proxy_worker_can_upgrade(apr_pool_t *p,
* @param url url to find the worker from
* @param mask bitmask of AP_PROXY_WORKER_IS_*
* @return proxy_worker or NULL if not found
+ * @note At run time, a caller looking in a balancer holds its thread lock
+ * (PROXY_THREAD_LOCK()) unless the balancer's ungrowable is set: its
+ * workers array grows under that lock.
*/
PROXY_DECLARE(proxy_worker *) ap_proxy_get_worker_ex(apr_pool_t *p,
proxy_balancer *balancer,
@@ -799,6 +822,7 @@ PROXY_DECLARE(proxy_worker *) ap_proxy_get_worker_ex(apr_pool_t *p,
* @param conf current proxy server configuration
* @param url url to find the worker from
* @return proxy_worker or NULL if not found
+ * @note Same locking as ap_proxy_get_worker_ex().
*/
PROXY_DECLARE(proxy_worker *) ap_proxy_get_worker(apr_pool_t *p,
proxy_balancer *balancer,
diff --git a/modules/proxy/mod_proxy_balancer.c b/modules/proxy/mod_proxy_balancer.c
index e8a5be228c2..0527d1c2dfd 100644
--- a/modules/proxy/mod_proxy_balancer.c
+++ b/modules/proxy/mod_proxy_balancer.c
@@ -341,7 +341,9 @@ static proxy_worker *find_best_worker(proxy_balancer *balancer,
request_rec *r)
{
proxy_worker *candidate = NULL;
+#if APR_HAS_THREADS
apr_status_t rv;
+#endif
#if APR_HAS_THREADS
if ((rv = PROXY_THREAD_LOCK(balancer)) != APR_SUCCESS) {
@@ -450,7 +452,7 @@ static void force_recovery(proxy_balancer *balancer, server_rec *s)
worker = (proxy_worker **)balancer->workers->elts;
for (i = 0; i < balancer->workers->nelts; i++, worker++) {
++(*worker)->s->retries;
- (*worker)->s->status &= ~PROXY_WORKER_IN_ERROR;
+ ap_proxy_set_wstatus(PROXY_WORKER_IN_ERROR_FLAG, 0, *worker);
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(01165)
"%s: Forcing recovery for worker (%s:%d)",
balancer->s->name, (*worker)->s->hostname_ex,
@@ -479,7 +481,9 @@ static int proxy_balancer_pre_request(proxy_worker **worker,
proxy_worker *runtime;
char *route = NULL;
const char *sticky = NULL;
+#if APR_HAS_THREADS
apr_status_t rv;
+#endif
*worker = NULL;
/* Step 1: check if the url is for us
@@ -653,7 +657,9 @@ static int proxy_balancer_post_request(proxy_worker *worker,
proxy_server_conf *conf)
{
+#if APR_HAS_THREADS
apr_status_t rv;
+#endif
#if APR_HAS_THREADS
if ((rv = PROXY_THREAD_LOCK(balancer)) != APR_SUCCESS) {
@@ -676,7 +682,7 @@ static int proxy_balancer_post_request(proxy_worker *worker,
"balancer parameter",
balancer->s->name, ap_proxy_worker_name(r->pool, worker),
val);
- worker->s->status |= PROXY_WORKER_IN_ERROR;
+ ap_proxy_set_wstatus(PROXY_WORKER_IN_ERROR_FLAG, 1, worker);
worker->s->error_time = apr_time_now();
break;
}
@@ -690,7 +696,7 @@ static int proxy_balancer_post_request(proxy_worker *worker,
"%s: Forcing worker (%s) into error state "
"due to timeout and 'failontimeout' parameter being set",
balancer->s->name, ap_proxy_worker_name(r->pool, worker));
- worker->s->status |= PROXY_WORKER_IN_ERROR;
+ ap_proxy_set_wstatus(PROXY_WORKER_IN_ERROR_FLAG, 1, worker);
worker->s->error_time = apr_time_now();
}
@@ -706,11 +712,29 @@ static int proxy_balancer_post_request(proxy_worker *worker,
return OK;
}
+/* ap_proxy_get_worker() under the balancer's lock when workers can be added
+ * (bsel NULL: the server's workers, a configuration-time array). */
+static proxy_worker *get_balancer_worker(request_rec *r, proxy_balancer *bsel,
+ proxy_server_conf *conf,
+ const char *name)
+{
+ proxy_worker *worker;
+
+ if (!bsel) {
+ return ap_proxy_get_worker(r->pool, NULL, conf, name);
+ }
+ PROXY_WORKERS_LOCK(bsel);
+ worker = ap_proxy_get_worker(r->pool, bsel, conf, name);
+ PROXY_WORKERS_UNLOCK(bsel);
+ return worker;
+}
+
static void recalc_factors(proxy_balancer *balancer)
{
int i;
proxy_worker **workers;
+ PROXY_WORKERS_LOCK(balancer);
/* Recalculate lbfactors */
workers = (proxy_worker **)balancer->workers->elts;
@@ -719,12 +743,15 @@ static void recalc_factors(proxy_balancer *balancer)
*/
if (balancer->workers->nelts == 1) {
(*workers)->s->lbstatus = (*workers)->s->lbfactor = 100;
- return;
}
- for (i = 0; i < balancer->workers->nelts; i++) {
- /* Update the status entries */
- workers[i]->s->lbstatus = workers[i]->s->lbfactor;
+ else {
+ for (i = 0; i < balancer->workers->nelts; i++) {
+ /* Update the status entries */
+ workers[i]->s->lbstatus = workers[i]->s->lbfactor;
+ }
}
+
+ PROXY_WORKERS_UNLOCK(balancer);
}
static apr_status_t lock_remove(void *data)
@@ -856,6 +883,40 @@ static apr_array_header_t *make_servers_ids(server_rec *main_s, apr_pool_t *p)
return ids;
}
+/*
+ * Workers can be added at run time only to a balancer with a growth (with
+ * none, all of its worker slots hold configured workers), but the copies of a
+ * balancer that the vhosts inherit (merge_balancers()) share its workers
+ * array: mark ungrowable the copies of an array that none of them can grow.
+ */
+static void mark_ungrowable_balancers(server_rec *main_s, apr_pool_t *p)
+{
+ apr_hash_t *growing = apr_hash_make(p);
+ proxy_server_conf *conf;
+ proxy_balancer *balancer;
+ server_rec *s;
+ int i;
+
+ for (s = main_s; s; s = s->next) {
+ conf = ap_get_module_config(s->module_config, &proxy_module);
+ balancer = (proxy_balancer *)conf->balancers->elts;
+ for (i = 0; i < conf->balancers->nelts; i++, balancer++) {
+ if (balancer->growth > 0) {
+ apr_hash_set(growing, &balancer->workers,
+ sizeof(balancer->workers), balancer);
+ }
+ }
+ }
+ for (s = main_s; s; s = s->next) {
+ conf = ap_get_module_config(s->module_config, &proxy_module);
+ balancer = (proxy_balancer *)conf->balancers->elts;
+ for (i = 0; i < conf->balancers->nelts; i++, balancer++) {
+ balancer->ungrowable = !apr_hash_get(growing, &balancer->workers,
+ sizeof(balancer->workers));
+ }
+ }
+}
+
/* post_config hook: */
static int balancer_post_config(apr_pool_t *pconf, apr_pool_t *plog,
apr_pool_t *ptemp, server_rec *s)
@@ -895,6 +956,7 @@ static int balancer_post_config(apr_pool_t *pconf, apr_pool_t *plog,
}
ids = make_servers_ids(s, ptemp);
+ mark_ungrowable_balancers(s, ptemp);
tstamp = apr_time_now();
/*
@@ -1121,6 +1183,124 @@ static int safe_referer(request_rec *r, const char *ref)
return strcasecmp(uri.hostname, ap_get_server_name(r)) == 0;
}
+/*
+ * Add the worker `url` to `bsel` at runtime. Returns APR_SUCCESS, or
+ * HTTP_BAD_REQUEST if it could not be added. The worker is created disabled.
+ *
+ * The global lock is taken first, so that no other process adds a worker
+ * between the check that it is not there yet and its slot being taken. The
+ * balancer's thread lock follows, for the part that changes this process's
+ * worker array: request threads walk it holding that lock, so they never see a
+ * worker that is not complete, and they do not wait for the global lock. Both
+ * come before proxy_mutex, which sync, definition and initialization take
+ * inside. A worker whose sharing fails is taken out of the array again and its
+ * slot given back.
+ */
+static int balancer_add_worker(request_rec *r, proxy_balancer *bsel,
+ proxy_server_conf *conf, const char *url,
+ const char *flags)
+{
+ proxy_worker *nworker;
+ proxy_worker_shared *shm;
+ unsigned int index = 0;
+ apr_status_t rv;
+ char *ret;
+ int status = HTTP_BAD_REQUEST;
+#if APR_HAS_THREADS
+ int thread_locked = 0;
+
+ if ((rv = PROXY_GLOBAL_LOCK(bsel)) != APR_SUCCESS) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01194)
+ "%s: Lock failed for adding worker", bsel->s->name);
+ return HTTP_BAD_REQUEST;
+ }
+ if ((rv = PROXY_THREAD_LOCK(bsel)) != APR_SUCCESS) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(10658)
+ "%s: Thread lock failed for adding worker",
+ bsel->s->name);
+ goto done;
+ }
+ thread_locked = 1;
+#endif
+
+ /* Another child may have added it since this one last synced. */
+ ap_proxy_sync_balancer(bsel, r->server, conf);
+ if (ap_proxy_get_worker(r->pool, bsel, conf, url)
+ || bsel->ungrowable
+ || !storage->num_free_slots(bsel->wslot)) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(10164)
+ "%s: failed to add worker %s", bsel->s->name, url);
+ goto done;
+ }
+
+ ret = ap_proxy_define_worker(conf->pool, &nworker, bsel, conf, url, 0);
+ if (ret) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(10163)
+ "%s: failed to add worker %s", bsel->s->name, url);
+ goto done;
+ }
+ /* nworker is now the last element of bsel->workers. */
+ PROXY_COPY_CONF_PARAMS(nworker, conf);
+ /* Optional status flags to create the worker with, and DISABLED always:
+ * set before ap_proxy_share_worker() copies the worker to shm, so that no
+ * child can ever find it there without them (a creator such as
+ * mod_proxy_beacon leaves no window in which the worker exists without its
+ * mark, or is enabled before it has been told to). */
+ ap_proxy_set_wstatus(PROXY_WORKER_DISABLED_FLAG, 1, nworker);
+ if (flags) {
+ for (; *flags; flags++) {
+ ap_proxy_set_wstatus(*flags, 1, nworker);
+ }
+ }
+ if ((rv = storage->grab(bsel->wslot, &index)) != APR_SUCCESS) {
+ ap_log_rerror(APLOG_MARK, APLOG_EMERG, rv, r, APLOGNO(01195)
+ "worker slotmem_grab failed");
+ apr_array_pop(bsel->workers);
+ goto done;
+ }
+ if ((rv = storage->dptr(bsel->wslot, index, (void *)&shm)) != APR_SUCCESS) {
+ ap_log_rerror(APLOG_MARK, APLOG_EMERG, rv, r, APLOGNO(01197)
+ "worker slotmem_dptr failed");
+ storage->release(bsel->wslot, index);
+ apr_array_pop(bsel->workers);
+ goto done;
+ }
+ if ((rv = ap_proxy_share_worker(nworker, shm, index)) != APR_SUCCESS) {
+ ap_log_rerror(APLOG_MARK, APLOG_EMERG, rv, r, APLOGNO(01199)
+ "Cannot share worker");
+ storage->release(bsel->wslot, index);
+ apr_array_pop(bsel->workers);
+ goto done;
+ }
+ if ((rv = ap_proxy_initialize_worker(nworker, r->server, conf->pool)) != APR_SUCCESS) {
+ ap_log_rerror(APLOG_MARK, APLOG_EMERG, rv, r, APLOGNO(01201)
+ "Cannot init worker");
+ /* Other children find slots by their hash: empty it. */
+ memset(shm, 0, sizeof(*shm));
+ storage->release(bsel->wslot, index);
+ apr_array_pop(bsel->workers);
+ goto done;
+ }
+ /* sync all timestamps */
+ bsel->wupdated = bsel->s->wupdated = nworker->s->updated = apr_time_now();
+ status = APR_SUCCESS;
+
+done:
+#if APR_HAS_THREADS
+ if (thread_locked
+ && (rv = PROXY_THREAD_UNLOCK(bsel)) != APR_SUCCESS) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(10659)
+ "%s: Thread unlock failed for adding worker",
+ bsel->s->name);
+ }
+ if ((rv = PROXY_GLOBAL_UNLOCK(bsel)) != APR_SUCCESS) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01203)
+ "%s: Unlock failed for adding worker", bsel->s->name);
+ }
+#endif
+ return status;
+}
+
/*
* Process the paramters and add or update the worker of the
* balancer. Must only be called if the nonce has been validated to
@@ -1132,7 +1312,6 @@ static int balancer_process_balancer_worker(request_rec *r, proxy_server_conf *c
apr_table_t *params)
{
- apr_status_t rv;
/* First set the params */
if (wsel) {
const char *val;
@@ -1296,97 +1475,31 @@ static int balancer_process_balancer_worker(request_rec *r, proxy_server_conf *c
if ((val = apr_table_get(params, "b_wyes")) &&
(*val == '1' && *(val+1) == '\0') &&
(val = apr_table_get(params, "b_nwrkr"))) {
- char *ret;
- proxy_worker *nworker;
- nworker = ap_proxy_get_worker(r->pool, bsel, conf, val);
- if (!nworker && storage->num_free_slots(bsel->wslot)) {
-#if APR_HAS_THREADS
- if ((rv = PROXY_GLOBAL_LOCK(bsel)) != APR_SUCCESS) {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01194)
- "%s: Lock failed for adding worker",
- bsel->s->name);
- }
-#endif
- ret = ap_proxy_define_worker(conf->pool, &nworker, bsel, conf, val, 0);
- if (!ret) {
- unsigned int index;
- proxy_worker_shared *shm;
- PROXY_COPY_CONF_PARAMS(nworker, conf);
- if ((rv = storage->grab(bsel->wslot, &index)) != APR_SUCCESS) {
- ap_log_rerror(APLOG_MARK, APLOG_EMERG, rv, r, APLOGNO(01195)
- "worker slotmem_grab failed");
-#if APR_HAS_THREADS
- if ((rv = PROXY_GLOBAL_UNLOCK(bsel)) != APR_SUCCESS) {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01196)
- "%s: Unlock failed for adding worker",
- bsel->s->name);
- }
-#endif
- return HTTP_BAD_REQUEST;
- }
- if ((rv = storage->dptr(bsel->wslot, index, (void *)&shm)) != APR_SUCCESS) {
- ap_log_rerror(APLOG_MARK, APLOG_EMERG, rv, r, APLOGNO(01197)
- "worker slotmem_dptr failed");
-#if APR_HAS_THREADS
- if ((rv = PROXY_GLOBAL_UNLOCK(bsel)) != APR_SUCCESS) {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01198)
- "%s: Unlock failed for adding worker",
- bsel->s->name);
- }
-#endif
- return HTTP_BAD_REQUEST;
- }
- if ((rv = ap_proxy_share_worker(nworker, shm, index)) != APR_SUCCESS) {
- ap_log_rerror(APLOG_MARK, APLOG_EMERG, rv, r, APLOGNO(01199)
- "Cannot share worker");
-#if APR_HAS_THREADS
- if ((rv = PROXY_GLOBAL_UNLOCK(bsel)) != APR_SUCCESS) {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01200)
- "%s: Unlock failed for adding worker",
- bsel->s->name);
- }
-#endif
- return HTTP_BAD_REQUEST;
- }
- if ((rv = ap_proxy_initialize_worker(nworker, r->server, conf->pool)) != APR_SUCCESS) {
- ap_log_rerror(APLOG_MARK, APLOG_EMERG, rv, r, APLOGNO(01201)
- "Cannot init worker");
-#if APR_HAS_THREADS
- if ((rv = PROXY_GLOBAL_UNLOCK(bsel)) != APR_SUCCESS) {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01202)
- "%s: Unlock failed for adding worker",
- bsel->s->name);
- }
-#endif
+ const char *flags = apr_table_get(params, "b_nwrkr_flags");
+ int rc;
+
+ /* mod_proxy_beacon's mark is the only status flag that a worker
+ * can be created with (balancer_handler() drops b_nwrkr_flags
+ * from the balancer-manager's requests).
+ */
+ if (flags) {
+ const char *f;
+ for (f = flags; *f; ++f) {
+ if (*f != PROXY_WORKER_BEACON_FLAG) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(10704)
+ "%s: refusing to add worker %s with "
+ "status flags \"%s\" (only '%c' is "
+ "allowed)", bsel->s->name, val, flags,
+ PROXY_WORKER_BEACON_FLAG);
return HTTP_BAD_REQUEST;
}
- /* sync all timestamps */
- bsel->wupdated = bsel->s->wupdated = nworker->s->updated = apr_time_now();
- /* by default, all new workers are disabled */
- ap_proxy_set_wstatus(PROXY_WORKER_DISABLED_FLAG, 1, nworker);
- } else {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(10163)
- "%s: failed to add worker %s",
- bsel->s->name, val);
-#if APR_HAS_THREADS
- PROXY_GLOBAL_UNLOCK(bsel);
-#endif
- return HTTP_BAD_REQUEST;
- }
-#if APR_HAS_THREADS
- if ((rv = PROXY_GLOBAL_UNLOCK(bsel)) != APR_SUCCESS) {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01203)
- "%s: Unlock failed for adding worker",
- bsel->s->name);
}
-#endif
- } else {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(10164)
- "%s: failed to add worker %s",
- bsel->s->name, val);
- return HTTP_BAD_REQUEST;
}
+ rc = balancer_add_worker(r, bsel, conf, val, flags);
+ if (rc != APR_SUCCESS) {
+ return rc;
+ }
}
}
@@ -1417,7 +1530,7 @@ static apr_status_t balancer_manage(request_rec *r, apr_table_t *params)
if ((name = apr_table_get(params, "w"))) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "balancer_manage "
"worker: %s", name);
- wsel = ap_proxy_get_worker(r->pool, bsel, conf, name);
+ wsel = get_balancer_worker(r, bsel, conf, name);
}
if (bsel) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "balancer_manage "
@@ -1441,6 +1554,7 @@ static void balancer_display_page(request_rec *r, proxy_server_conf *conf,
proxy_balancer *balancer;
proxy_worker *worker;
proxy_worker **workers;
+ const apr_array_header_t *members;
int i, n;
action = ap_construct_url(r->pool, r->uri, r);
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01204) "genning page");
@@ -1481,8 +1595,9 @@ static void balancer_display_page(request_rec *r, proxy_server_conf *conf,
}
/* End proxy_balancer */
ap_rputs(" \n", r);
- workers = (proxy_worker **)balancer->workers->elts;
- for (n = 0; n < balancer->workers->nelts; n++) {
+ members = ap_proxy_balancer_snap_workers(balancer, r->pool);
+ workers = (proxy_worker **)members->elts;
+ for (n = 0; n < members->nelts; n++) {
worker = *workers;
/* Start proxy_worker */
ap_rputs(" \n", r);
@@ -1717,8 +1832,9 @@ static void balancer_display_page(request_rec *r, proxy_server_conf *conf,
}
ap_rputs("
\n", r);
- workers = (proxy_worker **)balancer->workers->elts;
- for (n = 0; n < balancer->workers->nelts; n++) {
+ members = ap_proxy_balancer_snap_workers(balancer, r->pool);
+ workers = (proxy_worker **)members->elts;
+ for (n = 0; n < members->nelts; n++) {
char fbuf[50];
worker = *workers;
ap_rvputs(r, "\n| pool);
+
+ /* The status flags of a new worker are for balancer_manage()'s
+ * callers only: the balancer-manager creates it disabled.
+ */
+ apr_table_unset(params, "b_nwrkr_flags");
}
/* Ignore parameters if this looks like XSRF */
@@ -1985,7 +2106,7 @@ static int balancer_handler(request_rec *r)
apr_pstrcat(r->pool, BALANCER_PREFIX, name, NULL), 0);
if ((name = apr_table_get(params, "w"))) {
- wsel = ap_proxy_get_worker(r->pool, bsel, conf, name);
+ wsel = get_balancer_worker(r, bsel, conf, name);
}
@@ -2014,6 +2135,18 @@ static int balancer_handler(request_rec *r)
static void balancer_child_init(apr_pool_t *p, server_rec *s)
{
+#if APR_HAS_THREADS
+ /* The copies of a balancer that the vhosts inherit (merge_balancers())
+ * share its workers array. An array that can grow at run time
+ * (balancer-manager, ap_proxy_sync_balancer()) is walked under the
+ * balancer's thread mutex: give all the copies of such an array the same
+ * mutex, keyed by the array. An ungrowable array never changes, its
+ * copies keep the mutex that ap_proxy_initialize_balancer() creates for
+ * each.
+ */
+ apr_hash_t *tmutexes = apr_hash_make(p);
+#endif
+
while (s) {
proxy_balancer *balancer;
int i;
@@ -2033,6 +2166,16 @@ static void balancer_child_init(apr_pool_t *p, server_rec *s)
balancer = (proxy_balancer *)conf->balancers->elts;
for (i = 0; i < conf->balancers->nelts; i++, balancer++) {
+#if APR_HAS_THREADS
+ apr_thread_mutex_t *tmutex = NULL;
+ if (!balancer->ungrowable) {
+ tmutex = apr_hash_get(tmutexes, &balancer->workers,
+ sizeof(balancer->workers));
+ }
+ if (tmutex) {
+ balancer->tmutex = tmutex;
+ }
+#endif
rv = ap_proxy_initialize_balancer(balancer, s, p);
if (rv != APR_SUCCESS) {
@@ -2041,6 +2184,12 @@ static void balancer_child_init(apr_pool_t *p, server_rec *s)
balancer->s->name);
exit(1); /* Ugly, but what else? */
}
+#if APR_HAS_THREADS
+ if (!tmutex && !balancer->ungrowable) {
+ apr_hash_set(tmutexes, &balancer->workers, sizeof(balancer->workers),
+ balancer->tmutex);
+ }
+#endif
init_balancer_members(p, s, balancer);
}
s = s->next;
diff --git a/modules/proxy/mod_proxy_beacon-guide.md b/modules/proxy/mod_proxy_beacon-guide.md
new file mode 100644
index 00000000000..a7b4670f6f2
--- /dev/null
+++ b/modules/proxy/mod_proxy_beacon-guide.md
@@ -0,0 +1,369 @@
+# A Practical Guide to `mod_proxy_beacon`
+
+*Self-registering, self-healing reverse-proxy balancer membership over UDP.*
+
+---
+
+## 1. What it does
+
+Normally, adding a backend to an httpd reverse-proxy load balancer means editing
+the proxy config (or clicking around in `balancer-manager`) every time the fleet
+changes. `mod_proxy_beacon` flips that around: **each backend announces itself**
+to the proxy, and the proxy automatically:
+
+- **adds and enables** the backend as a live `BalancerMember` when it first
+ announces, and
+- **disables it** (takes it out of rotation) when it stops announcing — then
+ **re-enables it** when it comes back.
+
+The result is a balancer whose membership tracks the running fleet with no
+operator action. A backend added this way is a normal balancer member: it shows
+up in `balancer-manager` and behaves exactly like a statically configured
+`BalancerMember`.
+
+```
+ backend-1 ──┐ (periodic UDP "BEACON" datagrams,
+ backend-2 ──┤ each advertising its own URL)
+ backend-3 ──┘ │
+ ▼
+ ┌──────────────┐
+ │ reverse proxy│ ProxyBeaconListen :5555
+ │ balancer:// │ → add / enable / evict members
+ │ cluster │
+ └──────────────┘
+ │
+ clients
+```
+
+---
+
+## 2. How it works (the short version)
+
+- **Transport:** plain **unicast UDP** datagrams (not multicast — multicast is
+ filtered on most networks and never crosses the public Internet). Backends
+ `sendto` the proxy; the proxy binds one socket and receives. No external
+ library — APR sockets for transport, APR-util SipHash for auth.
+- **Fire-and-forget:** a lost datagram is simply recovered by the next periodic
+ announcement; reordered/replayed datagrams are rejected by a per-backend
+ timestamp check. No connection, reconnect, or framing layer.
+- **Where it runs:** all the work happens in a single `mod_watchdog` **singleton**
+ child process, which owns the socket and applies membership changes. The change
+ propagates fleet-wide through the balancer's shared-memory “updated” timestamp,
+ the same way `balancer-manager` edits do.
+
+---
+
+## 3. Requirements
+
+| Need | Why |
+|------|-----|
+| `mod_proxy` + `mod_proxy_balancer` | the balancer the members are added to |
+| `mod_watchdog` | runs the background send/receive/evict loop |
+| A **non-prefork** MPM (`event`, `worker`, …) | the watchdog singleton can't run under `prefork`; the module is silently inactive there |
+| `mod_proxy_http` (or your backend protocol module) | to actually proxy the traffic |
+
+Build it with `--enable-proxy-beacon`; no `--enable-mods-*` selection includes it. Confirm
+it's present:
+
+```sh
+httpd -M 2>&1 | grep proxy_beacon # shared build
+# or
+httpd -l | grep mod_proxy_beacon # static build
+```
+
+---
+
+## 4. Quick start
+
+### On the reverse proxy
+
+```apache
+# Receive backend announcements on the cluster-facing interface (UDP/5555).
+ProxyBeaconListen 0.0.0.0:5555
+ProxyBeaconSecret "hex:00112233445566778899aabbccddeeff"
+ProxyBeaconBalancer cluster
+
+# Drop a backend from rotation if it goes silent for 30s; re-add on next beacon.
+ProxyBeaconTimeout 30
+
+# An initially EMPTY balancer with spare slots for the dynamic members.
+
+ ProxySet growth=16
+
+
+ProxyPass "/" "balancer://cluster/"
+ProxyPassReverse "/" "balancer://cluster/"
+```
+
+### On each backend
+
+```apache
+# Announce this backend's routable origin to the proxy every 10s (UDP).
+ProxyBeaconAddress proxy.example.com:5555
+ProxyBeaconAdvertise http://10.0.0.5:8080
+ProxyBeaconSecret "hex:00112233445566778899aabbccddeeff"
+ProxyBeaconInterval 10
+```
+
+That's it. Start the backends; within one announcement interval each one appears
+as an enabled member of `balancer://cluster` on the proxy. Stop one, and after
+`ProxyBeaconTimeout` it drops out of rotation; start it again and it returns.
+
+> **`ProxyBeaconAdvertise` must be the URL the *proxy* can reach** — the
+> backend's routable origin, not `127.0.0.1`. It's validated at config-parse
+> time and must be a full `scheme://host[:port]` **with no path** (see
+> [Member identity](#member-identity)).
+
+---
+
+## 5. Directive reference
+
+### Proxy side (the receiver)
+
+| Directive | Default | Meaning |
+|-----------|---------|---------|
+| `ProxyBeaconListen [addr][:port]` | — | **Marks this server as the receiver.** Binds a UDP socket. `addr`/`port` are optional and inherited from the server's own `Listen`/`ServerName` when omitted (see note below). |
+| `ProxyBeaconBalancer name` | — | Balancer that announced backends are added to. Bare name (`cluster`); a leading `balancer://` is stripped. Must already exist with spare `growth`. |
+| `ProxyBeaconTimeout interval` | `0` (no eviction) | Seconds of silence before a member is disabled. `0` = add-only, never auto-remove. Set to a small multiple of the backends' interval to get self-healing. |
+| `ProxyBeaconSecret secret` | — (**required**) | Shared cluster secret; **same value on proxy and all backends**, either `hex:` + 32 hex digits (a random key: `openssl rand -hex 16`) or a passphrase of at least 16 characters (weaker: guessable offline from one captured packet). The server fails to start if a participating server omits it or it is invalid. |
+| `ProxyBeaconMaxSkew interval` | `30` | Anti-replay freshness window: reject announcements whose signed timestamp is more than this far from now (either direction). Sub-second values (`500ms`) are honoured. |
+
+**Inheriting the listen address:** because UDP and TCP are separate port spaces,
+`ProxyBeaconListen` can share the server's own service port without colliding
+with the TCP listener. With no argument it binds the server's own address:port;
+given just an address it inherits the port; etc. (The socket binds in an
+unprivileged watchdog child, so you **can't** share a privileged port like 80/443
+this way — use an explicit high port there.)
+
+### Backend side (the sender)
+
+| Directive | Default | Meaning |
+|-----------|---------|---------|
+| `ProxyBeaconAddress addr:port` | — | **Marks this server as a sender.** UDP target = the proxy's `ProxyBeaconListen` address. |
+| `ProxyBeaconAdvertise url` | — | The routable `scheme://host[:port]` origin the proxy adds as a member — no path, query, fragment or userinfo (rejected at config time). Omit it and the backend beacons but advertises nothing (logged, never added). |
+| `ProxyBeaconInterval interval` | `5` | How often this backend announces. Must be **meaningfully smaller** than the proxy's `ProxyBeaconTimeout`. |
+| `ProxyBeaconSecret secret` | — (**required**) | Same shared secret as the proxy. |
+
+> `ProxyBeaconListen` and `ProxyBeaconAddress` are **mutually exclusive** on the
+> same server — a server is either a receiver or a sender, not both.
+
+All directives accept `server config` and `virtual host` context. Interval-style
+directives use the standard httpd
+[time-interval syntax](../../docs/manual/mod/directive-dict.html#Syntax) and
+default to seconds (e.g. `ProxyBeaconInterval 10` or `... 500ms`).
+
+### Member identity
+
+An announced URL names a backend **origin** — `scheme://host[:port]`, nothing
+more. The proxy canonicalizes it and uses that one string as the member's
+identity everywhere: the key for its lease and replay state, the worker name it
+creates, and the name used for every later enable or evict.
+
+- **Canonical form:** scheme and host lower-cased, the scheme's default port
+ dropped, a single trailing `/` ignored. `HTTP://App.Example.com:80`,
+ `http://app.example.com/` and `http://app.example.com` are **one** member.
+- **Rejected:** a path (other than `/`), query, fragment, userinfo, an invalid
+ port, or the `unix:/path|http://…` socket form. These are dropped and logged as
+ `unacceptable url`; the backend is not added. `ProxyBeaconAdvertise` enforces
+ the same rule when the config is parsed, so a backend can't be misconfigured
+ into announcing one.
+
+**Why no paths?** The balancer finds a member by *longest-prefix* match.
+`http://10.0.0.5:8080/one` and `http://10.0.0.5:8080/one/two` would be tracked as
+two members with separate leases but resolve to one worker — so when one lease
+lapsed, the proxy would disable a worker whose other lease was still current. If
+you need different paths to go to different places, do that on the proxy with
+`ProxyPass`; advertise only where the backend lives.
+
+### Ownership and hand-off
+
+Beacon marks every worker it creates with the **`Bcn`** status (flag `B`, visible
+in the balancer-manager). It only ever enables or evicts workers carrying that
+mark: a `BalancerMember` from your configuration, or one an administrator added,
+is never touched, even if a backend announces exactly its URL.
+
+The announcements and leases are handled by **one** watchdog child. If that child
+dies, the watchdog moves to another child, which starts with no memory of the
+members. On taking over it **adopts every `Bcn` member** in the balancer and
+starts their leases afresh:
+
+- a member that has since gone silent is evicted `ProxyBeaconTimeout` after the
+ hand-off, instead of staying enabled forever;
+- a member that was already disabled is treated as evicted and is re-enabled by
+ its next announcement.
+
+Two things to know: a dead backend can stay in rotation for up to one
+`ProxyBeaconTimeout` after a hand-off, and the per-member replay high-water mark
+is not carried over — during a hand-off a captured announcement still inside
+`ProxyBeaconMaxSkew` can be replayed once per member, refreshing that lease for one
+timeout (it cannot add a member without the secret).
+
+**Holding a member out of rotation.** Beacon owns a member's **Disabled** flag
+(lease expiry sets it, the next announcement clears it), so a manual "Disable" in
+the balancer-manager is overridden. To keep a member out regardless of what it
+announces, set it **Stopped** or **Drain** — beacon never touches those, nor the
+health-check failure flag.
+
+**Capacity.** At most 256 announced URLs are tracked. Records of evicted members
+and of failed adds are released after being silent for more than twice
+`ProxyBeaconMaxSkew` (a replay of their last message would be stale by then), so
+they don't lock out new backends; a member that comes back is re-adopted. A
+balancer itself accepts at most 100 runtime members (`growth`). A holder of the
+secret can still fill the table with distinct URLs until they fall silent.
+
+**Socket problems.** If the UDP socket can't be opened (unresolvable address, port
+in use) it is retried with back-off, 30 s doubling to 10 min. Name lookups are
+synchronous on the single watchdog thread shared by every beacon configuration of
+the server, so an unresolvable name can stall them all for as long as the resolver
+takes to give up — **use IP addresses** in `ProxyBeaconAddress` / `ProxyBeaconListen`.
+
+> A new owner can only start once the old one's `watchdog-callback` mutex is
+> released. If the default mechanism isn't released when its holder is killed on
+> your platform, pick one that is: `Mutex sysvsem watchdog-callback`.
+
+---
+
+## 6. Security — read this before production
+
+The control channel decides where the proxy sends client traffic, so an
+unauthenticated channel is a route-hijack / SSRF risk: anyone who can reach the
+receive port could announce an arbitrary backend URL, and **UDP source addresses
+are trivially spoofable.**
+
+`ProxyBeaconSecret` is therefore **required** (identical on proxy and every
+backend) — `httpd -t` and startup both fail if a participating server omits it, so
+there is no unauthenticated mode to fall into. With it:
+
+- Each announcement is signed with a **SipHash-2-4 MAC** plus a timestamp; the
+ proxy recomputes the MAC (constant-time compare) and drops anything forged or
+ tampered **before parsing the URL**.
+- **Replay protection is two-layered:** (1) the `ProxyBeaconMaxSkew` freshness
+ window rejects stale timestamps, and (2) a per-backend high-water mark rejects
+ any timestamp that doesn't strictly advance — so capturing and re-sending a
+ dead backend's last datagram (to keep it from being evicted) is rejected even
+ inside the freshness window.
+
+**What the secret is.** A valid MAC proves only that the sender holds the
+secret — not that it owns the URL it announces, may speak for another backend, or
+is ready to serve. Every holder can register any origin the proxy can reach,
+keep other members' leases alive, and use up growth slots and tracking records.
+Treat the secret as an **administrator credential for the balancer** and share it
+only among hosts you'd trust with that; it is not a boundary between partially
+trusted workloads. Because the key is derived from the passphrase with a fast
+hash (and the tag is 64 bits), a captured announcement allows offline guessing:
+**use a long random secret** (at least 16 characters is enforced).
+
+**What is checked.** Every datagram is dropped unless it is ≤ 2048 bytes with no
+NUL, carries a valid MAC (even when no `ProxyBeaconBalancer` is set, so log-only
+mode logs only authenticated announcements), has the exact `BEACON key=value … mac=…`
+shape with no repeated field and a plain decimal `ts=`, and names a printable-ASCII
+origin.
+
+Operational notes:
+
+- **Clocks must be roughly in sync** (NTP). The timestamp check compares the
+ announcement's time against the proxy's clock; widen `ProxyBeaconMaxSkew` if
+ your hosts drift.
+- The secret lives in your config file — **restrict its permissions like a
+ private key.**
+- Announcements are **authenticated, not encrypted.** The payload is operational
+ metadata (URLs), not secrets. There's no transport confidentiality (DTLS would
+ be a separate future layer).
+
+---
+
+## 7. Tuning
+
+- **Interval vs. timeout.** Keep `ProxyBeaconInterval` well under
+ `ProxyBeaconTimeout` so an occasional dropped datagram doesn't evict a healthy
+ backend. A common ratio is timeout ≈ 3–6× interval (e.g. interval 10s, timeout
+ 30–60s).
+- **Size `growth` for your peak fleet.** A runtime-added member occupies one
+ growth slot **for the life of the proxy process** — it's *disabled* on
+ eviction, not removed (httpd can't remove workers at runtime, mirroring
+ `balancer-manager`). So `growth` must cover the maximum number of distinct
+ backend URLs you ever expect, not just the count live at one moment.
+- **One proxy, many backends.** A single receiver serves the whole fleet. For
+ multiple proxies, run `ProxyBeaconListen` on each and point backends at all of
+ them (one `ProxyBeaconAddress` server per proxy, or accept that only the
+ configured proxy learns about the backend).
+
+---
+
+## 8. Verifying & troubleshooting
+
+**See members appear:** enable `balancer-manager` on the proxy and watch the
+worker list:
+
+```apache
+
+ SetHandler balancer-manager
+ Require host localhost
+
+```
+
+**Watch the log.** Bump verbosity for the module and tail the error log:
+
+```apache
+LogLevel proxy_beacon:info
+```
+
+Useful log signals (grep the error log):
+
+| Log fragment | Means |
+|--------------|-------|
+| `received: BEACON ... url=...` | proxy is receiving announcements |
+| `added backend ... balancer://cluster` | member created + enabled |
+| `evicted backend ...` | a backend went silent past the timeout |
+| `re-enabled backend ...` | a previously-evicted backend came back |
+| `dropped ... mac mismatch` | wrong/missing secret on a sender (or a forged datagram) |
+| `replayed/reordered ts` | a stale/duplicate datagram was rejected |
+| `dropped ... oversize datagram` / `embedded NUL` / `bad frame` / `duplicate field` / `bad ts` | a datagram that isn't a well-formed announcement (see "What is checked") |
+| `dropped ... member table full` | 256 urls are already tracked; records free up as silent ones age out (see Capacity) |
+| `dropped ... unacceptable url` | an announcement's `url=` is not a plain origin (it has a path, query, userinfo, a bad port, or is a `unix:` URL) |
+| `took over N existing member(s)` | a new watchdog owner adopted the beacon-created members already in the balancer (see [Ownership and hand-off](#ownership-and-hand-off)) |
+| `dropped ... member not managed by beacon` | a backend announced the URL of a worker beacon did not create (configured or admin-added); it is left alone |
+| `dropped ... balancer add not confirmed` | the balancer reported success but no such member exists; retried after the back-off |
+| `ProxyBeaconSecret is required` (startup) | a participating server has no `ProxyBeaconSecret` — startup aborts |
+
+**Common gotchas:**
+
+- *Backend never joins.* Usually a **secret mismatch** (look for `mac mismatch`)
+ or a firewall blocking **UDP** on the beacon port (it's UDP, not TCP — separate
+ rule). Confirm the proxy is logging `received: BEACON` at all.
+- *Nothing happens, no errors.* You're probably on the **prefork MPM** — the
+ watchdog singleton doesn't run there, so the module is inactive. Switch to
+ `event`/`worker`.
+- *Traffic 503s to a backend that's “up”.* Check that `ProxyBeaconAdvertise` is
+ the URL the **proxy** can reach (not the backend's loopback) and that the
+ balancer has free `growth` slots.
+- *Healthy backend keeps getting evicted.* Interval too close to timeout, or
+ clock skew larger than `ProxyBeaconMaxSkew`. Widen the timeout/skew or sync
+ clocks.
+
+---
+
+## 9. The wire format (for the curious)
+
+One ASCII, space-separated, key=value datagram per announcement:
+
+```
+BEACON url=http://host:port host= pid= seq= ts= mac=
+```
+
+- `url=` — the routable origin added as a `BalancerMember`; `scheme://host[:port]`
+ only (see [Member identity](#member-identity)).
+- `ts=` (microseconds since epoch) and `mac=` — present only when a secret is set;
+ `ts` drives replay protection, `mac` is the SipHash signature.
+- `host=` / `pid=` / `seq=` — informational. (`seq` resets on backend restart, so
+ it's *not* used for replay detection — the wall-clock `ts` is.)
+
+---
+
+## 10. See also
+
+- `mod_proxy`, `mod_proxy_balancer` — the balancer these members live in
+- `mod_proxy_hcheck` — active health checking, complementary to beacon liveness
+- `mod_watchdog` — the background runner this module rides on
+- `modules/proxy/README.beacon` — the architecture/internals companion to this guide
+- `docs/manual/mod/mod_proxy_beacon.xml` — the formal directive reference
diff --git a/modules/proxy/mod_proxy_beacon.c b/modules/proxy/mod_proxy_beacon.c
new file mode 100644
index 00000000000..c67292ad95d
--- /dev/null
+++ b/modules/proxy/mod_proxy_beacon.c
@@ -0,0 +1,2092 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/*
+ * mod_proxy_beacon -- a UDP datagram announcement channel between backend
+ * servers and a front-end reverse proxy, by which backends self-register as
+ * balancer members.
+ *
+ * This module uses plain APR UDP sockets, adapting the socket-handling pattern
+ * of mod_heartmonitor. UDP datagrams are a natural fit for small, periodic,
+ * fire-and-forget announcements, and avoid a third-party dependency.
+ *
+ * UNICAST, not multicast: unlike mod_heartbeat (which multicasts to a group),
+ * each backend sends a point-to-point datagram to the proxy's configured address
+ * (apr_socket_sendto to a single resolved unicast sockaddr). Multicast is
+ * filtered on most networks and does not traverse the public Internet, so a
+ * cross-host control plane must be unicast. The proxy is a fixed unicast
+ * rendezvous; each backend is configured with its address.
+ *
+ * Direction: backends announce themselves to the proxy. The proxy binds a
+ * stable UDP port (the rendezvous) and receives; each backend sends to it:
+ *
+ * - Reverse proxy: ProxyBeaconListen 0.0.0.0:5555 (receiver, binds)
+ * - Backend server: ProxyBeaconAddress proxy-host:5555 (sender, sendto)
+ *
+ * A leading scheme (e.g. tcp://) in the address is accepted and ignored, so
+ * addresses written with a transport scheme keep working. Each backend sends
+ * a "BEACON" datagram every interval. Datagrams are fire-and-forget: a lost
+ * packet just delays an update by one interval, and reordering is rejected by
+ * the per-url monotonic timestamp (Phase 4), so the design tolerates UDP's lack
+ * of delivery/ordering guarantees without a reconnect or framing layer.
+ *
+ * Phase 1 (the channel): the proxy simply logged each announcement, proving the
+ * channel works between separate, remote servers.
+ *
+ * Phase 2: when the proxy receives an announcement that carries a backend
+ * URL, it ADDS that backend as a member (worker) of a configured balancer and
+ * ENABLES it -- the dynamic equivalent of "Add Worker" in the balancer-manager
+ * web UI, but driven by the backend announcing itself. We reuse
+ * mod_proxy_balancer's exported balancer_manage() optional function (the same
+ * core balancer_handler calls), so the add path is identical to the proven
+ * manager flow. The backend advertises its routable URL via ProxyBeaconAdvertise;
+ * the proxy names the target balancer via ProxyBeaconBalancer.
+ *
+ * Phase 3: the inverse -- when a backend STOPS announcing for longer than
+ * ProxyBeaconTimeout, the proxy takes it out of rotation by setting the worker's
+ * DISABLED flag (again via balancer_manage), and re-enables it if the backend
+ * starts announcing again. This gives the cluster automatic liveness without
+ * operator action. The timeout is a config directive (0 = disabled = pure
+ * Phase-2 behavior). All of this runs in the watchdog singleton that already
+ * owns the socket, so the per-URL last-seen table lives in this process's
+ * ctx -- no shared memory.
+ *
+ * Phase 4: authenticate the channel. Without this, anyone who can reach the
+ * proxy's bound port can announce an arbitrary url and the proxy will route real
+ * client traffic to it (SSRF / hijack) -- and a UDP source address is trivially
+ * spoofable, so authentication matters as much here as on any control plane. With
+ * a pre-shared cluster secret (ProxyBeaconSecret) on both ends, the sender appends
+ * a keyed MAC (SipHash-2-4 via APR-util -- the same primitive mod_session_crypto
+ * uses) plus a timestamp; the receiver recomputes the MAC and checks timestamp
+ * freshness (anti-replay), dropping any forged, tampered, or stale message
+ * before it is parsed/acted on. Authentication is REQUIRED: ProxyBeaconSecret
+ * must be set on every server that participates in the channel (sender or
+ * listener), or startup fails -- there is no unauthenticated mode. We
+ * authenticate, not encrypt -- the payload (backend URLs) is not secret; for
+ * transport confidentiality DTLS would be a separate, orthogonal future layer.
+ *
+ * The background work runs on a mod_watchdog SINGLETON instance (exactly one
+ * child process owns the socket), mirroring mod_proxy_hcheck.c. That child has
+ * no request_rec, so the receiver synthesizes a minimal one for balancer_manage()
+ * (see beacon_make_fake_request -- adapted from mod_proxy_hcheck's
+ * create_request_rec, plus a fake conn_rec that ap_log_rerror requires).
+ */
+
+#include "httpd.h"
+#include "http_config.h"
+#include "http_core.h"
+#include "http_log.h"
+#include "http_protocol.h"
+#include "ap_provider.h"
+#include "ap_listen.h"
+#include "mod_watchdog.h"
+#include "mod_proxy.h"
+
+#include "apr_strings.h"
+#include "apr_time.h"
+#include "apr_hash.h"
+#include "apr_uri.h"
+#include "apr_network_io.h"
+#include "apr_siphash.h"
+#include "apr_md5.h"
+
+#if APR_HAVE_PROCESS_H
+#include /* for getpid() on Windows */
+#endif
+#if APR_HAVE_UNISTD_H
+#include /* for getpid() */
+#endif
+
+module AP_MODULE_DECLARE_DATA proxy_beacon_module;
+
+#define BEACON_WATCHDOG_NAME "_proxy_beacon_"
+#define BEACON_DEFAULT_INTERVAL apr_time_from_sec(5)
+
+typedef enum {
+ BEACON_ROLE_NONE = 0,
+ BEACON_ROLE_SEND, /* backend: dials the proxy and announces itself */
+ BEACON_ROLE_LISTEN /* reverse proxy: listens and receives announcements */
+} beacon_role_e;
+
+/* Longest announced url we handle (including the NUL). */
+#define BEACON_URL_MAX 512
+
+/* listener-side per-backend state, keyed by url in ctx->seen. */
+typedef struct beacon_member_t {
+ apr_time_t last_seen; /* updated on every beacon for this url */
+ apr_time_t last_attempt; /* last add attempt (throttles retry when full) */
+ apr_int64_t last_ts; /* highest signed ts= accepted (replay guard) */
+ int added; /* worker exists in the balancer (add dedup) */
+ int evicted; /* WE set DISABLED on timeout (guards flip churn) */
+ char url[BEACON_URL_MAX]; /* the key in ctx->seen (the hash keeps no copy) */
+ struct beacon_member_t *next_free; /* free list link while unused */
+} beacon_member_t;
+
+typedef struct {
+ apr_pool_t *p; /* subpool for this context */
+ server_rec *s; /* canonical server identity */
+ char *pub_url; /* ProxyBeaconAddress (backend dial url) */
+ char *sub_url; /* ProxyBeaconListen (proxy listen url) */
+ char *advertise_url;/* ProxyBeaconAdvertise (sender: routable url) */
+ char *balancer_name;/* ProxyBeaconBalancer (listener: bare bal name) */
+ apr_interval_time_t interval; /* ProxyBeaconInterval (announce period) */
+ apr_interval_time_t evict_timeout;/* ProxyBeaconTimeout (0 = no eviction) */
+ beacon_role_e role;
+ apr_socket_t *sock; /* live UDP socket; valid only when opened */
+ apr_sockaddr_t *addr; /* listener: bind addr; sender: destination addr */
+ int opened; /* guard double-open / stop-without-start */
+ apr_time_t last_publish; /* sender throttle */
+ apr_time_t last_sweep; /* listener eviction-scan throttle */
+ apr_uint64_t seq; /* announcement counter */
+ apr_hash_t *seen; /* listener: url -> beacon_member_t* */
+ beacon_member_t *free_members; /* listener: reclaimed records, for reuse */
+ APR_OPTIONAL_FN_TYPE(balancer_manage) *manage_fn; /* listener: cached, lazy */
+ /* Phase 4: channel authentication. */
+ int has_secret; /* ProxyBeaconSecret was set */
+ unsigned char mac_key[APR_MD5_DIGESTSIZE]; /* siphash key (16 bytes) */
+ apr_interval_time_t max_skew; /* ProxyBeaconMaxSkew (replay window); 0 = default */
+ apr_uint64_t reject_count; /* listener: dropped-since-last-log counter */
+ apr_time_t last_reject_log; /* listener: reject-log rate limiter */
+ int open_failed; /* socket open failed; retried with back-off */
+ int reconciled; /* listener: adopted pre-existing members as owner */
+ apr_pool_t *open_pool; /* socket + address of the current open attempt */
+ apr_time_t next_open_try; /* when to retry a failed open (0 = not scheduled) */
+ apr_interval_time_t open_delay; /* current retry back-off (0 = no failure yet) */
+ int io_errors; /* failed sends/receives in a row */
+ apr_time_t last_io_error_log;
+ apr_time_t next_refresh; /* sender: when to resolve the destination again */
+ apr_pool_t *addr_pool; /* sender: a refreshed destination, if any */
+ apr_time_t recv_log_window; /* start of the second counted below */
+ unsigned int recv_log_count; /* "received:" lines logged in it */
+ apr_uint64_t recv_log_suppressed; /* ...and those it left out */
+} beacon_ctx_t;
+
+/* SipHash-2-4 output is 8 bytes -> 16 hex chars (+ NUL). */
+#define BEACON_MAC_HEXLEN (APR_SIPHASH_DSIZE * 2)
+/* Shortest ProxyBeaconSecret accepted. */
+#define BEACON_MIN_SECRET_LEN 16
+/* A secret of this form is used directly as the MAC key (no passphrase). */
+#define BEACON_HEXKEY_PREFIX "hex:"
+#define BEACON_MAXSKEW_DEFAULT apr_time_from_sec(30)
+
+/* Max announcement datagram we accept. Our messages are a few hundred bytes;
+ * anything larger is not one of ours and is dropped. */
+#define BEACON_MAX_MSG_LEN 2048
+
+/* When an add fails (e.g. the balancer is full), don't retry on every
+ * announcement -- back off this long between attempts for a given url. */
+#define BEACON_RETRY_BACKOFF apr_time_from_sec(60)
+
+/* Cap on tracked backend urls, to bound memory against a buggy or compromised
+ * (authenticated) backend announcing unboundedly many distinct urls. Once
+ * reached, unknown urls are dropped (rate-limited log) rather than tracked/added. */
+#define BEACON_MAX_MEMBERS 256
+
+/* A failed socket open (unresolvable address, port in use, ...) is retried: the
+ * cause may be transient (a name server that is not up yet). The delay starts
+ * at BEACON_OPEN_RETRY and doubles up to BEACON_OPEN_RETRY_MAX. Retrying every
+ * watchdog tick would flood the error log, and an address lookup blocks the
+ * (single, shared) watchdog thread for as long as the resolver takes to give
+ * up, so a failing name must not be retried often. */
+#define BEACON_OPEN_RETRY apr_time_from_sec(30)
+#define BEACON_OPEN_RETRY_MAX apr_time_from_sec(600)
+
+/* Cap on datagrams handled per watchdog tick, so a flood can't hold the
+ * watchdog thread in the receive loop; the rest wait for the next tick. */
+#define BEACON_MAX_DRAIN 1024
+/* ...and no more than this much time per tick, so that a flood of datagrams
+ * cannot keep the watchdog thread from the eviction sweep and the other
+ * contexts that share it. */
+#define BEACON_DRAIN_BUDGET apr_time_from_msec(50)
+/* After this many failed sends or receives in a row the socket is closed and
+ * reopened (re-resolving the address) under the open back-off. */
+#define BEACON_IO_ERRORS_MAX 5
+/* A sender looks its destination up again this often, so that a proxy which
+ * moved to another address is found. */
+#define BEACON_REFRESH apr_time_from_sec(300)
+/* The "received:" lines, at most this many per second and context. */
+#define BEACON_RECV_LOG_PER_SEC 20
+
+/* Process-wide watchdog handle, like mod_proxy_hcheck's static watchdog. */
+static ap_watchdog_t *beacon_watchdog;
+
+/*
+ * Per-server config. No socket calls here -- the role may not even be known yet,
+ * and this runs in the parent at config-parse time (possibly more than once).
+ */
+static void *beacon_create_server_config(apr_pool_t *p, server_rec *s)
+{
+ beacon_ctx_t *ctx = apr_pcalloc(p, sizeof(beacon_ctx_t));
+
+ ctx->s = s;
+ apr_pool_create(&ctx->p, p);
+ apr_pool_tag(ctx->p, "proxy_beacon");
+ ctx->interval = BEACON_DEFAULT_INTERVAL;
+ ctx->role = BEACON_ROLE_NONE;
+ ctx->seen = apr_hash_make(ctx->p);
+
+ return ctx;
+}
+
+static const char *beacon_set_sub_url(cmd_parms *cmd, void *dummy,
+ int argc, char *const argv[])
+{
+ beacon_ctx_t *ctx = ap_get_module_config(cmd->server->module_config,
+ &proxy_beacon_module);
+ const char *err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS);
+ if (err) {
+ return err;
+ }
+ if (argc > 1) {
+ return "ProxyBeaconListen takes at most one argument: [host][:port]";
+ }
+ if (ctx->pub_url) {
+ return "ProxyBeaconListen and ProxyBeaconAddress are mutually exclusive "
+ "on the same server";
+ }
+ /* No argument -> inherit both host and port from this server; one argument
+ * -> "[host][:port]", an omitted host or port being inherited from the
+ * server too. Store "" for the no-argument case (resolved against the
+ * server's own address at startup). */
+ ctx->sub_url = (argc == 1) ? apr_pstrdup(cmd->pool, argv[0]) : "";
+ ctx->role = BEACON_ROLE_LISTEN;
+ return NULL;
+}
+
+static const char *beacon_set_pub_url(cmd_parms *cmd, void *dummy, const char *arg)
+{
+ beacon_ctx_t *ctx = ap_get_module_config(cmd->server->module_config,
+ &proxy_beacon_module);
+ const char *err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS);
+ if (err) {
+ return err;
+ }
+ if (ctx->sub_url) {
+ return "ProxyBeaconListen and ProxyBeaconAddress are mutually exclusive "
+ "on the same server";
+ }
+ ctx->pub_url = apr_pstrdup(cmd->pool, arg);
+ ctx->role = BEACON_ROLE_SEND;
+ return NULL;
+}
+
+/*
+ * Canonical member identity. An announced url names a backend *origin*:
+ * scheme://host[:port], nothing more. Returns that origin in the exact form the
+ * proxy's worker-definition code stores it as the worker name -- lower-case
+ * scheme and host, the scheme's default port dropped, no trailing slash -- or
+ * NULL if url is not an origin (no scheme or host, a non-empty path, a query,
+ * a fragment, userinfo, or a port that is not a valid number).
+ *
+ * The announced string is used both as the key beacon tracks a member under and
+ * as the name handed to balancer_manage(), whose worker lookup is a
+ * longest-prefix match. Using one canonical origin for all of them keeps those
+ * identities equal; accepting paths would let /one and /one/two name the same
+ * worker while holding separate leases.
+ */
+static const char *beacon_canonical_url(apr_pool_t *pool, const char *url)
+{
+ apr_uri_t uri;
+ const char *host, *port = "", *c, *canon;
+
+ /* Printable ASCII only: the url is logged and becomes a worker name. */
+ for (c = url; *c; c++) {
+ if (!apr_isgraph(*c) || !apr_isascii(*c)) {
+ return NULL;
+ }
+ }
+ if (apr_uri_parse(pool, url, &uri) != APR_SUCCESS
+ || !uri.scheme || !*uri.scheme
+ || !uri.hostname || !*uri.hostname) {
+ return NULL;
+ }
+ if (uri.user || uri.password || uri.query || uri.fragment
+ || (uri.path && *uri.path && strcmp(uri.path, "/"))) {
+ return NULL;
+ }
+ /* apr_uri_parse() runs strtol() and truncates to 16 bits, so "-80" would
+ * otherwise come out as port 65456 and "99999" as 34463. */
+ if (uri.port_str && *uri.port_str) {
+ const char *d;
+ unsigned long port_val = 0;
+ for (d = uri.port_str; *d; d++) {
+ if (!apr_isdigit(*d)) {
+ return NULL;
+ }
+ port_val = port_val * 10 + (*d - '0');
+ if (port_val > 65535) {
+ return NULL;
+ }
+ }
+ if (!port_val) {
+ return NULL;
+ }
+ }
+
+ /* The proxy truncates a scheme or worker name that does not fit its shared
+ * storage, which would give the member another identity than the one
+ * announced. */
+ if (strlen(uri.scheme) >= PROXY_WORKER_MAX_SCHEME_SIZE
+ || strlen(uri.hostname) >= PROXY_RFC1035_HOSTNAME_SIZE) {
+ return NULL;
+ }
+
+ ap_str_tolower(uri.scheme);
+ ap_str_tolower(uri.hostname);
+ host = ap_strchr_c(uri.hostname, ':')
+ ? apr_pstrcat(pool, "[", uri.hostname, "]", NULL)
+ : uri.hostname;
+ if (uri.port && uri.port != ap_proxy_port_of_scheme(uri.scheme)) {
+ port = apr_psprintf(pool, ":%u", (unsigned)uri.port);
+ }
+ canon = apr_pstrcat(pool, uri.scheme, "://", host, port, NULL);
+ return strlen(canon) < PROXY_WORKER_MAX_NAME_SIZE ? canon : NULL;
+}
+
+static const char *beacon_set_advertise(cmd_parms *cmd, void *dummy,
+ const char *arg)
+{
+ beacon_ctx_t *ctx = ap_get_module_config(cmd->server->module_config,
+ &proxy_beacon_module);
+ const char *canon;
+ const char *err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS);
+ if (err) {
+ return err;
+ }
+ /* Must be a routable backend origin (scheme://host[:port], no path); it
+ * becomes a BalancerMember on the proxy. Announce its canonical form, so
+ * sender and receiver agree on the member's identity. */
+ canon = beacon_canonical_url(cmd->pool, arg);
+ if (!canon) {
+ return apr_psprintf(cmd->pool,
+ "ProxyBeaconAdvertise: '%s' is not a valid "
+ "scheme://host[:port] URL (no path, query, "
+ "fragment or userinfo; short enough to be a "
+ "worker name)", arg);
+ }
+ ctx->advertise_url = (char *)canon;
+ return NULL;
+}
+
+static const char *beacon_set_balancer(cmd_parms *cmd, void *dummy,
+ const char *arg)
+{
+ beacon_ctx_t *ctx = ap_get_module_config(cmd->server->module_config,
+ &proxy_beacon_module);
+ const char *err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS);
+ if (err) {
+ return err;
+ }
+ /* Store the bare name; balancer_manage() prepends BALANCER_PREFIX itself.
+ * Be forgiving if the admin wrote the full "balancer://name". */
+ if (!strncasecmp(arg, BALANCER_PREFIX, sizeof(BALANCER_PREFIX) - 1)) {
+ arg += sizeof(BALANCER_PREFIX) - 1;
+ }
+ if (!*arg) {
+ return "ProxyBeaconBalancer: empty balancer name";
+ }
+ ctx->balancer_name = apr_pstrdup(cmd->pool, arg);
+ return NULL;
+}
+
+static const char *beacon_set_interval(cmd_parms *cmd, void *dummy,
+ const char *arg)
+{
+ beacon_ctx_t *ctx = ap_get_module_config(cmd->server->module_config,
+ &proxy_beacon_module);
+ apr_interval_time_t iv;
+ apr_status_t rv;
+ const char *err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS);
+ if (err) {
+ return err;
+ }
+ rv = ap_timeout_parameter_parse(arg, &iv, "s");
+ if (rv != APR_SUCCESS) {
+ return "Unparse-able ProxyBeaconInterval setting";
+ }
+ if (iv < AP_WD_TM_SLICE) {
+ return apr_psprintf(cmd->pool,
+ "ProxyBeaconInterval must be greater than %"
+ APR_TIME_T_FMT "ms",
+ apr_time_as_msec(AP_WD_TM_SLICE));
+ }
+ ctx->interval = iv;
+ return NULL;
+}
+
+static const char *beacon_set_timeout(cmd_parms *cmd, void *dummy,
+ const char *arg)
+{
+ beacon_ctx_t *ctx = ap_get_module_config(cmd->server->module_config,
+ &proxy_beacon_module);
+ apr_interval_time_t iv;
+ apr_status_t rv;
+ const char *err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS);
+ if (err) {
+ return err;
+ }
+ rv = ap_timeout_parameter_parse(arg, &iv, "s");
+ if (rv != APR_SUCCESS || iv < 0) {
+ return "ProxyBeaconTimeout must be a non-negative time (0 disables "
+ "eviction)";
+ }
+ /* 0 = eviction disabled (pure announce-and-add behavior). */
+ ctx->evict_timeout = iv;
+ return NULL;
+}
+
+static int beacon_hexval(char c)
+{
+ return apr_isdigit(c) ? c - '0' : apr_tolower(c) - 'a' + 10;
+}
+
+static const char *beacon_set_secret(cmd_parms *cmd, void *dummy, const char *arg)
+{
+ beacon_ctx_t *ctx = ap_get_module_config(cmd->server->module_config,
+ &proxy_beacon_module);
+ const char *err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS);
+ if (err) {
+ return err;
+ }
+ if (!*arg) {
+ return "ProxyBeaconSecret: empty secret";
+ }
+ /* hex:<32 hex digits> is the key itself: a random 128-bit key has no
+ * passphrase to guess, so it needs no key derivation. */
+ if (!strncmp(arg, BEACON_HEXKEY_PREFIX, sizeof(BEACON_HEXKEY_PREFIX) - 1)) {
+ const char *h = arg + sizeof(BEACON_HEXKEY_PREFIX) - 1;
+ int i;
+
+ if (strlen(h) != 2 * sizeof(ctx->mac_key)) {
+ return apr_psprintf(cmd->pool,
+ "ProxyBeaconSecret: hex: needs exactly %d hex "
+ "digits (e.g. from 'openssl rand -hex %d')",
+ (int)(2 * sizeof(ctx->mac_key)),
+ (int)sizeof(ctx->mac_key));
+ }
+ for (i = 0; i < (int)sizeof(ctx->mac_key); i++) {
+ if (!apr_isxdigit(h[2 * i]) || !apr_isxdigit(h[2 * i + 1])) {
+ return "ProxyBeaconSecret: hex: value has a non-hex digit";
+ }
+ ctx->mac_key[i] = (unsigned char)
+ ((beacon_hexval(h[2 * i]) << 4) | beacon_hexval(h[2 * i + 1]));
+ }
+ ctx->has_secret = 1;
+ return NULL;
+ }
+ /* The MAC key is derived from the passphrase with a fast hash, so anyone who
+ * captures one announcement can test guesses offline at full speed; only a
+ * long random secret resists that. */
+ if (strlen(arg) < BEACON_MIN_SECRET_LEN) {
+ return apr_psprintf(cmd->pool,
+ "ProxyBeaconSecret: the secret must be at least %d "
+ "characters (use a long random value)",
+ BEACON_MIN_SECRET_LEN);
+ }
+ /* Derive a 16-byte SipHash key from the passphrase. This is key
+ * derivation (spreading the shared secret to the key size both ends use),
+ * not message hashing, so MD5 is fine here -- same approach as
+ * mod_session_crypto.c's compute_auth(). */
+ apr_md5(ctx->mac_key, arg, strlen(arg));
+ ctx->has_secret = 1;
+ return NULL;
+}
+
+static const char *beacon_set_maxskew(cmd_parms *cmd, void *dummy, const char *arg)
+{
+ beacon_ctx_t *ctx = ap_get_module_config(cmd->server->module_config,
+ &proxy_beacon_module);
+ apr_interval_time_t iv;
+ apr_status_t rv;
+ const char *err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS);
+ if (err) {
+ return err;
+ }
+ rv = ap_timeout_parameter_parse(arg, &iv, "s");
+ if (rv != APR_SUCCESS || iv <= 0) {
+ return "ProxyBeaconMaxSkew must be a positive time (replay window)";
+ }
+ ctx->max_skew = iv;
+ return NULL;
+}
+
+static const command_rec beacon_cmds[] = {
+ AP_INIT_TAKE_ARGV("ProxyBeaconListen", beacon_set_sub_url, NULL, RSRC_CONF,
+ "reverse proxy: UDP address [host][:port] to receive beacons "
+ "on. An omitted host or port (or no argument at all) is "
+ "inherited from this server's own address and port, so the "
+ "beacon channel can share the service endpoint. "
+ "e.g. 0.0.0.0:5555"),
+ AP_INIT_TAKE1("ProxyBeaconAddress", beacon_set_pub_url, NULL, RSRC_CONF,
+ "backend: UDP address host:port of the proxy to send beacons "
+ "to, e.g. proxy-host:5555"),
+ AP_INIT_TAKE1("ProxyBeaconInterval", beacon_set_interval, NULL, RSRC_CONF,
+ "backend announcement interval in seconds (default 5)"),
+ AP_INIT_TAKE1("ProxyBeaconAdvertise", beacon_set_advertise, NULL, RSRC_CONF,
+ "backend: routable URL to advertise to the proxy, "
+ "e.g. http://10.0.0.5:8080 (added as a BalancerMember)"),
+ AP_INIT_TAKE1("ProxyBeaconBalancer", beacon_set_balancer, NULL, RSRC_CONF,
+ "proxy: name of the balancer that announced backends are "
+ "added to, e.g. mycluster (for balancer://mycluster)"),
+ AP_INIT_TAKE1("ProxyBeaconTimeout", beacon_set_timeout, NULL, RSRC_CONF,
+ "proxy: seconds without an announcement after which a backend "
+ "is disabled (taken out of rotation); 0 disables eviction"),
+ AP_INIT_TAKE1("ProxyBeaconSecret", beacon_set_secret, NULL, RSRC_CONF,
+ "pre-shared cluster secret (REQUIRED); set to the same value on "
+ "the proxy and all backends to authenticate announcements "
+ "(SipHash MAC). Keep the conf file readable only by the server "
+ "user."),
+ AP_INIT_TAKE1("ProxyBeaconMaxSkew", beacon_set_maxskew, NULL, RSRC_CONF,
+ "proxy: max allowed seconds between an announcement's timestamp "
+ "and now (anti-replay window; requires NTP-synced clocks). "
+ "Default 30 seconds."),
+ { NULL }
+};
+
+/*
+ * Resolve a "[scheme://][host][:port]" address string to a UDP sockaddr. Any
+ * leading scheme (e.g. tcp://) is accepted and ignored, so addresses written
+ * with a transport scheme keep working. A NULL/empty url, or an omitted host
+ * or port, is filled from the caller-supplied defaults:
+ * - default_host NULL -> bind/resolve the wildcard address (all interfaces);
+ * - default_port 0 -> the port is then required (APR_EINVAL if missing).
+ * Letting the host/port be inherited lets the beacon channel share the server's
+ * own address:port; UDP and TCP are independent port spaces, so binding UDP:N
+ * does not collide with the server's TCP listener. *addr_out is from p.
+ */
+/*
+ * Split "[host][:port]". apr_parse_addr_port() refuses a string that starts
+ * with ':', which the directive syntax allows to mean "this server's host".
+ */
+static apr_status_t beacon_parse_hostport(apr_pool_t *p, const char *hostport,
+ char **host, apr_port_t *port)
+{
+ char *scope;
+
+ if (*hostport == ':') {
+ apr_off_t val;
+ char *end;
+
+ if (apr_isdigit(hostport[1]) == 0
+ || apr_strtoff(&val, hostport + 1, &end, 10) != APR_SUCCESS
+ || *end || val < 1 || val > 65535) {
+ return APR_EINVAL;
+ }
+ *host = NULL;
+ *port = (apr_port_t)val;
+ return APR_SUCCESS;
+ }
+ return apr_parse_addr_port(host, &scope, port, hostport, p);
+}
+
+static apr_status_t beacon_resolve(apr_pool_t *p, const char *url,
+ const char *default_host,
+ apr_port_t default_port,
+ apr_sockaddr_t **addr_out)
+{
+ char *host = NULL;
+ apr_port_t port = 0;
+ apr_status_t rv;
+
+ if (url && *url) {
+ const char *hostport = url, *sep;
+ if ((sep = ap_strstr_c(url, "://")) != NULL) {
+ hostport = sep + 3;
+ }
+ rv = beacon_parse_hostport(p, hostport, &host, &port);
+ if (rv != APR_SUCCESS) {
+ return rv;
+ }
+ }
+ if (!host || !*host) {
+ host = (char *)default_host; /* NULL -> wildcard (any address) */
+ }
+ if (!port) {
+ port = default_port;
+ }
+ if (!port) {
+ return APR_EINVAL; /* no port given and none to inherit */
+ }
+ return apr_sockaddr_info_get(addr_out, host, APR_UNSPEC, port, 0, p);
+}
+
+/*
+ * The listener may inherit its bind host/port from this server (so the beacon
+ * channel can share the server's own endpoint). Derive a concrete address/port
+ * from the server's actual bound listeners (ap_listeners) -- this reflects the
+ * real Listen socket (e.g. 0.0.0.0), which is what the beacon should match, and
+ * avoids leaving the host NULL (which resolves to the IPv6 wildcard and could
+ * miss IPv4 senders on a v6-only-strict host). The port is the server's own
+ * (ServerName/Listen) port; the host is taken from the listener on that port,
+ * else the first listener. Either output may remain unset (host NULL / port 0)
+ * if no listeners are configured.
+ */
+static void beacon_server_default_addr(server_rec *s, apr_pool_t *p,
+ const char **host_out,
+ apr_port_t *port_out)
+{
+ const char *host = NULL;
+ apr_port_t port = s->port;
+ ap_listen_rec *lr, *match = NULL;
+
+ for (lr = ap_listeners; lr; lr = lr->next) {
+ if (!lr->bind_addr) {
+ continue;
+ }
+ if (!match) {
+ match = lr; /* first, as a fallback */
+ }
+ if (port && lr->bind_addr->port == port) {
+ match = lr; /* prefer the server's own port */
+ break;
+ }
+ }
+ if (match && match->bind_addr) {
+ char ip[APRMAXHOSTLEN];
+ if (!port) {
+ port = match->bind_addr->port;
+ }
+ /* Not apr_sockaddr_ip_get(): it would allocate from the listener's
+ * pool, the process pool, which this watchdog thread must not use. */
+ if (apr_sockaddr_ip_getbuf(ip, sizeof ip, match->bind_addr)
+ == APR_SUCCESS) {
+ host = apr_pstrdup(p, ip);
+ }
+ }
+
+ *host_out = host;
+ *port_out = port;
+}
+
+/* STARTING: open the UDP socket; listener binds to receive, sender resolves
+ * its destination. */
+static void beacon_cb_starting(beacon_ctx_t *ctx)
+{
+ server_rec *s = ctx->s;
+ apr_status_t rv;
+
+ /* After an open/bind failure, wait for the retry in beacon_cb_running()
+ * (BEACON_OPEN_RETRY): retrying on every ~100ms watchdog tick would fill
+ * the error log. */
+ if (ctx->opened || ctx->open_failed) {
+ return;
+ }
+
+ /* The address and socket of an attempt live in their own pool, cleared
+ * before each retry so a persistent failure does not grow ctx->p. */
+ if (ctx->addr_pool) {
+ apr_pool_destroy(ctx->addr_pool);
+ ctx->addr_pool = NULL;
+ }
+ if (ctx->open_pool) {
+ apr_pool_clear(ctx->open_pool);
+ }
+ else {
+ apr_pool_create(&ctx->open_pool, ctx->p);
+ }
+
+ if (ctx->role == BEACON_ROLE_LISTEN) {
+ /* An omitted host and/or port in ProxyBeaconListen is inherited from
+ * this server's own address/port (ServerName/Listen), so the beacon
+ * channel can share the server's service endpoint. UDP and TCP are
+ * independent, so binding UDP: does not collide with the server's
+ * TCP listener. (A privileged port still cannot be bound here -- this
+ * callback runs in an unprivileged watchdog child -- so endpoint sharing
+ * is for non-privileged service ports.) */
+ const char *defhost;
+ apr_port_t defport;
+ beacon_server_default_addr(s, ctx->open_pool, &defhost, &defport);
+ if ((rv = beacon_resolve(ctx->open_pool, ctx->sub_url, defhost, defport,
+ &ctx->addr)) != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
+ APLOGNO(10567) "mod_proxy_beacon: cannot resolve "
+ "ProxyBeaconListen address '%s' (an omitted port "
+ "requires a known server port)",
+ *ctx->sub_url ? ctx->sub_url : "(inherit)");
+ ctx->open_failed = 1;
+ return;
+ }
+ if ((rv = apr_socket_create(&ctx->sock, ctx->addr->family, SOCK_DGRAM,
+ APR_PROTO_UDP, ctx->open_pool)) != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
+ APLOGNO(10568) "mod_proxy_beacon: apr_socket_create failed");
+ ctx->open_failed = 1;
+ return;
+ }
+ apr_socket_opt_set(ctx->sock, APR_SO_REUSEADDR, 1);
+ /* Receiving must never block: it happens on the watchdog thread. */
+ if ((rv = apr_socket_opt_set(ctx->sock, APR_SO_NONBLOCK, 1))
+ != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
+ APLOGNO(10637) "mod_proxy_beacon: cannot make the "
+ "listening socket non-blocking");
+ apr_socket_close(ctx->sock);
+ ctx->open_failed = 1;
+ return;
+ }
+ if ((rv = apr_socket_bind(ctx->sock, ctx->addr)) != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
+ APLOGNO(10569) "mod_proxy_beacon: bind to %pI failed",
+ ctx->addr);
+ apr_socket_close(ctx->sock);
+ ctx->open_failed = 1;
+ return;
+ }
+ ctx->opened = 1;
+ ctx->io_errors = 0;
+ {
+ /* Nothing could have been received while the socket was closed:
+ * do not evict members for that silence. */
+ apr_hash_index_t *hi;
+ apr_time_t t = apr_time_now();
+
+ for (hi = apr_hash_first(ctx->open_pool, ctx->seen); hi;
+ hi = apr_hash_next(hi)) {
+ void *val;
+
+ apr_hash_this(hi, NULL, NULL, &val);
+ ((beacon_member_t *)val)->last_seen = t;
+ }
+ }
+ ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s,
+ APLOGNO(10570) "mod_proxy_beacon: listening for beacons on %pI",
+ ctx->addr);
+ /* Warn if no balancer is configured: beacons will be logged but no
+ * backend workers will be added (Phase-1 log-only behavior). */
+ if (!ctx->balancer_name) {
+ ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
+ APLOGNO(10571) "mod_proxy_beacon: listener on %pI has no "
+ "ProxyBeaconBalancer; beacons will be logged only. "
+ "Set ProxyBeaconBalancer to add announced backends.",
+ ctx->addr);
+ }
+ }
+ else if (ctx->role == BEACON_ROLE_SEND) {
+ /* Sender: the destination host:port targets the proxy and cannot be
+ * inferred from this backend's own address, so both must be given
+ * explicitly (no defaults). */
+ if ((rv = beacon_resolve(ctx->open_pool, ctx->pub_url, NULL, 0, &ctx->addr))
+ != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
+ APLOGNO(10573) "mod_proxy_beacon: cannot resolve "
+ "ProxyBeaconAddress '%s' (must be host:port)",
+ ctx->pub_url);
+ ctx->open_failed = 1;
+ return;
+ }
+ if ((rv = apr_socket_create(&ctx->sock, ctx->addr->family, SOCK_DGRAM,
+ APR_PROTO_UDP, ctx->open_pool)) != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
+ APLOGNO(10574) "mod_proxy_beacon: apr_socket_create failed");
+ ctx->open_failed = 1;
+ return;
+ }
+ /* UDP is connectionless: no dial, no reconnect. Datagrams are sent to
+ * ctx->addr each interval; if the proxy isn't up yet they are simply
+ * dropped and the next interval tries again. */
+ if ((rv = apr_socket_opt_set(ctx->sock, APR_SO_NONBLOCK, 1))
+ != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
+ APLOGNO(10638) "mod_proxy_beacon: cannot make the "
+ "sending socket non-blocking");
+ apr_socket_close(ctx->sock);
+ ctx->open_failed = 1;
+ return;
+ }
+ ctx->opened = 1;
+ ctx->io_errors = 0;
+ ctx->next_refresh = apr_time_now() + BEACON_REFRESH;
+ ctx->last_publish = 0; /* beacon on the first running tick */
+ ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s,
+ APLOGNO(10575) "mod_proxy_beacon: beaconing to %pI", ctx->addr);
+ }
+}
+
+/*
+ * Synthesize a minimal request_rec for balancer_manage(), which runs here in
+ * the watchdog thread with no real client request. Adapted from
+ * mod_proxy_hcheck.c's create_request_rec (same watchdog context), but that one
+ * attaches a real backend conn_rec before logging; we have none, so we fabricate
+ * a minimal conn_rec too.
+ *
+ * balancer_manage()/balancer_process_balancer_worker() touch only r->pool,
+ * r->server, and ap_log_rerror(). ap_log_rerror is the trap: log_error_core()
+ * asserts r->connection != NULL and do_errorlog_default() unconditionally reads
+ * r->connection->outgoing, while add_log_id()->core_generate_log_id() reads
+ * c->current_thread. So we (a) give r a non-NULL conn_rec with ->outgoing set,
+ * and (b) pre-set r->log_id / c->log_id so the log-id generation path is skipped
+ * entirely.
+ */
+static request_rec *beacon_make_fake_request(apr_pool_t *p, server_rec *s)
+{
+ conn_rec *c = apr_pcalloc(p, sizeof(*c));
+ request_rec *r = apr_pcalloc(p, sizeof(*r));
+
+ c->pool = p;
+ c->base_server = s;
+ c->log = &s->log;
+ c->log_id = "beacon"; /* non-NULL -> skip add_log_id/log-id gen */
+ c->outgoing = 1; /* read by do_errorlog_default() */
+ c->client_ip = "-";
+ c->notes = apr_table_make(p, 1);
+
+ r->pool = p;
+ r->server = s;
+ r->connection = c;
+ r->log = &s->log;
+ r->log_id = "beacon";
+ r->per_dir_config = s->lookup_defaults;
+ r->request_config = ap_create_request_config(p);
+ r->notes = apr_table_make(p, 4);
+ r->subprocess_env = apr_table_make(p, 4);
+ r->headers_in = apr_table_make(p, 1);
+ r->headers_out = apr_table_make(p, 1);
+ r->err_headers_out = apr_table_make(p, 1);
+ r->useragent_ip = "-";
+ r->useragent_addr = NULL;
+ r->proxyreq = PROXYREQ_PROXY;
+ r->status = HTTP_OK;
+
+ return r;
+}
+
+/*
+ * Resolve mod_proxy_balancer's balancer_manage() optional fn (lazily, cached).
+ * Registered at hook-registration time, so available by the time we run.
+ */
+static int beacon_have_manage_fn(beacon_ctx_t *ctx)
+{
+ if (!ctx->manage_fn) {
+ ctx->manage_fn = APR_RETRIEVE_OPTIONAL_FN(balancer_manage);
+ if (!ctx->manage_fn) {
+ ap_log_error(APLOG_MARK, APLOG_ERR, 0, ctx->s,
+ APLOGNO(10576) "mod_proxy_beacon: balancer_manage unavailable "
+ "(is mod_proxy_balancer loaded?)");
+ return 0;
+ }
+ }
+ return 1;
+}
+
+/* Status flags a beacon worker is created with (see b_nwrkr_flags). */
+static const char beacon_new_flags[] = { PROXY_WORKER_BEACON_FLAG, '\0' };
+
+/*
+ * Look up url among the members of the configured balancer. Beacon only ever
+ * deals in canonical origins (see beacon_canonical_url()), for which the
+ * balancer's longest-prefix lookup can only match the worker of that exact name.
+ * balancer_manage()/balancer_process_balancer_worker() silently succeed on an
+ * operation on a worker they cannot find, so callers use this to learn what
+ * really happened. Returns NULL if there is no such member.
+ */
+static proxy_worker *beacon_find_worker(beacon_ctx_t *ctx, apr_pool_t *pool,
+ const char *url)
+{
+ proxy_server_conf *conf =
+ ap_get_module_config(ctx->s->module_config, &proxy_module);
+ proxy_balancer *bsel = ap_proxy_get_balancer(pool, conf,
+ apr_pstrcat(pool, BALANCER_PREFIX, ctx->balancer_name, NULL), 0);
+ proxy_worker *w;
+
+ if (!bsel) {
+ return NULL;
+ }
+ /* A worker added through another child's balancer-manager is not in this
+ * process's view until synced; without it the ownership check is blind. */
+ PROXY_THREAD_LOCK(bsel);
+ ap_proxy_sync_balancer(bsel, ctx->s, conf);
+ w = ap_proxy_get_worker(pool, bsel, conf, url);
+ PROXY_THREAD_UNLOCK(bsel);
+ return w;
+}
+
+static int beacon_worker_exists(beacon_ctx_t *ctx, apr_pool_t *pool,
+ const char *url)
+{
+ return beacon_find_worker(ctx, pool, url) != NULL;
+}
+
+/*
+ * Set (or clear) a worker's DISABLED flag via balancer_manage -- the exact path
+ * the balancer-manager UI uses (params { b, w, w_status_D }). This is how both
+ * "enable" (disabled=0) and "evict" (disabled=1) are performed. Returns
+ * APR_SUCCESS on success.
+ */
+static apr_status_t beacon_set_worker_disabled(beacon_ctx_t *ctx, apr_pool_t *pool,
+ const char *url, int disabled)
+{
+ apr_pool_t *subp;
+ request_rec *r;
+ apr_table_t *params;
+ apr_status_t rv;
+
+ /* ctx->manage_fn is resolved lazily; a status change can be the first
+ * balancer operation this process performs (e.g. re-enabling a member
+ * adopted from the previous watchdog owner). */
+ if (!beacon_have_manage_fn(ctx)) {
+ return APR_EGENERAL;
+ }
+
+ /* balancer_manage() reports success when it finds no such worker, which
+ * would let us record a status change that never happened. */
+ if (!beacon_worker_exists(ctx, pool, url)) {
+ return APR_ENOENT;
+ }
+
+ apr_pool_create(&subp, pool);
+ r = beacon_make_fake_request(subp, ctx->s);
+
+ params = apr_table_make(subp, 4);
+ apr_table_setn(params, "b", ctx->balancer_name);
+ apr_table_setn(params, "w", url);
+ apr_table_setn(params, "w_status_D", disabled ? "1" : "0");
+ rv = ctx->manage_fn(r, params);
+
+ apr_pool_destroy(subp);
+ return rv;
+}
+
+/*
+ * Emit a rate-limited (~1/s) message about dropped/failed announcements, so a
+ * full balancer or a flood of bad urls can't flood the error log. Shares the
+ * counter/timer with the Phase-4 rejection logging.
+ */
+static void beacon_log_throttled(beacon_ctx_t *ctx, apr_time_t now, const char *what)
+{
+ ctx->reject_count++;
+ if (ctx->last_reject_log == 0
+ || now - ctx->last_reject_log >= apr_time_from_sec(1)) {
+ ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ctx->s,
+ APLOGNO(10577) "mod_proxy_beacon: dropped %" APR_UINT64_T_FMT
+ " announcement(s) (last: %s)", ctx->reject_count, what);
+ ctx->reject_count = 0;
+ ctx->last_reject_log = now;
+ }
+}
+
+/*
+ * Attempt to add (and enable) url as a member of the configured balancer,
+ * reusing balancer_manage(). Two calls: add (the worker is created DISABLED by
+ * default), then clear the DISABLED flag so it serves traffic. Updates the
+ * caller-owned member entry m: m->added is set on success. Returns APR_SUCCESS
+ * on success. A failure here (e.g. the balancer is full) is expected and
+ * handled by the caller via backoff, not retried every announcement.
+ *
+ * Beacon only manages workers it created: a worker it adds is marked with
+ * PROXY_WORKER_BEACON, which lives in the worker's shared state and so outlives
+ * both this process and the watchdog owner that set it. A same-named worker
+ * that is not so marked (a BalancerMember from the configuration, or one an
+ * administrator added) is left alone.
+ */
+static apr_status_t beacon_try_add(beacon_ctx_t *ctx, apr_pool_t *pool,
+ const char *url, beacon_member_t *m,
+ apr_time_t now)
+{
+ server_rec *s = ctx->s;
+ apr_pool_t *subp;
+ request_rec *r;
+ apr_table_t *params;
+ apr_status_t rv;
+ proxy_worker *w;
+
+ m->last_attempt = now;
+
+ if (!beacon_have_manage_fn(ctx)) {
+ return APR_EGENERAL;
+ }
+
+ w = beacon_find_worker(ctx, pool, url);
+ if (w) {
+ /* The normal case after a graceful restart, when the balancer's
+ * members (persisted in shared memory) outlive this process's empty
+ * ctx->seen: balancer_manage() refuses to re-add an existing worker,
+ * so recover it -- otherwise a previously-evicted member would stay
+ * DISABLED forever -- but only if it is ours. */
+ if (!(w->s->status & PROXY_WORKER_BEACON)) {
+ beacon_log_throttled(ctx, now, "member not managed by beacon");
+ return APR_EEXIST;
+ }
+ ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s,
+ APLOGNO(10589) "mod_proxy_beacon: backend %s already in "
+ "balancer://%s (re-adopted)",
+ url, ctx->balancer_name);
+ }
+ else {
+ /* Step 1: add the worker (created DISABLED). A genuinely full
+ * balancer fails here; that is throttled and retried only after the
+ * backoff window, not on every announcement. */
+ apr_pool_create(&subp, pool);
+ r = beacon_make_fake_request(subp, s);
+ params = apr_table_make(subp, 4);
+ apr_table_setn(params, "b", ctx->balancer_name);
+ apr_table_setn(params, "b_nwrkr", url);
+ apr_table_setn(params, "b_wyes", "1");
+ apr_table_setn(params, "b_nwrkr_flags", beacon_new_flags);
+ rv = ctx->manage_fn(r, params);
+ apr_pool_destroy(subp);
+ if (rv != APR_SUCCESS) {
+ beacon_log_throttled(ctx, now, "balancer add failed (full?)");
+ return rv;
+ }
+ w = beacon_find_worker(ctx, pool, url);
+ if (!w) {
+ /* balancer_manage() said yes but there is no such member: don't
+ * claim a registration that did not happen. */
+ beacon_log_throttled(ctx, now, "balancer add not confirmed");
+ return APR_ENOENT;
+ }
+ if (!(w->s->status & PROXY_WORKER_BEACON)) {
+ /* Whatever this is, balancer_manage() did not create it with our
+ * mark, so it is not ours to manage (and to evict). */
+ beacon_log_throttled(ctx, now, "member not created by beacon");
+ return APR_EEXIST;
+ }
+ }
+
+ /* Step 2: enable it (clear the DISABLED flag) so it serves traffic.
+ * beacon_set_worker_disabled is self-contained -- it creates its own subpool
+ * from `pool`. */
+ rv = beacon_set_worker_disabled(ctx, pool, url, 0);
+ if (rv != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
+ APLOGNO(10578) "mod_proxy_beacon: added but failed to enable worker %s "
+ "in balancer://%s; will retry on its next announcement",
+ url, ctx->balancer_name);
+ /* Still a member, but disabled: recorded as evicted, so that the next
+ * announcement enables it (beacon_handle_announce). */
+ m->added = 1;
+ m->evicted = 1;
+ return rv;
+ }
+
+ m->added = 1;
+ m->evicted = 0;
+ ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s,
+ APLOGNO(10579) "mod_proxy_beacon: added backend %s to balancer://%s",
+ url, ctx->balancer_name);
+ return APR_SUCCESS;
+}
+
+/*
+ * Member records come from a free list, so the memory used for tracking is
+ * bounded by BEACON_MAX_MEMBERS records however many are reclaimed and
+ * recreated. Returns NULL if url does not fit.
+ */
+static beacon_member_t *beacon_member_new(beacon_ctx_t *ctx, const char *url,
+ apr_time_t now)
+{
+ beacon_member_t *m;
+
+ if (strlen(url) >= BEACON_URL_MAX) {
+ return NULL;
+ }
+ if (ctx->free_members) {
+ m = ctx->free_members;
+ ctx->free_members = m->next_free;
+ }
+ else {
+ m = apr_palloc(ctx->p, sizeof(*m));
+ }
+ memset(m, 0, sizeof(*m));
+ strcpy(m->url, url);
+ m->last_seen = now;
+ apr_hash_set(ctx->seen, m->url, APR_HASH_KEY_STRING, m);
+ return m;
+}
+
+static void beacon_member_free(beacon_ctx_t *ctx, beacon_member_t *m)
+{
+ apr_hash_set(ctx->seen, m->url, APR_HASH_KEY_STRING, NULL);
+ m->next_free = ctx->free_members;
+ ctx->free_members = m;
+}
+
+/*
+ * Handle one announced url. Tracks every url in ctx->seen (capped) so that:
+ * - a successful member is deduplicated and its last_seen refreshed;
+ * - a previously-evicted member is re-enabled when it announces again;
+ * - an add that failed (e.g. balancer full) is retried only after a backoff,
+ * not on every announcement.
+ * msg_ts is the signed timestamp (microseconds) from the verified message; this
+ * path is only reached on the authenticated balancer path, so it is always set.
+ */
+static void beacon_handle_announce(beacon_ctx_t *ctx, apr_pool_t *pool,
+ const char *url, apr_time_t now,
+ apr_int64_t msg_ts)
+{
+ beacon_member_t *m = apr_hash_get(ctx->seen, url, APR_HASH_KEY_STRING);
+
+ if (!m) {
+ /* Bound memory: don't track unboundedly many distinct urls (defense in
+ * depth against a buggy or compromised authenticated backend). */
+ if (apr_hash_count(ctx->seen) >= BEACON_MAX_MEMBERS) {
+ beacon_log_throttled(ctx, now, "member table full");
+ return;
+ }
+ m = beacon_member_new(ctx, url, now);
+ if (!m) {
+ return;
+ }
+ m->last_ts = msg_ts;
+ beacon_try_add(ctx, pool, m->url, m, now);
+ return;
+ }
+
+ /* Anti-replay (2): each url's signed ts must strictly increase. A replayed
+ * (byte-identical) announcement carries a ts we've already accepted, so
+ * reject it -- this closes the in-window replay the freshness check alone
+ * allows (e.g. replaying a dead backend's last announcement to keep it from
+ * being evicted). */
+ if (msg_ts <= m->last_ts) {
+ beacon_log_throttled(ctx, now, "replayed/reordered ts");
+ return;
+ }
+ m->last_ts = msg_ts;
+ m->last_seen = now;
+
+ if (!m->added) {
+ /* A prior add failed; retry, but only after the backoff window. */
+ if (now - m->last_attempt >= BEACON_RETRY_BACKOFF) {
+ beacon_try_add(ctx, pool, url, m, now);
+ }
+ return;
+ }
+
+ if (m->evicted) {
+ if (beacon_set_worker_disabled(ctx, pool, url, 0) == APR_SUCCESS) {
+ m->evicted = 0;
+ ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ctx->s,
+ APLOGNO(10580) "mod_proxy_beacon: re-enabled backend %s in "
+ "balancer://%s (announcing again)",
+ url, ctx->balancer_name);
+ }
+ }
+}
+
+/*
+ * Take over the beacon members already in the balancer.
+ *
+ * The leases (ctx->seen) are private to the watchdog-owning process, but the
+ * members they describe are not: they live in the balancer's shared memory and
+ * outlive that process. When the watchdog singleton moves to another child --
+ * after a crash, a recycle, or a restart -- the new owner starts with an empty
+ * table and would never evict a member that has since fallen silent, leaving it
+ * enabled for good.
+ *
+ * So, once, at the start of ownership, adopt every member carrying
+ * PROXY_WORKER_BEACON and start its lease now: it is evicted after the usual
+ * ProxyBeaconTimeout unless it announces again. A member that is already
+ * disabled is recorded as evicted, so that its next announcement re-enables it.
+ * Members without the mark (configured or added by an administrator) are not
+ * ours and are left alone.
+ *
+ * The per-member replay high-water mark is not recovered (last_ts starts at 0);
+ * see the replay notes in the documentation.
+ */
+static int beacon_reconcile(beacon_ctx_t *ctx, apr_pool_t *pool, apr_time_t now)
+{
+ proxy_server_conf *conf =
+ ap_get_module_config(ctx->s->module_config, &proxy_module);
+ proxy_balancer *bsel = ap_proxy_get_balancer(pool, conf,
+ apr_pstrcat(pool, BALANCER_PREFIX, ctx->balancer_name, NULL), 0);
+ proxy_worker **workers;
+ int i, adopted = 0, untracked = 0;
+
+ if (!bsel) {
+ return 0;
+ }
+
+ PROXY_THREAD_LOCK(bsel);
+ /* Pick up the members the previous owner added: this process's own view of
+ * the balancer only knows the ones that existed at configuration time.
+ * Without that the picture is incomplete: try again on the next tick. */
+ if (ap_proxy_sync_balancer(bsel, ctx->s, conf) != APR_SUCCESS) {
+ PROXY_THREAD_UNLOCK(bsel);
+ beacon_log_throttled(ctx, now, "takeover: balancer sync failed");
+ return 0;
+ }
+
+ workers = (proxy_worker **)bsel->workers->elts;
+ for (i = 0; i < bsel->workers->nelts; i++) {
+ proxy_worker *w = workers[i];
+ beacon_member_t *m;
+
+ if (!w->s || !(w->s->status & PROXY_WORKER_BEACON)
+ || apr_hash_get(ctx->seen, w->s->name, APR_HASH_KEY_STRING)) {
+ continue;
+ }
+ if (apr_hash_count(ctx->seen) >= BEACON_MAX_MEMBERS) {
+ /* No lease can be kept for it, so it would never be evicted: take
+ * it out of rotation until it announces again and is adopted. */
+ if (!(w->s->status & PROXY_WORKER_DISABLED)) {
+ ap_proxy_set_wstatus(PROXY_WORKER_DISABLED_FLAG, 1, w);
+ untracked++;
+ }
+ continue;
+ }
+ m = beacon_member_new(ctx, w->s->name, now);
+ if (!m) {
+ continue;
+ }
+ m->added = 1;
+ m->evicted = (w->s->status & PROXY_WORKER_DISABLED) != 0;
+ adopted++;
+ }
+ PROXY_THREAD_UNLOCK(bsel);
+
+ if (adopted) {
+ ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ctx->s,
+ APLOGNO(10636) "mod_proxy_beacon: took over %d existing "
+ "member(s) of balancer://%s; their leases restart now",
+ adopted, ctx->balancer_name);
+ }
+ if (untracked) {
+ ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ctx->s,
+ APLOGNO(10660) "mod_proxy_beacon: balancer://%s has more "
+ "members than the %d beacon can track; disabled %d of "
+ "them until they announce again",
+ ctx->balancer_name, BEACON_MAX_MEMBERS, untracked);
+ }
+ return 1;
+}
+
+/*
+ * Periodic sweep (watchdog singleton, throttled by the caller):
+ *
+ * - eviction: disable any member that has not announced within evict_timeout
+ * (no-op when eviction is disabled, timeout 0);
+ * - reclamation: forget members that are evicted, or whose add failed, once
+ * they have been silent long enough. Without this, failed registrations and
+ * departed backends would fill the BEACON_MAX_MEMBERS table for good and lock
+ * out new members.
+ *
+ * A record also carries the replay high-water mark, so it must outlive any
+ * replay of the member's last accepted message. That message was accepted at
+ * last_seen with a timestamp within max_skew of it, so it is stale (rejected by
+ * the freshness check) after last_seen + 2 * max_skew; reclaiming only after that
+ * loses no replay protection. A reclaimed member that announces again is simply
+ * recreated: its worker is still in the balancer and is re-adopted.
+ */
+static void beacon_sweep(beacon_ctx_t *ctx, apr_pool_t *pool, apr_time_t now)
+{
+ apr_hash_index_t *hi;
+ apr_time_t skew = ctx->max_skew > 0 ? ctx->max_skew : BEACON_MAXSKEW_DEFAULT;
+ /* Saturate: MaxSkew is any positive time the administrator wrote. */
+ apr_time_t reclaim_after =
+ skew > (APR_INT64_MAX - apr_time_from_sec(1)) / 2
+ ? APR_INT64_MAX : 2 * skew + apr_time_from_sec(1);
+
+ for (hi = apr_hash_first(pool, ctx->seen); hi; hi = apr_hash_next(hi)) {
+ void *val;
+ beacon_member_t *m;
+
+ apr_hash_this(hi, NULL, NULL, &val);
+ m = val;
+ if (ctx->evict_timeout > 0 && m->added && !m->evicted
+ && now - m->last_seen > ctx->evict_timeout
+ && beacon_have_manage_fn(ctx)) {
+ if (beacon_set_worker_disabled(ctx, pool, m->url, 1) == APR_SUCCESS) {
+ m->evicted = 1;
+ ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ctx->s,
+ APLOGNO(10581) "mod_proxy_beacon: evicted backend %s from "
+ "balancer://%s (no announcement for %"
+ APR_TIME_T_FMT "s)",
+ m->url, ctx->balancer_name,
+ apr_time_sec(now - m->last_seen));
+ }
+ }
+ else if ((!m->added || m->evicted)
+ && now - m->last_seen > reclaim_after) {
+ /* Safe while iterating: only the current entry is removed. */
+ beacon_member_free(ctx, m);
+ }
+ }
+}
+
+/*
+ * Extract the value of the "url=" token from a beacon message into buf.
+ * Returns 1 on success. The payload is untrusted network input, so parse
+ * defensively: the token is "url=" followed by non-space characters.
+ */
+static int beacon_parse_url(const char *msg, char *buf, apr_size_t buflen)
+{
+ const char *p = msg;
+
+ while (p && *p) {
+ if (!strncmp(p, "url=", 4)) {
+ apr_size_t i = 0;
+ p += 4;
+ while (*p && *p != ' ' && i + 1 < buflen) {
+ buf[i++] = *p++;
+ }
+ buf[i] = '\0';
+ /* A token that does not fit is rejected, not silently cut short:
+ * the truncated prefix could be a different, valid-looking url. */
+ if (*p && *p != ' ') {
+ return 0;
+ }
+ return (i > 0);
+ }
+ /* advance to the next space-separated token */
+ p = ap_strchr_c(p, ' ');
+ if (p) {
+ p++;
+ }
+ }
+ return 0;
+}
+
+/* ----- Phase 4: channel authentication (SipHash MAC + timestamp) ----- */
+
+/* Constant-time buffer compare (time depends only on size, not contents) --
+ * avoids a timing oracle on the MAC. apr_crypto_equals() would do this but is
+ * gated behind APU_HAVE_CRYPTO, which isn't always built; this is the same
+ * branchless idiom. */
+static int beacon_const_time_eq(const void *a, const void *b, apr_size_t n)
+{
+ const unsigned char *p1 = a, *p2 = b;
+ volatile unsigned char diff = 0;
+ apr_size_t i;
+ for (i = 0; i < n; i++) {
+ diff |= p1[i] ^ p2[i];
+ }
+ return diff == 0;
+}
+
+/* Hex-encode the SipHash-2-4 MAC of [base, base+len) into out (BEACON_MAC_HEXLEN+1
+ * bytes). */
+static void beacon_mac_hex(const beacon_ctx_t *ctx, const char *base,
+ apr_size_t len, char *out)
+{
+ unsigned char mac[APR_SIPHASH_DSIZE];
+ apr_siphash24_auth(mac, base, len, ctx->mac_key);
+ ap_bin2hex(mac, sizeof(mac), out); /* writes BEACON_MAC_HEXLEN + NUL */
+}
+
+/* sender: return " mac=", appending the keyed MAC. A secret is
+ * required on every participating server (enforced at config time), so this
+ * always signs. */
+static const char *beacon_sign(beacon_ctx_t *ctx, apr_pool_t *pool, const char *base)
+{
+ char hex[BEACON_MAC_HEXLEN + 1];
+
+ beacon_mac_hex(ctx, base, strlen(base), hex);
+ return apr_psprintf(pool, "%s mac=%s", base, hex);
+}
+
+/*
+ * Parse a timestamp token value strictly: 1 to 18 decimal digits, ending at a
+ * space or the end of the string. apr_atoi64() would also accept a sign,
+ * leading space, trailing garbage and out-of-range values, and arithmetic on an
+ * extreme timestamp could overflow.
+ */
+static int beacon_parse_ts(const char *p, apr_int64_t *out)
+{
+ apr_int64_t v = 0;
+ int n = 0;
+
+ for (; apr_isdigit(*p); p++, n++) {
+ if (n >= 18) {
+ return 0;
+ }
+ v = v * 10 + (*p - '0');
+ }
+ if (!n || (*p && *p != ' ')) {
+ return 0;
+ }
+ *out = v;
+ return 1;
+}
+
+/*
+ * Check the wire grammar of a message whose MAC has already been verified:
+ *
+ * BEACON = = ... mac=
+ *
+ * one leading BEACON marker, single-space-separated key=value tokens with a
+ * lower-case key and a non-empty value, and no repeated field among the ones we
+ * know. Without this the receiver reads fields by searching the string (the
+ * last "ts=" wins, a leading marker is never checked, a repeated field is
+ * silently resolved one way), so two parties can read the same signed bytes
+ * differently. Returns the ts= value via *tsp (NULL if absent).
+ */
+static const char *beacon_frame_check(const char *msg, const char **tsp,
+ const char **reason)
+{
+ static const char * const known[] = {
+ "url", "host", "pid", "seq", "ts", "mac"
+ };
+ unsigned seen = 0;
+ const char *p = msg;
+
+ *tsp = NULL;
+ if (strncmp(p, "BEACON ", 7)) {
+ *reason = "bad frame";
+ return NULL;
+ }
+ p += 7;
+
+ while (*p) {
+ const char *key = p, *eq;
+ apr_size_t klen;
+ unsigned i;
+
+ while (*p && *p != ' ') {
+ p++;
+ }
+ eq = memchr(key, '=', p - key);
+ if (p == key || !eq || eq == key || eq + 1 == p) {
+ *reason = "bad frame";
+ return NULL;
+ }
+ for (klen = 0; key + klen < eq; klen++) {
+ if (!apr_islower(key[klen])) {
+ *reason = "bad frame";
+ return NULL;
+ }
+ }
+ for (i = 0; i < sizeof(known) / sizeof(known[0]); i++) {
+ if (strlen(known[i]) == klen && !strncmp(key, known[i], klen)) {
+ if (seen & (1u << i)) {
+ *reason = "duplicate field";
+ return NULL;
+ }
+ seen |= 1u << i;
+ if (!strcmp(known[i], "ts")) {
+ *tsp = eq + 1;
+ }
+ break;
+ }
+ }
+ if (*p == ' ') {
+ p++;
+ if (!*p) {
+ *reason = "bad frame"; /* trailing space */
+ return NULL;
+ }
+ }
+ }
+ return msg;
+}
+
+/*
+ * listener: verify a received, NUL-terminated message. Returns 1 if the MAC matches
+ * the pre-shared key, the message is well-formed, AND the ts= timestamp is within
+ * ctx->max_skew of now.
+ * Only called when ctx->has_secret. Constant-time MAC compare. On success the
+ * parsed ts= (microseconds since the epoch) is written to *ts_out for the
+ * caller's per-url monotonic replay check. reason (out) is set on failure.
+ */
+static int beacon_verify(beacon_ctx_t *ctx, const char *msg, apr_time_t now,
+ apr_int64_t *ts_out, const char **reason)
+{
+ const char *macp = NULL, *p, *tsp;
+ char expected[BEACON_MAC_HEXLEN + 1];
+ apr_size_t prefix_len;
+ apr_int64_t ts, skew, delta;
+
+ /* Locate the last " mac=" -- the MAC covers everything before it. */
+ for (p = msg; (p = ap_strstr_c(p, " mac=")) != NULL; p += 5) {
+ macp = p;
+ }
+ if (!macp) {
+ *reason = "no mac";
+ return 0;
+ }
+ /* mac= must be the final field: exactly BEACON_MAC_HEXLEN chars followed by
+ * end-of-string. strlen is NUL-safe here -- the caller hands us a
+ * NUL-terminated copy with no embedded NUL -- so a short or garbled payload
+ * cannot make the constant-time compare below over-read past the buffer.
+ * The compare itself validates the hex content; we deliberately do not
+ * pre-scan for hex digits, which would leak MAC bytes through an early
+ * exit (timing oracle). */
+ if (strlen(macp + 5) != BEACON_MAC_HEXLEN) {
+ *reason = "bad mac length";
+ return 0;
+ }
+
+ prefix_len = (apr_size_t)(macp - msg);
+ beacon_mac_hex(ctx, msg, prefix_len, expected);
+ if (!beacon_const_time_eq(expected, macp + 5, BEACON_MAC_HEXLEN)) {
+ *reason = "mac mismatch";
+ return 0;
+ }
+
+ /* Authentic. Now insist it is also well-formed, so that every reader of
+ * these bytes sees the same fields. */
+ if (!beacon_frame_check(msg, &tsp, reason)) {
+ return 0;
+ }
+
+ /* Anti-replay (1): ts= must be present and within the freshness window.
+ * ts is in microseconds (raw apr_time_now()) so that announcements made
+ * less than a second apart still have strictly-increasing timestamps for
+ * the caller's per-url check. */
+ if (!tsp) {
+ *reason = "no ts";
+ return 0;
+ }
+ if (!beacon_parse_ts(tsp, &ts)) {
+ *reason = "bad ts";
+ return 0;
+ }
+ skew = ctx->max_skew > 0 ? ctx->max_skew : BEACON_MAXSKEW_DEFAULT;
+ delta = (apr_int64_t)now - ts; /* both well below 2^62: no overflow */
+ if (delta < 0) {
+ delta = -delta;
+ }
+ if (delta > skew) {
+ *reason = "stale timestamp";
+ return 0;
+ }
+
+ *ts_out = ts;
+ return 1;
+}
+
+/* RUNNING: sender sends a throttled beacon; listener drains its receive socket. */
+/*
+ * Count a failed send or receive. Returns true if it should be logged, which is
+ * at most once in 10 seconds. After BEACON_IO_ERRORS_MAX in a row the socket
+ * is closed: the open back-off in beacon_cb_running() opens it again, looking
+ * the address up again.
+ */
+static int beacon_io_failed(beacon_ctx_t *ctx, apr_time_t now)
+{
+ int log_it = now - ctx->last_io_error_log >= apr_time_from_sec(10);
+
+ if (log_it) {
+ ctx->last_io_error_log = now;
+ }
+ if (++ctx->io_errors >= BEACON_IO_ERRORS_MAX) {
+ ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ctx->s, APLOGNO(10672)
+ "mod_proxy_beacon: closing the socket after repeated "
+ "errors; it will be opened again");
+ apr_socket_close(ctx->sock);
+ ctx->opened = 0;
+ ctx->open_failed = 1;
+ ctx->io_errors = 0;
+ }
+ return log_it;
+}
+
+/*
+ * Sender: look the destination up again. The address in use is kept if that
+ * fails. This runs on the watchdog thread, so a slow resolver delays the other
+ * contexts for as long as the lookup takes: ProxyBeaconAddress should be an IP
+ * address, or a name that resolves quickly.
+ */
+static void beacon_refresh_destination(beacon_ctx_t *ctx, apr_time_t now)
+{
+ apr_pool_t *np;
+ apr_pool_t *old;
+ apr_sockaddr_t *na = NULL;
+ apr_status_t rv;
+
+ ctx->next_refresh = now + BEACON_REFRESH;
+ apr_pool_create(&np, ctx->p);
+ rv = beacon_resolve(np, ctx->pub_url, NULL, 0, &na);
+ if (rv != APR_SUCCESS) {
+ apr_pool_destroy(np);
+ ap_log_error(APLOG_MARK, APLOG_WARNING, rv, ctx->s, APLOGNO(10673)
+ "mod_proxy_beacon: cannot resolve ProxyBeaconAddress '%s' "
+ "again; keeping the address in use", ctx->pub_url);
+ return;
+ }
+ if (na->family != ctx->addr->family) {
+ /* The socket belongs to the old family: open a new one. */
+ apr_pool_destroy(np);
+ apr_socket_close(ctx->sock);
+ ctx->opened = 0;
+ beacon_cb_starting(ctx);
+ return;
+ }
+ if (!apr_sockaddr_equal(na, ctx->addr)) {
+ ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ctx->s, APLOGNO(10674)
+ "mod_proxy_beacon: beaconing to %pI now", na);
+ }
+ old = ctx->addr_pool;
+ ctx->addr_pool = np;
+ ctx->addr = na;
+ if (old) {
+ apr_pool_destroy(old);
+ }
+}
+
+static void beacon_cb_running(beacon_ctx_t *ctx, apr_pool_t *pool)
+{
+ server_rec *s = ctx->s;
+ apr_status_t rv;
+
+ if (ctx->open_failed) {
+ /* Retry a failed open, at a pace that cannot flood the log. */
+ apr_time_t t = apr_time_now();
+ if (!ctx->next_open_try) {
+ ctx->open_delay = ctx->open_delay
+ ? ctx->open_delay * 2 : BEACON_OPEN_RETRY;
+ if (ctx->open_delay > BEACON_OPEN_RETRY_MAX) {
+ ctx->open_delay = BEACON_OPEN_RETRY_MAX;
+ }
+ ctx->next_open_try = t + ctx->open_delay;
+ }
+ else if (t >= ctx->next_open_try) {
+ ctx->open_failed = 0;
+ ctx->next_open_try = 0;
+ beacon_cb_starting(ctx);
+ }
+ }
+ if (!ctx->opened) {
+ return;
+ }
+ ctx->open_delay = 0;
+
+ if (ctx->role == BEACON_ROLE_LISTEN && ctx->balancer_name
+ && !ctx->reconciled) {
+ ctx->reconciled = beacon_reconcile(ctx, pool, apr_time_now());
+ }
+
+ if (ctx->role == BEACON_ROLE_SEND) {
+ apr_time_t now = apr_time_now();
+
+ if (now >= ctx->next_refresh) {
+ beacon_refresh_destination(ctx, now);
+ if (!ctx->opened) {
+ return;
+ }
+ }
+ if (now >= ctx->last_publish + ctx->interval) {
+ const char *host = ctx->s->server_hostname
+ ? ctx->s->server_hostname : "(unknown)";
+ const char *msg;
+ char *base;
+ apr_size_t len;
+ /* Carry the routable URL so the proxy can add us as a member.
+ * Without ProxyBeaconAdvertise, fall back to the Phase-1 payload
+ * (channel proof only; the listener just logs it). ts= is the signing
+ * timestamp in microseconds (Phase 4 anti-replay): the proxy checks
+ * both a freshness window and that it strictly increases per url, so
+ * a byte-identical replay (same ts) is rejected. Harmless when
+ * unsigned. */
+ if (ctx->advertise_url) {
+ base = apr_psprintf(pool,
+ "BEACON url=%s host=%s pid=%" APR_PID_T_FMT
+ " seq=%" APR_UINT64_T_FMT " ts=%" APR_INT64_T_FMT,
+ ctx->advertise_url, host, getpid(), ctx->seq++,
+ (apr_int64_t)now);
+ }
+ else {
+ base = apr_psprintf(pool,
+ "BEACON host=%s pid=%" APR_PID_T_FMT
+ " seq=%" APR_UINT64_T_FMT " ts=%" APR_INT64_T_FMT,
+ host, getpid(), ctx->seq++,
+ (apr_int64_t)now);
+ }
+ /* Phase 4: append a keyed MAC when a shared secret is configured. */
+ msg = beacon_sign(ctx, pool, base);
+ /* Send strlen(msg) bytes (no trailing NUL on the wire) as a single
+ * UDP datagram to the proxy. Fire-and-forget; a failure here just
+ * means this announcement is lost and the next interval retries. */
+ len = strlen(msg);
+ if ((rv = apr_socket_sendto(ctx->sock, ctx->addr, 0, msg, &len))
+ != APR_SUCCESS) {
+ if (beacon_io_failed(ctx, now)) {
+ ap_log_error(APLOG_MARK, APLOG_WARNING, rv, s,
+ APLOGNO(10582) "mod_proxy_beacon: sendto %s "
+ "failed", ctx->pub_url);
+ }
+ }
+ else {
+ ctx->io_errors = 0;
+ }
+ ctx->last_publish = now;
+ }
+ }
+ else if (ctx->role == BEACON_ROLE_LISTEN) {
+ apr_time_t now;
+ apr_pool_t *ptemp;
+ apr_time_t started = apr_time_now();
+ int n;
+
+ apr_pool_create(&ptemp, pool);
+ apr_pool_tag(ptemp, "beacon_recv");
+
+ /* Drain the socket every tick (re-enable latency matters), up to
+ * BEACON_MAX_DRAIN datagrams and BEACON_DRAIN_BUDGET of time. */
+ for (n = 0; n < BEACON_MAX_DRAIN; n++) {
+ char buf[BEACON_MAX_MSG_LEN + 2];
+ apr_sockaddr_t from;
+ /* Ask for one byte more than we accept: recvfrom() silently
+ * truncates a longer datagram to the buffer size, so receiving
+ * the extra byte is how an oversize datagram is told from one
+ * that exactly fits. */
+ apr_size_t sz = BEACON_MAX_MSG_LEN + 1;
+ apr_time_t msg_now;
+ const char *msg_str;
+ char url[BEACON_URL_MAX];
+ apr_int64_t msg_ts = 0;
+
+ if (n && apr_time_now() - started > BEACON_DRAIN_BUDGET) {
+ break;
+ }
+ apr_pool_clear(ptemp);
+ from.pool = ptemp;
+ rv = apr_socket_recvfrom(&from, ctx->sock, 0, buf, &sz);
+ if (APR_STATUS_IS_EAGAIN(rv)) {
+ ctx->io_errors = 0;
+ break; /* socket drained */
+ }
+ if (rv != APR_SUCCESS) {
+ if (beacon_io_failed(ctx, apr_time_now())) {
+ ap_log_error(APLOG_MARK, APLOG_WARNING, rv, s,
+ APLOGNO(10583) "mod_proxy_beacon: recvfrom "
+ "failed");
+ }
+ break;
+ }
+ ctx->io_errors = 0;
+ if (sz == 0) {
+ continue; /* empty datagram */
+ }
+
+ /* Capture a single wall-clock snapshot for this message so that
+ * MAC verification, throttle logging, and last-seen recording all
+ * share the same time base (no TOCTOU drift across calls). */
+ msg_now = apr_time_now();
+
+ if (sz > BEACON_MAX_MSG_LEN) {
+ beacon_log_throttled(ctx, msg_now, "oversize datagram");
+ continue;
+ }
+ /* Our messages are text. A NUL would end the string every parser
+ * below works on while the datagram goes on, so what is verified
+ * and what was sent would differ. */
+ if (memchr(buf, '\0', sz)) {
+ beacon_log_throttled(ctx, msg_now, "embedded NUL");
+ continue;
+ }
+ buf[sz] = '\0';
+ msg_str = buf;
+
+ /* Phase 4: verify the MAC and freshness BEFORE logging or acting on
+ * the payload, so forged/tampered content is dropped (throttled) and
+ * never reaches the INFO log. A secret is required (enforced at
+ * config time) on every participating server, with or without a
+ * ProxyBeaconBalancer. msg_ts (microseconds) is the signed
+ * timestamp, used below for the per-url monotonic replay check. */
+ {
+ const char *reason = "?";
+ if (!beacon_verify(ctx, msg_str, msg_now, &msg_ts, &reason)) {
+ beacon_log_throttled(ctx, msg_now, reason);
+ continue;
+ }
+ }
+
+ /* Escape the payload before it reaches the log, so even an
+ * authenticated sender cannot embed newline/control/ANSI sequences
+ * to forge or corrupt error-log lines. Done only after
+ * verification so a rejected datagram allocates nothing. */
+ if (APLOGinfo(s)) {
+ /* An authentic message can be replayed within the freshness
+ * window as often as the sender likes: bound the log. */
+ if (msg_now - ctx->recv_log_window >= apr_time_from_sec(1)) {
+ if (ctx->recv_log_suppressed) {
+ ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
+ APLOGNO(10675) "mod_proxy_beacon: %"
+ APR_UINT64_T_FMT " received: lines left "
+ "out in the last second",
+ ctx->recv_log_suppressed);
+ }
+ ctx->recv_log_window = msg_now;
+ ctx->recv_log_count = 0;
+ ctx->recv_log_suppressed = 0;
+ }
+ if (ctx->recv_log_count < BEACON_RECV_LOG_PER_SEC) {
+ ctx->recv_log_count++;
+ ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
+ APLOGNO(10584) "mod_proxy_beacon: received: %s",
+ ap_escape_logitem(ptemp, msg_str));
+ }
+ else {
+ ctx->recv_log_suppressed++;
+ }
+ }
+
+ if (!ctx->balancer_name) {
+ continue;
+ }
+
+ /* Phase 2/3: carries a routable url= -> add the backend (or
+ * refresh last-seen / re-enable if previously evicted). */
+ if (beacon_parse_url(msg_str, url, sizeof(url))) {
+ /* A valid MAC only shows the sender holds the secret, not
+ * that it used the bundled sender: apply the sender's rule
+ * here too, and track the member by its canonical origin. */
+ const char *canon = beacon_canonical_url(ptemp, url);
+ if (!canon) {
+ beacon_log_throttled(ctx, msg_now, "unacceptable url");
+ continue;
+ }
+ beacon_handle_announce(ctx, ptemp, canon, msg_now, msg_ts);
+ }
+ }
+ apr_pool_destroy(ptemp);
+
+ /* Phase 3: evict backends that stopped announcing. Throttle the scan
+ * to ~1s (the recv drain above already runs every tick). */
+ now = apr_time_now();
+ if (ctx->balancer_name
+ && now - ctx->last_sweep >= apr_time_from_sec(1)) {
+ beacon_sweep(ctx, pool, now);
+ ctx->last_sweep = now;
+ }
+ }
+}
+
+/* STOPPING: close the socket if we opened it. */
+static void beacon_cb_stopping(beacon_ctx_t *ctx)
+{
+ if (ctx->opened) {
+ apr_socket_close(ctx->sock);
+ ctx->opened = 0;
+ ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ctx->s,
+ APLOGNO(10585) "mod_proxy_beacon: socket closed");
+ }
+}
+
+/*
+ * Watchdog callback. Always returns APR_SUCCESS: a non-success return would
+ * unregister the callback and permanently stop the channel, which we never
+ * want for a transient socket error.
+ */
+static apr_status_t beacon_watchdog_callback(int state, void *data,
+ apr_pool_t *pool)
+{
+ beacon_ctx_t *ctx = (beacon_ctx_t *)data;
+
+ switch (state) {
+ case AP_WATCHDOG_STATE_STARTING:
+ beacon_cb_starting(ctx);
+ break;
+ case AP_WATCHDOG_STATE_RUNNING:
+ beacon_cb_running(ctx, pool);
+ break;
+ case AP_WATCHDOG_STATE_STOPPING:
+ beacon_cb_stopping(ctx);
+ break;
+ }
+
+ return APR_SUCCESS;
+}
+
+static int beacon_post_config(apr_pool_t *pconf, apr_pool_t *plog,
+ apr_pool_t *ptemp, server_rec *main_s)
+{
+ apr_status_t rv;
+ server_rec *s;
+ APR_OPTIONAL_FN_TYPE(ap_watchdog_get_instance) *beacon_get_instance;
+ APR_OPTIONAL_FN_TYPE(ap_watchdog_register_callback) *beacon_register_callback;
+
+ /* post_config runs twice; skip the initial config-test pass. */
+ if (ap_state_query(AP_SQ_MAIN_STATE) == AP_SQ_MS_CREATE_PRE_CONFIG) {
+ return OK;
+ }
+
+ beacon_get_instance = APR_RETRIEVE_OPTIONAL_FN(ap_watchdog_get_instance);
+ beacon_register_callback =
+ APR_RETRIEVE_OPTIONAL_FN(ap_watchdog_register_callback);
+ if (!beacon_get_instance || !beacon_register_callback) {
+ ap_log_error(APLOG_MARK, APLOG_CRIT, 0, main_s,
+ APLOGNO(10586) "mod_proxy_beacon: mod_watchdog is required");
+ return !OK;
+ }
+
+ rv = beacon_get_instance(&beacon_watchdog, BEACON_WATCHDOG_NAME, 0, 1, pconf);
+ if (rv) {
+ ap_log_error(APLOG_MARK, APLOG_CRIT, rv, main_s,
+ APLOGNO(10587) "mod_proxy_beacon: failed to create watchdog instance (%s)",
+ BEACON_WATCHDOG_NAME);
+ return !OK;
+ }
+
+ for (s = main_s; s; s = s->next) {
+ beacon_ctx_t *ctx = ap_get_module_config(s->module_config,
+ &proxy_beacon_module);
+ /* Skip non-canonical server contexts (shared across vhosts). */
+ if (s != ctx->s) {
+ continue;
+ }
+ /* Only servers with a directive participate. */
+ if (ctx->role == BEACON_ROLE_NONE) {
+ continue;
+ }
+ /* ProxyBeaconSecret is required on every participating server (sender or
+ * listener): the channel is authenticated, with no unauthenticated mode.
+ * A UDP source address is trivially spoofable, so an unsigned channel
+ * would let anyone who can reach the listen port announce an arbitrary
+ * backend url and hijack client traffic. Fail startup rather than run
+ * insecurely. */
+ if (!ctx->has_secret) {
+ ap_log_error(APLOG_MARK, APLOG_CRIT, 0, s,
+ APLOGNO(10572) "mod_proxy_beacon: ProxyBeaconSecret is "
+ "required but not set; the beacon channel must be "
+ "authenticated. Set ProxyBeaconSecret to the same value "
+ "on the proxy and all backends.");
+ return !OK;
+ }
+ rv = beacon_register_callback(beacon_watchdog, AP_WD_TM_SLICE, ctx,
+ beacon_watchdog_callback);
+ if (rv) {
+ ap_log_error(APLOG_MARK, APLOG_CRIT, rv, s,
+ APLOGNO(10588) "mod_proxy_beacon: failed to register watchdog callback");
+ return !OK;
+ }
+ }
+
+ return OK;
+}
+
+/*
+ * "[scheme://][host][:port]" syntax only, with no lookup: a name that does not
+ * resolve yet may be fine once the network is up, but a malformed address never
+ * is. A sender needs both host and port; a listener inherits what is omitted.
+ */
+static int beacon_addr_syntax_ok(apr_pool_t *p, const char *url,
+ int need_host_port)
+{
+ char *host = NULL;
+ apr_port_t port = 0;
+ const char *hostport = url, *sep;
+
+ if (url && (sep = ap_strstr_c(url, "://")) != NULL) {
+ hostport = sep + 3;
+ }
+ if (!hostport || !*hostport) {
+ return !need_host_port;
+ }
+ if (beacon_parse_hostport(p, hostport, &host, &port) != APR_SUCCESS) {
+ return 0;
+ }
+ return !need_host_port || (host && *host && port);
+}
+
+/*
+ * Everything that is wrong with the configuration for good, however the
+ * network is when the server starts, so that "httpd -t" says so and a start
+ * does not go ahead only to fail in a child. What can change (the address
+ * resolving, the port binding) is left to the retries in the watchdog callback.
+ */
+static int beacon_check_config(apr_pool_t *pconf, apr_pool_t *plog,
+ apr_pool_t *ptemp, server_rec *main_s)
+{
+ server_rec *s, *t;
+ int errs = 0, participating = 0;
+
+ for (s = main_s; s; s = s->next) {
+ beacon_ctx_t *ctx = ap_get_module_config(s->module_config,
+ &proxy_beacon_module);
+ if (s != ctx->s || ctx->role == BEACON_ROLE_NONE) {
+ continue;
+ }
+ participating++;
+
+ if (!ctx->has_secret) {
+ ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_ERR, 0, s,
+ APLOGNO(10661) "mod_proxy_beacon: ProxyBeaconSecret "
+ "is required but not set; the beacon channel must be "
+ "authenticated");
+ errs++;
+ }
+
+ if (ctx->role == BEACON_ROLE_SEND) {
+ if (!beacon_addr_syntax_ok(ptemp, ctx->pub_url, 1)) {
+ ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_ERR, 0, s,
+ APLOGNO(10662) "mod_proxy_beacon: "
+ "ProxyBeaconAddress '%s' must be host:port",
+ ctx->pub_url);
+ errs++;
+ }
+ continue;
+ }
+
+ if (!beacon_addr_syntax_ok(ptemp, ctx->sub_url, 0)) {
+ ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_ERR, 0, s,
+ APLOGNO(10663) "mod_proxy_beacon: ProxyBeaconListen "
+ "'%s' must be [host][:port]", ctx->sub_url);
+ errs++;
+ }
+ if (ctx->balancer_name) {
+ proxy_server_conf *conf = ap_get_module_config(s->module_config,
+ &proxy_module);
+ if (!conf || !ap_proxy_get_balancer(ptemp, conf,
+ apr_pstrcat(ptemp, BALANCER_PREFIX, ctx->balancer_name,
+ NULL), 0)) {
+ ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_ERR, 0, s,
+ APLOGNO(10664) "mod_proxy_beacon: "
+ "ProxyBeaconBalancer: balancer://%s is not "
+ "defined for this server", ctx->balancer_name);
+ errs++;
+ }
+ if (!APR_RETRIEVE_OPTIONAL_FN(balancer_manage)) {
+ ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_ERR, 0, s,
+ APLOGNO(10665) "mod_proxy_beacon: "
+ "ProxyBeaconBalancer needs mod_proxy_balancer");
+ errs++;
+ }
+ }
+ /* Two listeners on one address: only one of them would receive. */
+ for (t = main_s; t != s; t = t->next) {
+ beacon_ctx_t *other = ap_get_module_config(t->module_config,
+ &proxy_beacon_module);
+ if (t == other->s && other->role == BEACON_ROLE_LISTEN
+ && !strcmp(other->sub_url, ctx->sub_url)) {
+ ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_WARNING, 0, s,
+ APLOGNO(10667) "mod_proxy_beacon: ProxyBeaconListen "
+ "'%s' is also written for another server; if "
+ "both resolve to the same address, only one of "
+ "them will receive the beacons", ctx->sub_url);
+ }
+ }
+ }
+
+ if (participating
+ && !APR_RETRIEVE_OPTIONAL_FN(ap_watchdog_get_instance)) {
+ ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_ERR, 0, main_s,
+ APLOGNO(10666) "mod_proxy_beacon: mod_watchdog is "
+ "required");
+ errs++;
+ }
+
+ return errs ? !OK : OK;
+}
+
+static void beacon_register_hooks(apr_pool_t *p)
+{
+ static const char *const aszSucc[] = { "mod_watchdog.c",
+ "mod_proxy_balancer.c", NULL };
+ ap_hook_check_config(beacon_check_config, NULL, NULL, APR_HOOK_MIDDLE);
+ ap_hook_post_config(beacon_post_config, NULL, aszSucc, APR_HOOK_LAST);
+}
+
+AP_DECLARE_MODULE(proxy_beacon) =
+{
+ STANDARD20_MODULE_STUFF,
+ NULL, /* create per-dir config */
+ NULL, /* merge per-dir config */
+ beacon_create_server_config, /* create per-server config */
+ NULL, /* merge per-server config */
+ beacon_cmds, /* command table */
+ beacon_register_hooks /* register hooks */
+};
diff --git a/modules/proxy/mod_proxy_hcheck.c b/modules/proxy/mod_proxy_hcheck.c
index c5064607e2d..860c53037c7 100644
--- a/modules/proxy/mod_proxy_hcheck.c
+++ b/modules/proxy/mod_proxy_hcheck.c
@@ -52,7 +52,7 @@ typedef struct {
} hc_condition_t;
typedef struct {
- apr_pool_t *p;
+ apr_pool_t *p; /* Stays first: mod_aptest's pool probe reads it */
apr_array_header_t *templates;
apr_table_t *conditions;
apr_hash_t *hcworkers;
@@ -66,6 +66,7 @@ typedef struct {
const char *req; /* pre-formatted HTTP/AJP request */
proxy_worker *w; /* Pointer to the actual worker */
const char *protocol; /* HTTP 1.0 or 1.1? */
+ apr_pool_t *req_pool; /* For req once rebuilt, cleared when rebuilt again */
} wctx_t;
typedef struct {
@@ -87,7 +88,9 @@ static void *hc_create_config(apr_pool_t *p, server_rec *s)
apr_pool_tag(ctx->p, "proxy_hcheck");
ctx->templates = apr_array_make(p, 10, sizeof(hc_template_t));
ctx->conditions = apr_table_make(p, 10);
- ctx->hcworkers = apr_hash_make(p);
+ /* Filled by the watchdog at run time, while other threads allocate from
+ * pconf (balancers' workers arrays): keep it in our own pool. */
+ ctx->hcworkers = apr_hash_make(ctx->p);
return ctx;
}
@@ -547,7 +550,20 @@ static proxy_worker *hc_get_hcworker(sctx_t *ctx, proxy_worker *worker,
worker, worker->s->scheme, worker->s->hostname_ex,
(int)port);
hc->s->method = worker->s->method;
- create_hcheck_req(wctx, hc, ctx->p);
+ /* Rebuild the request in a pool of its own, created at the first
+ * change only (a pool costs at least 8KB) and cleared at the next
+ * ones. No check of the worker can be using the old request here:
+ * the watchdog starts the next check only once the previous one is
+ * done.
+ */
+ if (!wctx->req_pool) {
+ apr_pool_create(&wctx->req_pool, ctx->p);
+ apr_pool_tag(wctx->req_pool, "proxy_hcheck_req");
+ }
+ else {
+ apr_pool_clear(wctx->req_pool);
+ }
+ create_hcheck_req(wctx, hc, wctx->req_pool);
}
return hc;
}
@@ -1014,6 +1030,7 @@ static apr_status_t hc_watchdog_callback(int state, void *data,
now = apr_time_now();
balancer = (proxy_balancer *)conf->balancers->elts;
for (i = 0; i < conf->balancers->nelts; i++, balancer++) {
+ PROXY_THREAD_LOCK(balancer);
workers = (proxy_worker **)balancer->workers->elts;
for (n = 0; n < balancer->workers->nelts; n++, workers++) {
worker = *workers;
@@ -1021,6 +1038,7 @@ static apr_status_t hc_watchdog_callback(int state, void *data,
worker->s->updated = now;
}
}
+ PROXY_THREAD_UNLOCK(balancer);
}
#if HC_USE_THREADS
if (tpsize && hctp == NULL) {
@@ -1050,12 +1068,22 @@ static apr_status_t hc_watchdog_callback(int state, void *data,
{
balancer = (proxy_balancer *)conf->balancers->elts;
for (i = 0; i < conf->balancers->nelts; i++, balancer++) {
- /* Have any new balancers or workers been added dynamically? */
+ apr_array_header_t *members;
+
+ /* Have any new balancers or workers been added dynamically?
+ * Request threads add them too (under this lock), growing
+ * the array and possibly moving it, so look at the list
+ * only with the lock held and work from a copy of it; a
+ * check can take long and must not hold the lock.
+ */
+ PROXY_THREAD_LOCK(balancer);
ap_proxy_sync_balancer(balancer, s, conf);
+ members = apr_array_copy(pool, balancer->workers);
+ PROXY_THREAD_UNLOCK(balancer);
now = apr_time_now();
- workers = (proxy_worker **)balancer->workers->elts;
- for (n = 0; n < balancer->workers->nelts; n++, workers++) {
+ workers = (proxy_worker **)members->elts;
+ for (n = 0; n < members->nelts; n++, workers++) {
worker = *workers;
if (!PROXY_WORKER_IS(worker, PROXY_WORKER_STOPPED) &&
(worker->s->method != NONE) &&
diff --git a/modules/proxy/proxy_util.c b/modules/proxy/proxy_util.c
index 81b7de2a695..7461b6aa16c 100644
--- a/modules/proxy/proxy_util.c
+++ b/modules/proxy/proxy_util.c
@@ -73,7 +73,43 @@ static int lb_workers_limit = 0;
const apr_strmatch_pattern PROXY_DECLARE_DATA *ap_proxy_strmatch_path;
const apr_strmatch_pattern PROXY_DECLARE_DATA *ap_proxy_strmatch_domain;
-extern apr_global_mutex_t *proxy_mutex;
+#if APR_HAS_THREADS
+/* Serializes, within a process, the definition, initialization and sync of
+ * the run-time workers. Those are per-process data (the workers and
+ * balancers, and the pools they are allocated from), so it is a thread
+ * mutex, created at post_config for each child to inherit unlocked.
+ */
+static apr_thread_mutex_t *proxy_mutex = NULL;
+
+static APR_INLINE void proxy_mutex_lock(void)
+{
+ apr_thread_mutex_lock(proxy_mutex);
+}
+
+static APR_INLINE void proxy_mutex_unlock(void)
+{
+ apr_thread_mutex_unlock(proxy_mutex);
+}
+#else
+#define proxy_mutex_lock() ((void)0)
+#define proxy_mutex_unlock() ((void)0)
+#endif
+
+int proxy_util_post_config(apr_pool_t *pconf, apr_pool_t *plog,
+ apr_pool_t *ptemp, server_rec *main_s)
+{
+#if APR_HAS_THREADS
+ apr_status_t rv = apr_thread_mutex_create(&proxy_mutex,
+ APR_THREAD_MUTEX_DEFAULT,
+ pconf);
+ if (rv != APR_SUCCESS) {
+ ap_log_perror(APLOG_MARK, APLOG_CRIT, rv, plog, APLOGNO(02478)
+ "failed to create proxy mutex");
+ return HTTP_INTERNAL_SERVER_ERROR;
+ }
+#endif
+ return OK;
+}
static const apr_time_t *proxy_start_time; /* epoch for expiring addresses */
@@ -923,7 +959,7 @@ PROXY_DECLARE(const char *) ap_proxy_location_reverse_map(request_rec *r,
if (ap_proxy_valid_balancer_name((char *)real, 0) &&
(balancer = ap_proxy_get_balancer(r->pool, sconf, real, 1))) {
int n, l3 = 0;
- proxy_worker **worker = (proxy_worker **)balancer->workers->elts;
+ proxy_worker **worker;
const char *urlpart = ap_strchr_c(real + sizeof(BALANCER_PREFIX) - 1, '/');
if (urlpart) {
if (!urlpart[1])
@@ -935,7 +971,14 @@ PROXY_DECLARE(const char *) ap_proxy_location_reverse_map(request_rec *r,
* BalancerMember balancer://alias http://example.com/foo
* ProxyPassReverse /bash balancer://alias/bar
* translate url http://example.com/foo/bar/that to /bash/that
+ *
+ * The workers array grows at run time (balancer-manager, sync of
+ * the workers other children added) under the balancer's thread
+ * lock: walk it under that lock, unless no worker can be added.
*/
+ u = NULL;
+ PROXY_WORKERS_LOCK(balancer);
+ worker = (proxy_worker **)balancer->workers->elts;
for (n = 0; n < balancer->workers->nelts; n++) {
l2 = strlen((*worker)->s->name_ex);
if (urlpart) {
@@ -947,7 +990,7 @@ PROXY_DECLARE(const char *) ap_proxy_location_reverse_map(request_rec *r,
&& strncmp(urlpart, url + l2, l3) == 0) {
u = apr_pstrcat(r->pool, ent[i].fake, &url[l2 + l3],
NULL);
- return ap_is_url(u) ? u : ap_construct_url(r->pool, u, r);
+ break;
}
}
else if (l1 >= l2 && strncasecmp((*worker)->s->name_ex, url, l2) == 0) {
@@ -957,10 +1000,14 @@ PROXY_DECLARE(const char *) ap_proxy_location_reverse_map(request_rec *r,
} else {
u = apr_pstrcat(r->pool, ent[i].fake, &url[l2], NULL);
}
- return ap_is_url(u) ? u : ap_construct_url(r->pool, u, r);
+ break;
}
worker++;
}
+ PROXY_WORKERS_UNLOCK(balancer);
+ if (u) {
+ return ap_is_url(u) ? u : ap_construct_url(r->pool, u, r);
+ }
}
else {
const char *part = url;
@@ -1331,9 +1378,7 @@ PROXY_DECLARE(apr_status_t) ap_proxy_share_balancer(proxy_balancer *balancer,
PROXY_DECLARE(apr_status_t) ap_proxy_initialize_balancer(proxy_balancer *balancer, server_rec *s, apr_pool_t *p)
{
-#if APR_HAS_THREADS
apr_status_t rv = APR_SUCCESS;
-#endif
ap_slotmem_provider_t *storage = balancer->storage;
apr_size_t size;
unsigned int num;
@@ -1955,6 +2000,20 @@ PROXY_DECLARE(proxy_worker *) ap_proxy_get_worker(apr_pool_t *p,
return ap_proxy_get_worker_ex(p, balancer, conf, url, 0);
}
+PROXY_DECLARE(const apr_array_header_t *) ap_proxy_balancer_snap_workers(proxy_balancer *balancer,
+ apr_pool_t *p)
+{
+ apr_array_header_t *workers;
+
+ if (balancer->ungrowable) {
+ return balancer->workers;
+ }
+ PROXY_THREAD_LOCK(balancer);
+ workers = apr_array_copy(p, balancer->workers);
+ PROXY_THREAD_UNLOCK(balancer);
+ return workers;
+}
+
/*
* To create a worker from scratch first we define the
* specifics of the worker; this is all local data.
@@ -1962,12 +2021,9 @@ PROXY_DECLARE(proxy_worker *) ap_proxy_get_worker(apr_pool_t *p,
* shared. This allows for dynamic addition during
* config and runtime.
*/
-PROXY_DECLARE(char *) ap_proxy_define_worker_ex(apr_pool_t *p,
- proxy_worker **worker,
- proxy_balancer *balancer,
- proxy_server_conf *conf,
- const char *url,
- unsigned int mask)
+static char *define_worker(apr_pool_t *p, proxy_worker **worker,
+ proxy_balancer *balancer, proxy_server_conf *conf,
+ const char *url, unsigned int mask)
{
apr_status_t rv;
proxy_worker_shared *wshared;
@@ -2074,31 +2130,18 @@ PROXY_DECLARE(char *) ap_proxy_define_worker_ex(apr_pool_t *p,
}
ptr = apr_uri_unparse(p, &uri, APR_URI_UNP_REVEALPASSWORD);
- /*
- * Workers can be associated w/ balancers or on their
- * own; ie: the generic reverse-proxy or a worker
- * in a simple ProxyPass statement. eg:
- *
- * ProxyPass / http://www.example.com
- *
- * in which case the worker goes in the conf slot.
- */
- if (balancer) {
- proxy_worker **runtime;
- /* recall that we get a ptr to the ptr here */
- runtime = apr_array_push(balancer->workers);
- *worker = *runtime = apr_palloc(p, sizeof(proxy_worker)); /* right to left baby */
- /* we've updated the list of workers associated with
- * this balancer *locally* */
- balancer->wupdated = apr_time_now();
- } else if (conf) {
- *worker = apr_array_push(conf->workers);
- } else {
- /* we need to allocate space here */
- *worker = apr_palloc(p, sizeof(proxy_worker));
+ /* Reject names that cannot be stored before allocating anything for them:
+ * the allocation below is from p, which for runtime workers is the
+ * long-lived configuration pool, so a failed definition must not leave a
+ * proxy_worker_shared behind. (These are the same limits PROXY_STRNCPY()
+ * enforces below.) */
+ if (strlen(uri.hostname) >= PROXY_RFC1035_HOSTNAME_SIZE) {
+ return apr_psprintf(p, "worker hostname (%s) too long", uri.hostname);
}
- memset(*worker, 0, sizeof(proxy_worker));
-
+ if (sockpath && strlen(sockpath) >= PROXY_WORKER_MAX_NAME_SIZE) {
+ return apr_psprintf(p, "worker uds path (%s) too long", sockpath);
+ }
+
/* right here we just want to tuck away the worker info.
* if called during config, we don't have shm setup yet,
* so just note the info for later. */
@@ -2121,7 +2164,16 @@ PROXY_DECLARE(char *) ap_proxy_define_worker_ex(apr_pool_t *p,
ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, APLOGNO(010117)
"Alert! worker scheme (%s) too long; truncated to: %s", uri.scheme, wshared->scheme);
}
+ /*
+ * Everything that can fail is checked before the worker is added to the
+ * balancer's (or conf's) worker array below: an entry appended here and then
+ * abandoned on error would stay in the array with no shared data (->s is
+ * NULL) for every later walk of the array to trip over.
+ */
if (PROXY_STRNCPY(wshared->hostname_ex, uri.hostname) != APR_SUCCESS) {
+ if (mask & AP_PROXY_WORKER_IS_MALLOCED) {
+ free(wshared);
+ }
return apr_psprintf(p, "worker hostname (%s) too long", uri.hostname);
}
if (PROXY_STRNCPY(wshared->hostname, uri.hostname) != APR_SUCCESS) {
@@ -2170,6 +2222,9 @@ PROXY_DECLARE(char *) ap_proxy_define_worker_ex(apr_pool_t *p,
}
if (sockpath) {
if (PROXY_STRNCPY(wshared->uds_path, sockpath) != APR_SUCCESS) {
+ if (mask & AP_PROXY_WORKER_IS_MALLOCED) {
+ free(wshared);
+ }
return apr_psprintf(p, "worker uds path (%s) too long", sockpath);
}
@@ -2177,6 +2232,26 @@ PROXY_DECLARE(char *) ap_proxy_define_worker_ex(apr_pool_t *p,
else {
*wshared->uds_path = '\0';
}
+
+ /*
+ * Workers can be associated w/ balancers or on their
+ * own; ie: the generic reverse-proxy or a worker
+ * in a simple ProxyPass statement. eg:
+ *
+ * ProxyPass / http://www.example.com
+ *
+ * in which case the worker goes in the conf slot.
+ */
+ if (balancer) {
+ /* Added to the balancer's array only once it is complete (below). */
+ *worker = apr_palloc(p, sizeof(proxy_worker));
+ } else if (conf) {
+ *worker = apr_array_push(conf->workers);
+ } else {
+ /* we need to allocate space here */
+ *worker = apr_palloc(p, sizeof(proxy_worker));
+ }
+ memset(*worker, 0, sizeof(proxy_worker));
if (!balancer) {
wshared->status |= PROXY_WORKER_IGNORE_ERRORS;
}
@@ -2187,9 +2262,43 @@ PROXY_DECLARE(char *) ap_proxy_define_worker_ex(apr_pool_t *p,
(*worker)->balancer = balancer;
(*worker)->s = wshared;
+ if (balancer) {
+ proxy_worker **runtime = apr_array_push(balancer->workers);
+ *runtime = *worker;
+ /* we've updated the list of workers associated with
+ * this balancer *locally* */
+ balancer->wupdated = apr_time_now();
+ }
+
return NULL;
}
+PROXY_DECLARE(char *) ap_proxy_define_worker_ex(apr_pool_t *p,
+ proxy_worker **worker,
+ proxy_balancer *balancer,
+ proxy_server_conf *conf,
+ const char *url,
+ unsigned int mask)
+{
+ char *err;
+
+ /* A worker added to a balancer at run time is allocated from the main
+ * server's configuration pool, which all the balancers share (the vhosts'
+ * ones too), and the balancer's workers array grows from pconf, while the
+ * caller holds only that balancer's locks: allocate under proxy_mutex, as
+ * ap_proxy_sync_balancer() and ap_proxy_initialize_worker() do. Workers
+ * defined without a balancer or before the MPM runs don't race with
+ * those.
+ */
+ if (!balancer || ap_state_query(AP_SQ_MAIN_STATE) != AP_SQ_MS_RUN_MPM) {
+ return define_worker(p, worker, balancer, conf, url, mask);
+ }
+ proxy_mutex_lock();
+ err = define_worker(p, worker, balancer, conf, url, mask);
+ proxy_mutex_unlock();
+ return err;
+}
+
PROXY_DECLARE(char *) ap_proxy_define_worker(apr_pool_t *p,
proxy_worker **worker,
proxy_balancer *balancer,
@@ -2333,7 +2442,7 @@ PROXY_DECLARE(apr_status_t) ap_proxy_initialize_worker(proxy_worker *worker, ser
ap_proxy_worker_name(p, worker));
}
else {
- apr_global_mutex_lock(proxy_mutex);
+ proxy_mutex_lock();
/* Check again after we got the lock if we are still uninitialized */
if (!(AP_VOLATILIZE_T(unsigned int, worker->local_status) & PROXY_WORKER_INITIALIZED)) {
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(00927)
@@ -2346,7 +2455,7 @@ PROXY_DECLARE(apr_status_t) ap_proxy_initialize_worker(proxy_worker *worker, ser
if (rv != APR_SUCCESS) {
ap_log_error(APLOG_MARK, APLOG_ERR, rv, s, APLOGNO(00928)
"can not create worker thread mutex");
- apr_global_mutex_unlock(proxy_mutex);
+ proxy_mutex_unlock();
return rv;
}
}
@@ -2356,7 +2465,7 @@ PROXY_DECLARE(apr_status_t) ap_proxy_initialize_worker(proxy_worker *worker, ser
if (worker->cp == NULL) {
ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(00929)
"can not create connection pool");
- apr_global_mutex_unlock(proxy_mutex);
+ proxy_mutex_unlock();
return APR_EGENERAL;
}
@@ -2393,11 +2502,11 @@ PROXY_DECLARE(apr_status_t) ap_proxy_initialize_worker(proxy_worker *worker, ser
worker->local_status |= (PROXY_WORKER_INITIALIZED);
}
}
- apr_global_mutex_unlock(proxy_mutex);
+ proxy_mutex_unlock();
}
if (rv == APR_SUCCESS) {
- worker->s->status |= (PROXY_WORKER_INITIALIZED);
+ ap_proxy_set_wstatus(PROXY_WORKER_INITIALIZED_FLAG, 1, worker);
}
return rv;
}
@@ -2416,7 +2525,7 @@ static int ap_proxy_retry_worker(const char *proxy_function, proxy_worker *worke
if ((worker->s->status & PROXY_WORKER_IGNORE_ERRORS)
|| apr_time_now() > worker->s->error_time + worker->s->retry) {
++worker->s->retries;
- worker->s->status &= ~PROXY_WORKER_IN_ERROR;
+ ap_proxy_set_wstatus(PROXY_WORKER_IN_ERROR_FLAG, 0, worker);
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(00932)
"%s: worker for (%s:%d) has been marked for retry",
proxy_function, worker->s->hostname_ex,
@@ -4034,7 +4143,7 @@ PROXY_DECLARE(int) ap_proxy_connect_backend(const char *proxy_function,
if (rv != APR_SUCCESS) {
if (!(worker->s->status & PROXY_WORKER_IGNORE_ERRORS)) {
worker->s->error_time = apr_time_now();
- worker->s->status |= PROXY_WORKER_IN_ERROR;
+ ap_proxy_set_wstatus(PROXY_WORKER_IN_ERROR_FLAG, 1, worker);
ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(00959)
"ap_proxy_connect_backend disabling worker for (%s:%d) "
"for %" APR_TIME_T_FMT "s",
@@ -4321,15 +4430,23 @@ ap_proxy_hashfunc(const char *str, proxy_hash_t method)
PROXY_DECLARE(apr_status_t) ap_proxy_set_wstatus(char c, int set, proxy_worker *w)
{
- unsigned int *status = &w->s->status;
+ volatile apr_uint32_t *status = (volatile apr_uint32_t *)&w->s->status;
char flag = toupper(c);
proxy_wstat_t *pwt = proxy_wstat_tbl;
while (pwt->bit) {
if (flag == pwt->flag) {
- if (set)
- *status |= pwt->bit;
- else
- *status &= ~(pwt->bit);
+ /*
+ * The status word is shared by every process and thread, and is
+ * changed from several places at once (balancer-manager, health
+ * checks, ...), each setting only its own bit.
+ * A plain |= / &= can lose another one's change in between its
+ * read and its write.
+ */
+ apr_uint32_t old, upd;
+ do {
+ old = *status;
+ upd = set ? (old | pwt->bit) : (old & ~(apr_uint32_t)pwt->bit);
+ } while (apr_atomic_cas32(status, upd, old) != old);
return APR_SUCCESS;
}
pwt++;
@@ -4412,11 +4529,20 @@ PROXY_DECLARE(apr_status_t) ap_proxy_sync_balancer(proxy_balancer *b, server_rec
}
if (!found) {
proxy_worker **runtime;
- /* XXX: a thread mutex is maybe enough here */
- apr_global_mutex_lock(proxy_mutex);
+ /* An ungrowable balancer's workers array is walked without its
+ * lock (PROXY_WORKERS_LOCK()), so it must never grow: refuse a
+ * worker it doesn't know rather than push it.
+ */
+ if (b->ungrowable) {
+ ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(10703)
+ "%s: not adding shm[%d] worker %s to a balancer "
+ "that can't grow", b->s->name, index, shm->name);
+ continue;
+ }
+ proxy_mutex_lock();
runtime = apr_array_push(b->workers);
*runtime = apr_pcalloc(conf->pool, sizeof(proxy_worker));
- apr_global_mutex_unlock(proxy_mutex);
+ proxy_mutex_unlock();
(*runtime)->hash = shm->hash;
(*runtime)->balancer = b;
(*runtime)->s = shm;
diff --git a/modules/proxy/proxy_util.h b/modules/proxy/proxy_util.h
index 9bae20b4502..0cb48d2ba55 100644
--- a/modules/proxy/proxy_util.h
+++ b/modules/proxy/proxy_util.h
@@ -31,6 +31,35 @@ PROXY_DECLARE(int) ap_proxy_is_domainname(struct dirconn_entry *This, apr_pool_t
PROXY_DECLARE(int) ap_proxy_is_hostname(struct dirconn_entry *This, apr_pool_t *p);
PROXY_DECLARE(int) ap_proxy_is_word(struct dirconn_entry *This, apr_pool_t *p);
+/*
+ * The workers array of a balancer that can grow changes at run time, under the
+ * balancer's thread lock (balancer_add_worker(), ap_proxy_sync_balancer()):
+ * walk it holding that lock. The array of an ungrowable balancer never
+ * changes, and is walked without it.
+ */
+#if APR_HAS_THREADS
+#define PROXY_WORKERS_LOCK(b) ((b)->ungrowable ? APR_SUCCESS : \
+ PROXY_THREAD_LOCK(b))
+#define PROXY_WORKERS_UNLOCK(b) ((b)->ungrowable ? APR_SUCCESS : \
+ PROXY_THREAD_UNLOCK(b))
+#else
+#define PROXY_WORKERS_LOCK(b) PROXY_THREAD_LOCK(b)
+#define PROXY_WORKERS_UNLOCK(b) PROXY_THREAD_UNLOCK(b)
+#endif
+
+/**
+ * The workers of a balancer to walk, for a walk that does not hold the
+ * balancer's lock throughout (e.g. one that writes the response).
+ * @param balancer the balancer
+ * @param p pool to allocate the copy from
+ * @return the balancer's workers array itself when no worker can be
+ * added to it, else a copy taken under the balancer's thread
+ * lock, not held across I/O; to be read only. The workers
+ * live as long as the configuration.
+ */
+PROXY_DECLARE(const apr_array_header_t *) ap_proxy_balancer_snap_workers(proxy_balancer *balancer,
+ apr_pool_t *p);
+
extern PROXY_DECLARE_DATA int proxy_lb_workers;
extern PROXY_DECLARE_DATA const apr_strmatch_pattern *ap_proxy_strmatch_path;
extern PROXY_DECLARE_DATA const apr_strmatch_pattern *ap_proxy_strmatch_domain;
@@ -40,6 +69,15 @@ extern PROXY_DECLARE_DATA const apr_strmatch_pattern *ap_proxy_strmatch_domain;
*/
void proxy_util_register_hooks(apr_pool_t *p);
+/**
+ * Post-config initialization of what proxy_util.c owns (e.g. the mutex
+ * serializing the definition, initialization and sync of the run-time
+ * workers in each process), called from mod_proxy's post_config hook with
+ * the same arguments.
+ */
+int proxy_util_post_config(apr_pool_t *pconf, apr_pool_t *plog,
+ apr_pool_t *ptemp, server_rec *main_s);
+
/*
* interpolate an env str in a configuration string
*
diff --git a/test/modules/proxy/env.py b/test/modules/proxy/env.py
index 3aa2870d58c..7b9e9cf86ab 100644
--- a/test/modules/proxy/env.py
+++ b/test/modules/proxy/env.py
@@ -85,8 +85,9 @@ def __init__(self, env: 'HttpdTestEnv'):
"proxy_connect", "lbmethod_byrequests", "remoteip"])
# Modules only some tests use: a build without one skips those
# tests (env.require()) instead of failing setup for the package.
- self.add_optional_modules(["proxy_hcheck", "proxy_scgi", "proxy_ajp",
- "proxy_uwsgi", "proxy_fcgi"])
+ self.add_optional_modules(["proxy_hcheck", "proxy_beacon",
+ "proxy_scgi", "proxy_ajp",
+ "proxy_uwsgi", "proxy_fcgi", "info"])
class ProxyTestEnv(HttpdTestEnv):
diff --git a/test/modules/proxy/test_09_hcheck_log_uri.py b/test/modules/proxy/test_09_hcheck_log_uri.py
index 1978ae289fb..1766196e85c 100644
--- a/test/modules/proxy/test_09_hcheck_log_uri.py
+++ b/test/modules/proxy/test_09_hcheck_log_uri.py
@@ -4,7 +4,11 @@
all in the logs (PR 66042).
"""
+import http.client
+import os
import re
+import time
+import urllib.parse
import pytest
@@ -47,3 +51,76 @@ def test_proxy_09_01_hcuri_is_logged(self, env):
# the health check's own (expected, deliberately provoked) connect
# failures against the unused backend port
env.httpd_error_log.ignore_recent(lognos=["AH00957"])
+
+
+@needs_dependency("mod_proxy_hcheck", ProxyTestEnv.has_shared_module("proxy_hcheck"),
+ reason="mod_proxy_hcheck not available")
+class TestHcheckMethodChange:
+ """The health check request of a worker is rebuilt when its method is
+ changed through the balancer-manager (in a pool cleared each time, not
+ growing): each new method is the one used from then on.
+ """
+
+ @pytest.fixture(autouse=True, scope='class')
+ @classmethod
+ def _class_scope(cls, env):
+ conf = HttpdConf(env)
+ conf.add([
+ '',
+ f' BalancerMember "http://127.0.0.1:{env.http_port}" '
+ 'hcmethod=GET hcuri=/hcu-change hcinterval=1',
+ '',
+ 'ProxyPass "/hcc/" "balancer://hcuchange/"',
+ '',
+ ' SetHandler balancer-manager',
+ ' Require all granted',
+ '',
+ ])
+ conf.install()
+ assert env.apache_restart() == 0
+
+ def _request(self, env, method, path, body=None):
+ conn = http.client.HTTPConnection("127.0.0.1", env.http_port, timeout=10)
+ try:
+ headers = {"Host": f"127.0.0.1:{env.http_port}",
+ "Referer": f"http://127.0.0.1:{env.http_port}/balancer-manager"}
+ if body is not None:
+ headers["Content-Type"] = "application/x-www-form-urlencoded"
+ conn.request(method, path, body=body, headers=headers)
+ r = conn.getresponse()
+ return r.status, r.read().decode(errors="replace")
+ finally:
+ conn.close()
+
+ def _wait_requested(self, env, method, timeout=10):
+ """Whether a health check with method is logged after the current
+ end of the access log, within timeout.
+ """
+ log = os.path.join(env.server_logs_dir, "access_log")
+ line = re.compile(rf'"{method} /+hcu-change HTTP/1\.0"')
+ start = os.path.getsize(log) if os.path.isfile(log) else 0
+ end = time.time() + timeout
+ while time.time() < end:
+ if os.path.isfile(log):
+ with open(log) as f:
+ f.seek(start)
+ if line.search(f.read()):
+ return True
+ time.sleep(0.2)
+ return False
+
+ def test_proxy_09_02_hcmethod_change(self, env):
+ assert self._wait_requested(env, "GET"), \
+ "the configured hcmethod was not used"
+ worker = f"http://127.0.0.1:{env.http_port}"
+ for method in ("HEAD", "GET", "HEAD"):
+ status, page = self._request(env, "GET", "/balancer-manager")
+ assert status == 200
+ m = re.search(r"b=hcuchange&[^\"]*?nonce=([0-9a-fA-F-]+)", page)
+ assert m, "no nonce for balancer://hcuchange"
+ body = (f"b=hcuchange&w={urllib.parse.quote(worker, safe='')}"
+ f"&nonce={m.group(1)}&w_hm={method}")
+ status, _ = self._request(env, "POST", "/balancer-manager", body)
+ assert status == 200
+ assert self._wait_requested(env, method), \
+ f"the health check did not use the new hcmethod {method}"
diff --git a/test/modules/proxy/test_12_balancer.py b/test/modules/proxy/test_12_balancer.py
new file mode 100644
index 00000000000..35ff2fd6c31
--- /dev/null
+++ b/test/modules/proxy/test_12_balancer.py
@@ -0,0 +1,677 @@
+"""The workers of balancers at run time: added through the balancer-managers,
+listed by them, by mod_status and by ProxyPassReverse, with and without a
+growth, and persisted.
+
+Each class says what it covers.
+"""
+
+import glob
+import http.client
+import os
+import re
+import threading
+import time
+import urllib.parse
+
+import pytest
+
+from pyhttpd.conf import HttpdConf
+
+NBALANCERS = 16
+NVHOSTS = 8
+NWORKERS = 100
+WALKS = ["page", "status", "reverse-map"]
+NFIXED_VHOSTS = 4
+NFIXED_WORKERS = 50
+WALK_SECS = 3
+
+
+def _worker_url(b, w):
+ return f"http://127.{b + 1}.0.{w + 1}:{20000 + w}"
+
+
+def _member_url(env, name="app"):
+ return f"http://127.0.0.1:{env.http_port}/{name}"
+
+
+class TestBalancerAddWorkers:
+ """Workers added at run time to the balancers of several vhosts at once.
+
+ A vhost with its own proxy configuration takes the main server's
+ configuration pool, from which the run-time workers of all its balancers are
+ allocated, while an add holds only its own balancer's locks: concurrent adds
+ through the balancer-managers, one client per vhost, must neither crash the
+ child nor lose or garble the workers.
+ """
+
+ @pytest.fixture(autouse=True, scope='class')
+ @classmethod
+ def _class_scope(cls, env):
+ conf = HttpdConf(env)
+ for b in range(NBALANCERS):
+ conf.start_vhost(domains=[cls._domain(env, b)], port=env.http_port)
+ conf.add([
+ f"",
+ f" ProxySet growth={NWORKERS}",
+ "",
+ f"ProxyPass /add{b} balancer://add{b}",
+ "",
+ " SetHandler balancer-manager",
+ " Require all granted",
+ "",
+ ])
+ conf.end_vhost()
+ conf.install()
+ assert env.apache_restart() == 0
+
+ @staticmethod
+ def _domain(env, b):
+ return f"baladd{b}.{env.http_tld}"
+
+ def _request(self, env, b, conn, method, path, body=None):
+ domain = self._domain(env, b)
+ headers = {"Host": domain, "Referer": f"http://{domain}/balancer-manager"}
+ if body is not None:
+ headers["Content-Type"] = "application/x-www-form-urlencoded"
+ conn.request(method, path, body=body, headers=headers)
+ r = conn.getresponse()
+ return r.status, r.read().decode(errors="replace")
+
+ def _add_workers(self, env, b, results):
+ conn = http.client.HTTPConnection("127.0.0.1", env.http_port, timeout=10)
+ try:
+ _, page = self._request(env, b, conn, "GET", "/balancer-manager")
+ m = re.search(rf"b=add{b}&[^\"]*?nonce=([0-9a-fA-F-]+)",
+ page.replace("&", "&"))
+ assert m, f"no nonce for balancer://add{b}"
+ statuses = []
+ for w in range(NWORKERS):
+ body = (f"b=add{b}&b_wyes=1&nonce={m.group(1)}&b_nwrkr="
+ + urllib.parse.quote(_worker_url(b, w), safe=""))
+ status, _ = self._request(env, b, conn, "POST", "/balancer-manager",
+ body.encode())
+ statuses.append(status)
+ results[b] = statuses
+ except Exception as e:
+ results[b] = repr(e)
+ finally:
+ conn.close()
+
+ def test_proxy_12_01_concurrent_adds(self, env):
+ results = {}
+ threads = [threading.Thread(target=self._add_workers, args=(env, b, results))
+ for b in range(NBALANCERS)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join(timeout=120)
+ for b in range(NBALANCERS):
+ assert results.get(b) == [200] * NWORKERS, \
+ f"adds to balancer://add{b} failed: {results.get(b)}"
+
+ # Each balancer lists exactly the workers added to it (a child syncs
+ # those the other children added from shm).
+ for b in range(NBALANCERS):
+ conn = http.client.HTTPConnection("127.0.0.1", env.http_port, timeout=10)
+ try:
+ status, page = self._request(env, b, conn, "GET", "/balancer-manager?xml=1")
+ finally:
+ conn.close()
+ assert status == 200
+ m = re.search(rf"balancer://add{b}(.*?)",
+ page, re.S)
+ assert m, f"balancer://add{b} not listed"
+ names = re.findall(r"\s*([^<]*)",
+ m.group(1))
+ assert sorted(names) == sorted(_worker_url(b, w) for w in range(NWORKERS)), \
+ f"balancer://add{b} lists {len(names)} workers, not the {NWORKERS} added"
+
+
+class TestBalancerVhostCopies:
+ """Workers added at run time to the vhost copies of one balancer.
+
+ A balancer of the main server that vhosts with their own proxy
+ configuration use is copied into each of them, and the copies share its
+ workers array: an add through one vhost's balancer-manager grows the array
+ that the other vhosts' balancer-managers walk at the same time, so all the
+ copies must take the same lock for it. mod_status' proxy section and
+ ProxyPassReverse walk the array too, polled during the adds.
+ """
+
+ @pytest.fixture(autouse=True, scope='class')
+ @classmethod
+ def _class_scope(cls, env):
+ conf = HttpdConf(env)
+ conf.add([
+ "",
+ f" BalancerMember {_member_url(env)}",
+ f" ProxySet growth={NWORKERS}",
+ "",
+ "ExtendedStatus On",
+ "ProxyStatus On",
+ "",
+ " SetHandler server-status",
+ " Require all granted",
+ "",
+ ])
+ for v in range(NVHOSTS):
+ conf.start_vhost(domains=[cls._domain(env, v)], port=env.http_port)
+ conf.add([
+ "ProxyPass /shared balancer://shared",
+ # /rmap/* is proxied to this vhost's /redir/*, redirected to
+ # the configured member (hit) or to no member (miss), the
+ # Location mapped by the walk of balancer://shared's workers
+ "ProxyPreserveHost On",
+ f"ProxyPass /rmap/ http://127.0.0.1:{env.http_port}/redir/",
+ "ProxyPassReverse /mapped balancer://shared/",
+ f"Redirect /redir/hit {_member_url(env)}/x",
+ "Redirect /redir/miss http://127.0.0.2:1/x",
+ "",
+ " SetHandler balancer-manager",
+ " Require all granted",
+ "",
+ ])
+ conf.end_vhost()
+ conf.install()
+ assert env.apache_restart() == 0
+
+ @staticmethod
+ def _domain(env, v):
+ return f"balcopy{v}.{env.http_tld}"
+
+ def _request(self, env, v, conn, method, path, body=None):
+ domain = self._domain(env, v)
+ headers = {"Host": domain, "Referer": f"http://{domain}/balancer-manager"}
+ if body is not None:
+ headers["Content-Type"] = "application/x-www-form-urlencoded"
+ conn.request(method, path, body=body, headers=headers)
+ r = conn.getresponse()
+ return r.status, r.read().decode(errors="replace")
+
+ def _list_workers(self, env, v, conn):
+ status, page = self._request(env, v, conn, "GET", "/balancer-manager?xml=1")
+ assert status == 200
+ m = re.search(r"balancer://shared(.*?)",
+ page, re.S)
+ assert m, f"balancer://shared not listed on vhost {v}"
+ return re.findall(r"\s*([^<]*)", m.group(1))
+
+ def _add_workers(self, env, v, results):
+ conn = http.client.HTTPConnection("127.0.0.1", env.http_port, timeout=10)
+ try:
+ _, page = self._request(env, v, conn, "GET", "/balancer-manager")
+ m = re.search(r"b=shared&[^\"]*?nonce=([0-9a-fA-F-]+)",
+ page.replace("&", "&"))
+ assert m, f"no nonce for balancer://shared on vhost {v}"
+ statuses = []
+ for w in range(NWORKERS):
+ body = (f"b=shared&b_wyes=1&nonce={m.group(1)}&b_nwrkr="
+ + urllib.parse.quote(_worker_url(v, w), safe=""))
+ status, _ = self._request(env, v, conn, "POST", "/balancer-manager",
+ body.encode())
+ statuses.append(status)
+ results[v] = statuses
+ except Exception as e:
+ results[v] = repr(e)
+ finally:
+ conn.close()
+
+ def _status_workers(self, env, v, conn):
+ status, page = self._request(env, v, conn, "GET", "/server-status?auto")
+ assert status == 200
+ m = re.search(r"^ProxyBalancer\[(\d+)\]Name: balancer://shared$", page, re.M)
+ assert m, f"balancer://shared not in the status of vhost {v}"
+ return re.findall(rf"^ProxyBalancer\[{m.group(1)}\]Worker\[\d+\]Name: (.*)$",
+ page, re.M)
+
+ def _reverse_map(self, env, v, conn, what):
+ conn.request("GET", f"/rmap/{what}", headers={"Host": self._domain(env, v)})
+ r = conn.getresponse()
+ r.read()
+ assert r.status == 302, f"/rmap/{what} on vhost {v}: {r.status}"
+ return r.getheader("Location")
+
+ def _walk(self, env, v, conn, kind):
+ if kind == "page":
+ self._list_workers(env, v, conn)
+ elif kind == "status":
+ assert _member_url(env) in self._status_workers(env, v, conn)
+ else:
+ loc = self._reverse_map(env, v, conn, "hit")
+ assert loc.endswith("/mapped/x"), f"/rmap/hit on vhost {v}: {loc}"
+ loc = self._reverse_map(env, v, conn, "miss")
+ assert loc == "http://127.0.0.2:1/x", f"/rmap/miss on vhost {v}: {loc}"
+
+ def _walk_workers(self, env, v, kind, done, results):
+ conn = http.client.HTTPConnection("127.0.0.1", env.http_port, timeout=10)
+ try:
+ while not done.is_set():
+ self._walk(env, v, conn, kind)
+ results[(v, kind)] = "ok"
+ except Exception as e:
+ results[(v, kind)] = repr(e)
+ finally:
+ conn.close()
+
+ def test_proxy_12_02_concurrent_adds_and_walks(self, env):
+ added, walked = {}, {}
+ done = threading.Event()
+ adders = [threading.Thread(target=self._add_workers, args=(env, v, added))
+ for v in range(NVHOSTS)]
+ walkers = [threading.Thread(target=self._walk_workers,
+ args=(env, v, kind, done, walked))
+ for v in range(NVHOSTS) for kind in WALKS]
+ for t in walkers + adders:
+ t.start()
+ for t in adders:
+ t.join(timeout=120)
+ done.set()
+ for t in walkers:
+ t.join(timeout=30)
+ for v in range(NVHOSTS):
+ assert added.get(v) == [200] * NWORKERS, \
+ f"adds through vhost {v} failed: {added.get(v)}"
+ for kind in WALKS:
+ assert walked.get((v, kind)) == "ok", \
+ f"{kind} walk on vhost {v} failed: {walked.get((v, kind))}"
+
+ # Each vhost lists the workers added through it, and no other than
+ # those added through the vhosts (the copies share the array).
+ everything = {_worker_url(v, w) for v in range(NVHOSTS) for w in range(NWORKERS)}
+ everything.add(_member_url(env))
+ for v in range(NVHOSTS):
+ # the balancer-manager syncs the child's workers, the status
+ # that follows on the same connection lists the same
+ conn = http.client.HTTPConnection("127.0.0.1", env.http_port, timeout=10)
+ try:
+ names = self._list_workers(env, v, conn)
+ in_status = self._status_workers(env, v, conn)
+ finally:
+ conn.close()
+ assert sorted(in_status) == sorted(names), \
+ f"vhost {v} lists other workers in its status than in its balancer-manager"
+ assert len(names) == len(set(names)), f"vhost {v} lists a worker twice"
+ assert set(names) <= everything, \
+ f"vhost {v} lists unknown workers: {sorted(set(names) - everything)[:5]}"
+ mine = {_worker_url(v, w) for w in range(NWORKERS)}
+ assert mine <= set(names), \
+ f"vhost {v} misses {len(mine - set(names))} of the workers added through it"
+
+
+def _fixed_domain(env, v):
+ return f"balfixed{v}.{env.http_tld}"
+
+
+def _vhost_lines(env, balancer, last_member):
+ # /rmap/* is proxied to the vhost's own /redir/*, redirected to the
+ # member last_member (hit) or to no member (miss), the Location mapped
+ # by the walk of the balancer's workers
+ return [
+ f"ProxyPass /{balancer} balancer://{balancer}",
+ "ProxyPreserveHost On",
+ f"ProxyPass /rmap/ http://127.0.0.1:{env.http_port}/redir/",
+ f"ProxyPassReverse /mapped balancer://{balancer}/",
+ f"Redirect /redir/hit {_member_url(env, last_member)}/x",
+ "Redirect /redir/miss http://127.0.0.2:1/x",
+ "",
+ " SetHandler balancer-manager",
+ " Require all granted",
+ "",
+ ]
+
+
+STATUS_LINES = [
+ "ExtendedStatus On",
+ "ProxyStatus On",
+ "",
+ " SetHandler server-status",
+ " Require all granted",
+ "",
+]
+
+
+class Client:
+
+ def __init__(self, env, v, balancer):
+ self.env = env
+ self.domain = _fixed_domain(env, v)
+ self.balancer = balancer
+ self.conn = http.client.HTTPConnection("127.0.0.1", env.http_port, timeout=10)
+
+ def close(self):
+ self.conn.close()
+
+ def request(self, method, path, body=None):
+ headers = {"Host": self.domain,
+ "Referer": f"http://{self.domain}/balancer-manager"}
+ if body is not None:
+ headers["Content-Type"] = "application/x-www-form-urlencoded"
+ self.conn.request(method, path, body=body, headers=headers)
+ r = self.conn.getresponse()
+ return r.status, r.getheader("Location"), r.read().decode(errors="replace")
+
+ def page_workers(self):
+ status, _, page = self.request("GET", "/balancer-manager?xml=1")
+ assert status == 200
+ m = re.search(rf"balancer://{self.balancer}(.*?)"
+ r"", page, re.S)
+ assert m, f"balancer://{self.balancer} not listed on {self.domain}"
+ return re.findall(r"\s*([^<]*)", m.group(1))
+
+ def page_statuses(self):
+ """{name: status} of the balancer's workers on the XML page."""
+ status, _, page = self.request("GET", "/balancer-manager?xml=1")
+ assert status == 200
+ m = re.search(rf"balancer://{self.balancer}"
+ r"(.*?)", page, re.S)
+ assert m, f"balancer://{self.balancer} not listed on {self.domain}"
+ return dict(re.findall(r"\s*([^<]*)"
+ r".*?"
+ r"([^<]*)",
+ m.group(1), re.S))
+
+ def status_workers(self):
+ status, _, page = self.request("GET", "/server-status?auto")
+ assert status == 200
+ m = re.search(rf"^ProxyBalancer\[(\d+)\]Name: balancer://{self.balancer}$",
+ page, re.M)
+ assert m, f"balancer://{self.balancer} not in the status of {self.domain}"
+ return re.findall(rf"^ProxyBalancer\[{m.group(1)}\]Worker\[\d+\]Name: (.*)$",
+ page, re.M)
+
+ def reverse_map(self, what):
+ status, loc, _ = self.request("GET", f"/rmap/{what}")
+ assert status == 302, f"/rmap/{what} on {self.domain}: {status}"
+ return loc
+
+ def check_walks(self, members):
+ """The page (first: it syncs the child's workers), the status and
+ ProxyPassReverse see exactly members."""
+ assert sorted(self.page_workers()) == sorted(members)
+ assert sorted(self.status_workers()) == sorted(members)
+ loc = self.reverse_map("hit")
+ assert loc.endswith("/mapped/x"), f"/rmap/hit on {self.domain}: {loc}"
+ loc = self.reverse_map("miss")
+ assert loc == "http://127.0.0.2:1/x", f"/rmap/miss on {self.domain}: {loc}"
+
+ def add_worker(self, url, flags=None):
+ _, _, page = self.request("GET", "/balancer-manager")
+ m = re.search(rf"b={self.balancer}&[^\"]*?nonce=([0-9a-fA-F-]+)",
+ page.replace("&", "&"))
+ assert m, f"no nonce for balancer://{self.balancer} on {self.domain}"
+ body = (f"b={self.balancer}&b_wyes=1&nonce={m.group(1)}&b_nwrkr="
+ + urllib.parse.quote(url, safe=""))
+ if flags is not None:
+ body += "&b_nwrkr_flags=" + urllib.parse.quote(flags, safe="")
+ status, _, _ = self.request("POST", "/balancer-manager", body.encode())
+ return status
+
+
+def _walk_loop(env, v, balancer, members, done, results, key):
+ c = Client(env, v, balancer)
+ try:
+ while not done.is_set():
+ if members is None:
+ c.page_workers()
+ c.status_workers()
+ c.reverse_map("miss")
+ else:
+ c.check_walks(members)
+ results[key] = "ok"
+ except Exception as e:
+ results[key] = repr(e)
+ finally:
+ c.close()
+
+
+class TestBalancerNoGrowth:
+ """Balancers whose workers can't change at run time.
+
+ No worker can be added to a balancer without a growth: all of its worker
+ slots hold configured workers, so its workers array is walked without the
+ lock (balancer-manager, mod_status' proxy section, ProxyPassReverse).
+ balancer://fixed has no growth, its copies are in NFIXED_VHOSTS vhosts.
+ """
+
+ MEMBERS = ["app0", "app1", "app2"]
+
+ @pytest.fixture(autouse=True, scope='class')
+ @classmethod
+ def _class_scope(cls, env):
+ conf = HttpdConf(env)
+ conf.add([""]
+ + [f" BalancerMember {_member_url(env, m)}" for m in cls.MEMBERS]
+ + [""] + STATUS_LINES)
+ for v in range(NFIXED_VHOSTS):
+ conf.start_vhost(domains=[_fixed_domain(env, v)], port=env.http_port)
+ conf.add(_vhost_lines(env, "fixed", cls.MEMBERS[-1]))
+ conf.end_vhost()
+ conf.install()
+ assert env.apache_restart() == 0
+
+ def test_proxy_12_03_walks(self, env):
+ members = [_member_url(env, m) for m in self.MEMBERS]
+ results = {}
+ done = threading.Event()
+ threads = [threading.Thread(target=_walk_loop,
+ args=(env, v, "fixed", members, done, results, (v, n)))
+ for v in range(NFIXED_VHOSTS) for n in range(4)]
+ for t in threads:
+ t.start()
+ time.sleep(WALK_SECS)
+ done.set()
+ for t in threads:
+ t.join(timeout=WALK_SECS + 30)
+ for v in range(NFIXED_VHOSTS):
+ for n in range(4):
+ assert results.get((v, n)) == "ok", \
+ f"walks on vhost {v} failed: {results.get((v, n))}"
+
+ def test_proxy_12_04_no_add(self, env):
+ members = [_member_url(env, m) for m in self.MEMBERS]
+ c = Client(env, 0, "fixed")
+ try:
+ c.add_worker(_member_url(env, "added"))
+ c.check_walks(members)
+ finally:
+ c.close()
+ env.httpd_error_log.ignore_recent(lognos=["AH10164"])
+
+
+class TestBalancerMixedGrowth:
+ """The vhost copies of a balancer share its workers array, and some
+ copies may have a growth when others have none. balancer://mixed has no
+ growth in the main server's copy, inherited by vhost 0, and a growth in
+ the copies of the other vhosts: this checks that the mixed configuration
+ works, a copy without growth listing its members and serving while the
+ other vhosts' copies add workers. It can't observe the lock."""
+
+ @pytest.fixture(autouse=True, scope='class')
+ @classmethod
+ def _class_scope(cls, env):
+ conf = HttpdConf(env)
+ conf.add(["",
+ f" BalancerMember {_member_url(env, 'app0')}",
+ ""] + STATUS_LINES)
+ for v in range(NFIXED_VHOSTS):
+ conf.start_vhost(domains=[_fixed_domain(env, v)], port=env.http_port)
+ if v:
+ conf.add(["",
+ f" ProxySet growth={NFIXED_WORKERS}",
+ ""])
+ conf.add(_vhost_lines(env, "mixed", "app0"))
+ conf.end_vhost()
+ conf.install()
+ assert env.apache_restart() == 0
+
+ def _add_workers(self, env, v, results):
+ c = Client(env, v, "mixed")
+ try:
+ results[v] = [c.add_worker(_worker_url(v, w))
+ for w in range(NFIXED_WORKERS)]
+ except Exception as e:
+ results[v] = repr(e)
+ finally:
+ c.close()
+
+ def test_proxy_12_05_walk_while_others_grow(self, env):
+ added, walked = {}, {}
+ done = threading.Event()
+ adders = [threading.Thread(target=self._add_workers, args=(env, v, added))
+ for v in range(1, NFIXED_VHOSTS)]
+ walkers = [threading.Thread(target=_walk_loop,
+ args=(env, 0, "mixed", None, done, walked, n))
+ for n in range(8)]
+ for t in walkers + adders:
+ t.start()
+ for t in adders:
+ t.join(timeout=120)
+ done.set()
+ for t in walkers:
+ t.join(timeout=30)
+ for v in range(1, NFIXED_VHOSTS):
+ assert added.get(v) == [200] * NFIXED_WORKERS, f"adds on vhost {v}: {added.get(v)}"
+ for n in range(8):
+ assert walked.get(n) == "ok", f"walk {n} on vhost 0 failed: {walked.get(n)}"
+ # A vhost lists the workers added through it (its balancer-manager
+ # syncs them from its copy's slots); the copies share one array, so
+ # it may list the others' too, in the children that added them.
+ for v in range(NFIXED_VHOSTS):
+ c = Client(env, v, "mixed")
+ try:
+ names = c.page_workers()
+ finally:
+ c.close()
+ assert len(names) == len(set(names)), f"vhost {v} lists a worker twice"
+ mine = {_member_url(env, "app0")}
+ if v:
+ mine |= {_worker_url(v, w)
+ for w in range(NFIXED_WORKERS)}
+ assert mine <= set(names), f"vhost {v} misses {len(mine - set(names))} workers"
+
+
+class TestBalancerPersist:
+ """balancer://persist with BalancerPersist: a worker added with a growth,
+ then restarts with and without the growth. The balancer's configuration
+ is in a file of its own, included, so that a graceful restart reads it
+ changed."""
+
+ @pytest.fixture(autouse=True, scope='class')
+ @classmethod
+ def _class_scope(cls, env):
+ cls._install(env, ["app0"], 1)
+ conf = HttpdConf(env)
+ conf.add(STATUS_LINES + [f"Include {cls._conf_path(env)}"])
+ conf.install()
+
+ @staticmethod
+ def _conf_path(env):
+ return os.path.join(env.gen_dir, "balancer-persist.conf")
+
+ @classmethod
+ def _install(cls, env, members, growth):
+ lines = (["BalancerPersist On", ""]
+ + [f" BalancerMember {_member_url(env, m)}" for m in members]
+ + ([f" ProxySet growth={growth}"] if growth else [])
+ + ["",
+ f"",
+ f" ServerName {_fixed_domain(env, 0)}",
+ " BalancerPersist On"]
+ + [f" {line}" for line in _vhost_lines(env, "persist", members[-1])]
+ + [""])
+ with open(cls._conf_path(env), "w") as fd:
+ fd.write("\n".join(lines) + "\n")
+
+ def _fresh_start_with_added(self, env):
+ """Start with app0 and a growth of 1, add the worker "added"."""
+ assert env.apache_stop() == 0
+ for f in glob.glob(os.path.join(env.server_dir, "logs", "slotmem-shm-*.persist")):
+ os.remove(f)
+ self._install(env, ["app0"], 1)
+ assert env.apache_restart() == 0
+ c = Client(env, 0, "persist")
+ try:
+ assert c.add_worker(_member_url(env, "added")) == 200
+ assert sorted(c.page_workers()) == sorted([_member_url(env, "app0"),
+ _member_url(env, "added")])
+ finally:
+ c.close()
+
+ def _check(self, env, members):
+ c = Client(env, 0, "persist")
+ try:
+ c.check_walks([_member_url(env, m) for m in members])
+ finally:
+ c.close()
+
+ def test_proxy_12_06_persist_no_growth_graceful(self, env):
+ # Two members and no growth: as many slots as the file restored, so
+ # the added worker's slot goes to app1.
+ self._fresh_start_with_added(env)
+ self._install(env, ["app0", "app1"], 0)
+ assert env.apache_reload() == 0
+ self._check(env, ["app0", "app1"])
+
+ def test_proxy_12_07_persist_no_growth_full_restart(self, env):
+ self._fresh_start_with_added(env)
+ self._install(env, ["app0", "app1"], 0)
+ assert env.apache_restart() == 0
+ self._check(env, ["app0", "app1"])
+ # One member and no growth: one slot, the file (two) is not restored.
+ self._install(env, ["app0"], 0)
+ assert env.apache_restart() == 0
+ self._check(env, ["app0"])
+ env.httpd_error_log.ignore_recent(lognos=["AH02551"])
+
+ def test_proxy_12_08_persist_growth_kept(self, env):
+ # The same growth: the added worker comes back from the file.
+ self._fresh_start_with_added(env)
+ assert env.apache_restart() == 0
+ added = sorted([_member_url(env, "app0"), _member_url(env, "added")])
+ c = Client(env, 0, "persist")
+ try:
+ assert sorted(c.page_workers()) == added
+ assert sorted(c.status_workers()) == added
+ finally:
+ c.close()
+
+
+class TestBalancerAddFlags:
+ """b_nwrkr_flags in a balancer-manager request: the status flags that a
+ worker can be created with are for balancer_manage()'s callers
+ (mod_proxy_beacon), the balancer-manager ignores them and creates the
+ worker disabled, without them."""
+
+ @pytest.fixture(autouse=True, scope='class')
+ @classmethod
+ def _class_scope(cls, env):
+ conf = HttpdConf(env)
+ conf.start_vhost(domains=[_fixed_domain(env, 0)], port=env.http_port)
+ conf.add(["",
+ f" BalancerMember {_member_url(env, 'app0')}",
+ " ProxySet growth=4",
+ "",
+ "ProxyPass /flags balancer://flags",
+ "",
+ " SetHandler balancer-manager",
+ " Require all granted",
+ ""])
+ conf.end_vhost()
+ conf.install()
+ assert env.apache_restart() == 0
+
+ # A URL that starts with a worker's URL matches that worker, so no name
+ # here is the prefix of another.
+ @pytest.mark.parametrize("name, flags", [("init", "O"), ("beacon", "B"),
+ ("mixed", "OBHS")])
+ def test_proxy_12_09_add_flags_ignored(self, env, name, flags):
+ url = _member_url(env, name)
+ c = Client(env, 0, "flags")
+ try:
+ assert c.add_worker(url, flags) == 200
+ status = c.page_statuses().get(url)
+ finally:
+ c.close()
+ assert status is not None, f"{url} not added"
+ assert status.split() == ["Init", "Dis"], \
+ f"{url} added with b_nwrkr_flags={flags}: status {status!r}"
diff --git a/test/modules/proxy/test_14_watchdog_pools.py b/test/modules/proxy/test_14_watchdog_pools.py
new file mode 100644
index 00000000000..6ab53c0ef94
--- /dev/null
+++ b/test/modules/proxy/test_14_watchdog_pools.py
@@ -0,0 +1,274 @@
+"""Watchdog callbacks must not allocate from pconf or the process pool at
+run time: other threads of the child use them too, without a common lock
+(balancers' workers arrays grow in pconf from mod_proxy_beacon and the
+balancer-manager), and children crashed on the corrupted pool.
+
+mod_aptest's aptest-pool-probe tells how many bytes something else took from
+either pool in its child since child_init.
+
+Nor must mod_proxy_hcheck's own pool grow when health checks are changed
+through the balancer-manager: the probe tells about that pool too.
+"""
+
+import http.client
+import re
+import time
+import urllib.parse
+
+import pytest
+
+from pyhttpd.backport import not_backported
+from pyhttpd.conf import HttpdConf
+from pyhttpd.depends import needs_dependency
+
+from .env import ProxyTestEnv
+
+# One child where the MPM has threads, so that the probes reach the
+# watchdog's; a few under prefork, which must not reach MaxRequestWorkers.
+# mpm_winnt has one child already and none of these directives.
+CONFIG = [
+ 'Define APTEST_POOL_PROBE',
+ '',
+ ' StartServers 2',
+ ' MinSpareServers 1',
+ ' MaxSpareServers 4',
+ ' MaxRequestWorkers 4',
+ '',
+ '',
+ '',
+ ' StartServers 1',
+ ' ServerLimit 1',
+ '',
+ ' ThreadsPerChild 25',
+ ' MaxRequestWorkers 25',
+ ' MinSpareThreads 1',
+ ' MaxSpareThreads 25',
+ '',
+ '',
+ '',
+ '',
+ ' SetHandler aptest-pool-probe',
+ '',
+]
+
+
+def start(env, lines):
+ conf = HttpdConf(env)
+ conf.add(CONFIG)
+ conf.add(lines)
+ conf.install()
+ pos = env.httpd_error_log.current_pos()
+ assert env.apache_restart() == 0
+ return pos
+
+
+def log_lines(env, pos):
+ with open(env.httpd_error_log.path, errors="replace") as fd:
+ fd.seek(pos)
+ return fd.readlines()
+
+
+def wait_pids(env, pos, pattern, count, timeout=15):
+ """The pids of the first count lines matching pattern."""
+ rx = re.compile(r'.*\[pid (\d+)[:\]].*' + pattern)
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ pids = [m.group(1) for m in map(rx.match, log_lines(env, pos)) if m]
+ if len(pids) >= count:
+ return pids[:count]
+ time.sleep(0.2)
+ return None
+
+
+def probe_all(env, pos, pid):
+ """{pool: bytes} something else took from each pool the probe watches in
+ child pid ("pconf", "process", and "hcheck" with mod_proxy_hcheck). Any
+ value but 0 means something did: a negative or very large one means the
+ pool moved to another block because of it."""
+ rx = re.compile(r'.*\[pid ' + pid + r'[:\]].*aptest-pool-probe: (.*)')
+ for _ in range(50):
+ r = env.curl_get(env.mkurl("http", "test1", "/pool-probe"))
+ if r.response and r.response["status"] == 501:
+ pytest.skip("APR pool debugging: allocations are not contiguous")
+ assert r.response and r.response["status"] == 200, r
+ for line in log_lines(env, pos):
+ m = rx.match(line)
+ if m:
+ return {k: int(v) for k, v
+ in re.findall(r'(\w+)=(-?\d+)', m.group(1))}
+ pytest.fail(f"no probe reached the watchdog's child, pid {pid}")
+
+
+def probe(env, pos, pid):
+ """(pconf, process) of probe_all()."""
+ deltas = probe_all(env, pos, pid)
+ return deltas["pconf"], deltas["process"]
+
+
+def measure(env, lines, pattern, count):
+ """Pool deltas in the child that logged pattern count times."""
+ if env.mpm_module == "mpm_prefork":
+ # A prefork child with watchdog threads (mod_proxy_hcheck's is always
+ # there) can crash in its exit cleanup on stop: often enough to make
+ # these tests noise.
+ pytest.skip("prefork children with watchdog threads can crash on stop")
+ pos = start(env, lines)
+ pids = wait_pids(env, pos, pattern, count)
+ assert pids, f"never logged {count} times: {pattern}"
+ assert len(set(pids)) == 1, pids
+ return probe(env, pos, pids[0])
+
+
+HCHECK_MEMBERS = 20 # past the 16 buckets a hash starts with: it grows
+
+
+@needs_dependency("mod_proxy_hcheck", ProxyTestEnv.has_shared_module("proxy_hcheck"),
+ reason="mod_proxy_hcheck not available")
+class TestHcheckPools:
+
+ @not_backported("9faada15d6", "mod_proxy_hcheck allocating from pconf at run time",
+ backported_in="2.4.72")
+ def test_proxy_14_01_hcheck(self, env):
+ lines = ['LogLevel proxy_hcheck:debug', '']
+ lines += [f' BalancerMember "http://127.0.0.1:{env.http_port}/m{i:02d}/" '
+ 'hcmethod=TCP hcinterval=1' for i in range(HCHECK_MEMBERS)]
+ lines += ['']
+ pconf, process = measure(env, lines, r'AH03248: Creating hc worker',
+ HCHECK_MEMBERS)
+ assert (pconf, process) == (0, 0), \
+ f"pconf {pconf}, process pool {process} bytes taken by the health checks"
+
+ def _manager(self, env, body=None):
+ conn = http.client.HTTPConnection("127.0.0.1", env.http_port, timeout=10)
+ try:
+ headers = {"Host": f"127.0.0.1:{env.http_port}",
+ "Referer": f"http://127.0.0.1:{env.http_port}/balancer-manager"}
+ if body is not None:
+ headers["Content-Type"] = "application/x-www-form-urlencoded"
+ conn.request("GET" if body is None else "POST", "/balancer-manager",
+ body=body, headers=headers)
+ r = conn.getresponse()
+ return r.status, r.read().decode(errors="replace")
+ finally:
+ conn.close()
+
+ @not_backported("gh-1133", "mod_proxy_hcheck growing its pool at each health check change",
+ backported_in="2.4.72")
+ def test_proxy_14_03_hcheck_changes(self, env):
+ # mod_proxy_hcheck's pool does not grow when the health check method
+ # or URI of a worker changes through the balancer-manager: the
+ # request rebuilt for each change goes to a pool of the worker's own.
+ if env.mpm_module == "mpm_prefork":
+ pytest.skip("prefork children with watchdog threads can crash on stop")
+ members = 4
+ changes = 2 * members # the first change of a worker, then the next
+ checking = r'Checking balancer://hcchange worker'
+ worker = f"http://127.0.0.1:{env.http_port}/c%d/"
+ lines = ['LogLevel proxy_hcheck:trace3', '']
+ lines += [f' BalancerMember "{worker % i}" '
+ 'hcmethod=GET hcuri=/hcc hcinterval=100ms'
+ for i in range(members)]
+ lines += [
+ '',
+ '',
+ ' SetHandler balancer-manager',
+ ' Require all granted',
+ '',
+ ]
+ pos = start(env, lines)
+ pids = wait_pids(env, pos, r'AH03248: Creating hc worker', members)
+ assert pids, "the hc workers were not all created"
+ assert len(set(pids)) == 1, pids
+ pid = pids[0]
+ # The watchdog logs the next check once the last hc worker is done.
+ assert wait_pids(env, env.httpd_error_log.current_pos(), checking, 1)
+ pos = env.httpd_error_log.current_pos()
+ if "hcheck" not in probe_all(env, pos, pid):
+ pytest.fail("mod_aptest's probe found no mod_proxy_hcheck pool")
+
+ # Checks alone take nothing.
+ assert wait_pids(env, env.httpd_error_log.current_pos(), checking,
+ 2 * members)
+ hcheck = probe_all(env, env.httpd_error_log.current_pos(), pid)["hcheck"]
+ assert hcheck == 0, f"{hcheck} bytes taken by the health checks"
+
+ for i in range(changes):
+ # Each change flips the worker's method too (to HEAD at its first
+ # change, back to GET at its second): 2.4.x rebuilds the request
+ # on a method change only.
+ method = 'GET' if (i // members) % 2 else 'HEAD'
+ status, page = self._manager(env)
+ assert status == 200
+ m = re.search(r"b=hcchange&[^\"]*?nonce=([0-9a-fA-F-]+)", page)
+ assert m, "no nonce for balancer://hcchange"
+ w = urllib.parse.quote(worker % (i % members), safe='')
+ body = (f"b=hcchange&w={w}&nonce={m.group(1)}&w_hu=/hcc-{i}"
+ f"&w_hm={method}")
+ pos = env.httpd_error_log.current_pos()
+ status, _ = self._manager(env, body)
+ assert status == 200
+ # Each change rebuilt on its own, not along with the next one.
+ assert wait_pids(env, pos, r'AH03311: Updating hc worker', 1), \
+ f"change {i} of the health check not applied"
+ # The watchdog logs the next check once the last rebuild is done.
+ assert wait_pids(env, env.httpd_error_log.current_pos(), checking, 1)
+ hcheck = probe_all(env, env.httpd_error_log.current_pos(), pid)["hcheck"]
+ assert hcheck == 0, \
+ f"{hcheck} bytes taken by {changes} changes of the health checks"
+
+
+@needs_dependency("mod_proxy_beacon", ProxyTestEnv.has_shared_module("proxy_beacon"),
+ reason="mod_proxy_beacon not available")
+class TestBeaconPools:
+
+ @not_backported("6e5c70b9d8", "mod_proxy_beacon allocating from the process pool",
+ backported_in="2.4.72")
+ def test_proxy_14_02_beacon_inherited_listen(self, env):
+ # No address: it is taken from the server's listener.
+ lines = [
+ 'ProxyBeaconListen',
+ 'ProxyBeaconBalancer bpool',
+ 'ProxyBeaconSecret test-pools-shared-secret',
+ '',
+ ' ProxySet growth=5',
+ '',
+ ]
+ pconf, process = measure(env, lines, r'AH10570: mod_proxy_beacon: listening', 1)
+ assert (pconf, process) == (0, 0), \
+ f"pconf {pconf}, process pool {process} bytes taken by the beacon"
+
+
+@needs_dependency("mod_proxy_hcheck", ProxyTestEnv.has_shared_module("proxy_hcheck"),
+ reason="mod_proxy_hcheck not available")
+@needs_dependency("mod_info", ProxyTestEnv.has_shared_module("info"),
+ reason="mod_info not available")
+class TestWatchdogChildInit:
+
+ @not_backported("039706610c", "mod_watchdog's child_init running before mod_proxy_balancer's")
+ def test_proxy_14_04_balancers_before_watchdogs(self, env):
+ # mod_watchdog's child_init starts the watchdog threads, whose
+ # callbacks (mod_proxy_hcheck's, mod_proxy_beacon's) walk the
+ # balancers, hcheck's as soon as it starts: the balancers' child_init
+ # must have run first.
+ conf = HttpdConf(env)
+ conf.add([
+ '',
+ ' SetHandler server-info',
+ ' Require local',
+ '',
+ '',
+ f' BalancerMember "http://127.0.0.1:{env.http_port}/" '
+ 'hcmethod=TCP hcinterval=5',
+ '',
+ ])
+ conf.install()
+ assert env.apache_restart() == 0
+ r = env.curl_get(f"http://127.0.0.1:{env.http_port}/server-info?hooks")
+ assert r.response and r.response["status"] == 200, r
+ body = r.response["body"].decode("latin-1")
+ m = re.search(r"Child Init:(.*?)", body, re.S)
+ assert m, "no Child Init hooks in /server-info?hooks"
+ order = re.findall(r'href="\?([^"]+\.c)"', m.group(1))
+ assert "mod_watchdog.c" in order and "mod_proxy_balancer.c" in order, order
+ assert order.index("mod_proxy_balancer.c") < order.index("mod_watchdog.c"), \
+ f"watchdogs start before the balancers are initialized: {order}"
diff --git a/test/pyhttpd/classic_errorlog.py b/test/pyhttpd/classic_errorlog.py
index 8e9c88c01d3..03c82e56f85 100644
--- a/test/pyhttpd/classic_errorlog.py
+++ b/test/pyhttpd/classic_errorlog.py
@@ -86,7 +86,7 @@
"test_proxy.py": (["AH02229"], []),
"test_proxy_balancer.py": ([
"AH00957", "AH00959", "AH01114", "AH01170", "AH01171", "AH10187"], []),
- "test_proxy_beacon.py": (["AH01170"], []),
+ "test_proxy_beacon.py": (["AH01170", "AH01171"], []),
"test_proxy_beacon_input.py": (["AH10187"], []),
"test_proxy_hcheck.py": (["AH10187"], []),
"test_remoteip.py": (["AH03499"], []),
diff --git a/test/pyhttpd/mod_aptest/mod_aptest.c b/test/pyhttpd/mod_aptest/mod_aptest.c
index 8567abf2311..4410d750332 100644
--- a/test/pyhttpd/mod_aptest/mod_aptest.c
+++ b/test/pyhttpd/mod_aptest/mod_aptest.c
@@ -20,6 +20,7 @@
#include
#include
+#include
#include
#include
#include
@@ -129,10 +130,107 @@ static int aptest_getline_echo(request_rec *r)
return OK;
}
+/*
+ * Handler "aptest-pool-probe": return how many bytes something else took
+ * from the process pool since mod_watchdog started its threads in this
+ * child, and from pconf since the end of child_init (other modules' own
+ * child_init legitimately use it), or since the last probe. A pool moving
+ * to another block shows as a negative or very large value. The probe
+ * uses both pools without a lock, so it must not run where others use them:
+ * it is only set up when the config has "Define APTEST_POOL_PROBE".
+ *
+ * A mark is a zero-size allocation, which takes nothing (but under valgrind):
+ * a real one moves the pool on to another block when its block is full.
+ *
+ * With mod_proxy_hcheck loaded, it also tells how many bytes were taken from
+ * the main server's own pool of mod_proxy_hcheck (where its watchdog creates
+ * the health check workers) since mod_watchdog started its threads, or since
+ * the last probe.
+ */
+#if !APR_POOL_DEBUG
+static char *pconf_mark, *process_mark, *hcheck_mark;
+static apr_pool_t *hcheck_pool;
+
+static void aptest_child_init_process(apr_pool_t *pchild, server_rec *s)
+{
+ if (ap_exists_config_define("APTEST_POOL_PROBE")) {
+ module *m = ap_find_linked_module("mod_proxy_hcheck.c");
+
+ process_mark = apr_palloc(s->process->pool, 0);
+ if (m) {
+ /* The pool is the first member of mod_proxy_hcheck's server
+ * config.
+ */
+ void *ctx = ap_get_module_config(s->module_config, m);
+
+ hcheck_pool = *(apr_pool_t **)ctx;
+ hcheck_mark = apr_palloc(hcheck_pool, 0);
+ }
+ }
+}
+
+static void aptest_child_init_pconf(apr_pool_t *pchild, server_rec *s)
+{
+ if (ap_exists_config_define("APTEST_POOL_PROBE")) {
+ pconf_mark = apr_palloc(s->process->pconf, 0);
+ }
+}
+
+static apr_int64_t aptest_pool_delta(apr_pool_t *p, char **last)
+{
+ char *mark = apr_palloc(p, 0);
+ apr_int64_t delta = (apr_int64_t)(apr_uintptr_t)mark
+ - (apr_int64_t)(apr_uintptr_t)*last;
+
+ *last = mark;
+ return delta;
+}
+#endif
+
+static int aptest_pool_probe(request_rec *r)
+{
+#if !APR_POOL_DEBUG
+ apr_int64_t pconf, process;
+ char hcheck[32] = "";
+#endif
+
+ if (strcmp(r->handler, "aptest-pool-probe")) {
+ return DECLINED;
+ }
+#if APR_POOL_DEBUG
+ /* Every allocation is a separate block: nothing to measure. */
+ return HTTP_NOT_IMPLEMENTED;
+#else
+ if (!pconf_mark || !process_mark) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
+ "aptest-pool-probe: no Define APTEST_POOL_PROBE");
+ return HTTP_INTERNAL_SERVER_ERROR;
+ }
+ pconf = aptest_pool_delta(r->server->process->pconf, &pconf_mark);
+ process = aptest_pool_delta(r->server->process->pool, &process_mark);
+ if (hcheck_pool) {
+ apr_snprintf(hcheck, sizeof hcheck, " hcheck=%" APR_INT64_T_FMT,
+ aptest_pool_delta(hcheck_pool, &hcheck_mark));
+ }
+ ap_log_rerror(APLOG_MARK, APLOG_NOTICE, 0, r,
+ "aptest-pool-probe: pconf=%" APR_INT64_T_FMT
+ " process=%" APR_INT64_T_FMT "%s", pconf, process, hcheck);
+ ap_set_content_type(r, "text/plain");
+ ap_rprintf(r, "pconf=%" APR_INT64_T_FMT " process=%" APR_INT64_T_FMT
+ "%s\n", pconf, process, hcheck);
+ return OK;
+#endif
+}
+
/* Install this module into the apache2 infrastructure.
*/
static void aptest_hooks(apr_pool_t *pool)
{
+#if !APR_POOL_DEBUG
+ /* The watchdog threads start in mod_watchdog's child_init. */
+ static const char * const before_watchdog[] = { "mod_watchdog.c", NULL };
+#endif
+
ap_log_perror(APLOG_MARK, APLOG_TRACE1, 0, pool,
"installing hooks and handlers");
@@ -141,6 +239,13 @@ static void aptest_hooks(apr_pool_t *pool)
NULL, APR_HOOK_MIDDLE);
ap_hook_fixups(aptest_allow_methods, NULL, NULL, APR_HOOK_MIDDLE);
ap_hook_handler(aptest_getline_echo, NULL, NULL, APR_HOOK_MIDDLE);
+#if !APR_POOL_DEBUG
+ ap_hook_child_init(aptest_child_init_process, NULL, before_watchdog,
+ APR_HOOK_REALLY_LAST);
+ ap_hook_child_init(aptest_child_init_pconf, NULL, NULL,
+ APR_HOOK_REALLY_LAST);
+#endif
+ ap_hook_handler(aptest_pool_probe, NULL, NULL, APR_HOOK_MIDDLE);
}
|