From 0a74347ae40ea4fdee4bde101f8c0bae51787272 Mon Sep 17 00:00:00 2001 From: ylavic Date: Mon, 30 Nov 2026 11:27:53 +0100 Subject: [PATCH 1/3] mod_proxy_hcheck: don't grow memory when a worker's health check changes. Each change of a worker's health check method or URI through the balancer-manager rebuilt its pre-formatted request in the module's pool, never freeing the previous one until the next restart. Keep the request in a pool of the health check worker's own, cleared when the request is rebuilt; no check of the worker runs then (the watchdog starts the next one only once the previous one is done). * modules/proxy/mod_proxy_hcheck.c: (wctx_t): Add req_pool. (create_hcheck_req): Clear and use it, rather than taking a pool. (hc_get_hcworker): Create it. * test/modules/proxy/test_09_hcheck_log_uri.py: (TestHcheckMethodChange): New test, the new method is used after each change through the balancer-manager. * changes-entries/proxy-hcheck-req-pool.txt: New. --- changes-entries/proxy-hcheck-req-pool.txt | 3 + modules/proxy/mod_proxy_hcheck.c | 16 +++- test/modules/proxy/test_09_hcheck_log_uri.py | 77 ++++++++++++++++++++ 3 files changed, 92 insertions(+), 4 deletions(-) create mode 100644 changes-entries/proxy-hcheck-req-pool.txt diff --git a/changes-entries/proxy-hcheck-req-pool.txt b/changes-entries/proxy-hcheck-req-pool.txt new file mode 100644 index 00000000000..ed002125a60 --- /dev/null +++ b/changes-entries/proxy-hcheck-req-pool.txt @@ -0,0 +1,3 @@ + *) mod_proxy_hcheck: Don't grow memory each time the health check method + or URI of a worker is changed through the balancer-manager. + [Yann Ylavic] diff --git a/modules/proxy/mod_proxy_hcheck.c b/modules/proxy/mod_proxy_hcheck.c index 18ab0bceb64..238a515cc84 100644 --- a/modules/proxy/mod_proxy_hcheck.c +++ b/modules/proxy/mod_proxy_hcheck.c @@ -76,6 +76,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, cleared when it's rebuilt */ } wctx_t; typedef struct { @@ -454,13 +455,18 @@ static void set_request_connection(request_rec *r, conn_rec *conn) r->useragent_ip = conn->client_ip; } -static void create_hcheck_req(wctx_t *wctx, proxy_worker *hc, - apr_pool_t *p) +/* (Re)build the request in wctx->req_pool, cleared first: not while a check + * of the worker runs (the watchdog starts none before the last one is done). + */ +static void create_hcheck_req(wctx_t *wctx, proxy_worker *hc) { + apr_pool_t *p = wctx->req_pool; char *req = NULL; const char *method = NULL; const char *protocol = NULL; + apr_pool_clear(p); + /* TODO: Fold into switch/case below? This seems more obvious */ if ( (hc->s->method == OPTIONS11) || (hc->s->method == HEAD11) || (hc->s->method == GET11) ) { protocol = "HTTP/1.1"; @@ -578,7 +584,9 @@ static proxy_worker *hc_get_hcworker(sctx_t *ctx, proxy_worker *worker, wctx->path = apr_pstrdup(ctx->p, uri.path); } wctx->w = worker; - create_hcheck_req(wctx, hc, ctx->p); + apr_pool_create(&wctx->req_pool, ctx->p); + apr_pool_tag(wctx->req_pool, "proxy_hcheck_req"); + create_hcheck_req(wctx, hc); hc->context = wctx; /* apr_hash_set() keeps the key pointer as is, not a copy of the key, * so it must outlive the hash: not the address of our argument. */ @@ -599,7 +607,7 @@ static proxy_worker *hc_get_hcworker(sctx_t *ctx, proxy_worker *worker, (int)port); hc->s->method = worker->s->method; PROXY_STRNCPY(hc->s->hcuri, worker->s->hcuri); - create_hcheck_req(wctx, hc, ctx->p); + create_hcheck_req(wctx, hc); } return hc; } diff --git a/test/modules/proxy/test_09_hcheck_log_uri.py b/test/modules/proxy/test_09_hcheck_log_uri.py index 0562a200d0c..71ed8847303 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 @@ -48,3 +52,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}" From e7ea277380c4aa301a22265cd1cc547ff8057bfe Mon Sep 17 00:00:00 2001 From: ylavic Date: Mon, 30 Nov 2026 12:43:15 +0100 Subject: [PATCH 2/3] mod_proxy_hcheck: create the request's pool at the worker's first change only. A pool costs at least 8KB, for each health check worker while most never change. Build the initial request in the module's pool as before, and create the worker's request pool when its method or URI first changes, clearing it at the next changes. * modules/proxy/mod_proxy_hcheck.c: (wctx_t): Update req_pool's comment. (create_hcheck_req): Take the pool again. (hc_get_hcworker): Create req_pool at the first change, clear it at the next ones. --- modules/proxy/mod_proxy_hcheck.c | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/modules/proxy/mod_proxy_hcheck.c b/modules/proxy/mod_proxy_hcheck.c index 238a515cc84..c9598837060 100644 --- a/modules/proxy/mod_proxy_hcheck.c +++ b/modules/proxy/mod_proxy_hcheck.c @@ -76,7 +76,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, cleared when it's rebuilt */ + apr_pool_t *req_pool; /* For req once rebuilt, cleared when rebuilt again */ } wctx_t; typedef struct { @@ -455,18 +455,13 @@ static void set_request_connection(request_rec *r, conn_rec *conn) r->useragent_ip = conn->client_ip; } -/* (Re)build the request in wctx->req_pool, cleared first: not while a check - * of the worker runs (the watchdog starts none before the last one is done). - */ -static void create_hcheck_req(wctx_t *wctx, proxy_worker *hc) +static void create_hcheck_req(wctx_t *wctx, proxy_worker *hc, + apr_pool_t *p) { - apr_pool_t *p = wctx->req_pool; char *req = NULL; const char *method = NULL; const char *protocol = NULL; - apr_pool_clear(p); - /* TODO: Fold into switch/case below? This seems more obvious */ if ( (hc->s->method == OPTIONS11) || (hc->s->method == HEAD11) || (hc->s->method == GET11) ) { protocol = "HTTP/1.1"; @@ -584,9 +579,7 @@ static proxy_worker *hc_get_hcworker(sctx_t *ctx, proxy_worker *worker, wctx->path = apr_pstrdup(ctx->p, uri.path); } wctx->w = worker; - apr_pool_create(&wctx->req_pool, ctx->p); - apr_pool_tag(wctx->req_pool, "proxy_hcheck_req"); - create_hcheck_req(wctx, hc); + create_hcheck_req(wctx, hc, ctx->p); hc->context = wctx; /* apr_hash_set() keeps the key pointer as is, not a copy of the key, * so it must outlive the hash: not the address of our argument. */ @@ -607,7 +600,20 @@ static proxy_worker *hc_get_hcworker(sctx_t *ctx, proxy_worker *worker, (int)port); hc->s->method = worker->s->method; PROXY_STRNCPY(hc->s->hcuri, worker->s->hcuri); - create_hcheck_req(wctx, hc); + /* 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; } From 1a16e694da1b7a92a19375a604135338e4cfd9b7 Mon Sep 17 00:00:00 2001 From: ylavic Date: Mon, 30 Nov 2026 14:04:40 +0100 Subject: [PATCH 3/3] test: check that mod_proxy_hcheck's pool doesn't grow with health check changes mod_aptest's pool probe also tells how many bytes were taken from the main server's pool of mod_proxy_hcheck, which must not grow when a worker's health check method or URI is changed through the balancer-manager. * test/pyhttpd/mod_aptest/mod_aptest.c: (aptest_child_init_process): Mark mod_proxy_hcheck's pool when loaded. (aptest_pool_probe): Add its delta as "hcheck=". * modules/proxy/mod_proxy_hcheck.c: (sctx_t): Say that p stays first, mod_aptest reads it. * test/modules/proxy/test_14_watchdog_pools.py: (probe_all): New, every pool's delta, from probe(). (TestHcheckPools.test_proxy_14_03_hcheck_changes): New test, neither the checks nor changes of each worker's method and URI grow the pool. --- modules/proxy/mod_proxy_hcheck.c | 2 +- test/modules/proxy/test_14_watchdog_pools.py | 99 ++++++++++++++++++-- test/pyhttpd/mod_aptest/mod_aptest.c | 30 +++++- 3 files changed, 119 insertions(+), 12 deletions(-) diff --git a/modules/proxy/mod_proxy_hcheck.c b/modules/proxy/mod_proxy_hcheck.c index c9598837060..2ef8f3a44ee 100644 --- a/modules/proxy/mod_proxy_hcheck.c +++ b/modules/proxy/mod_proxy_hcheck.c @@ -62,7 +62,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; diff --git a/test/modules/proxy/test_14_watchdog_pools.py b/test/modules/proxy/test_14_watchdog_pools.py index fbff52bba34..6f3d5810127 100644 --- a/test/modules/proxy/test_14_watchdog_pools.py +++ b/test/modules/proxy/test_14_watchdog_pools.py @@ -5,10 +5,15 @@ 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 @@ -75,12 +80,12 @@ def wait_pids(env, pos, pattern, count, timeout=15): return None -def probe(env, pos, pid): - """(pconf, process): bytes something else took from either pool in child - pid. 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: ' - r'pconf=(-?\d+) process=(-?\d+)') +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: @@ -89,10 +94,17 @@ def probe(env, pos, pid): for line in log_lines(env, pos): m = rx.match(line) if m: - return tuple(int(v) for v in m.groups()) + 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": @@ -125,6 +137,79 @@ def test_proxy_14_01_hcheck(self, env): 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") + 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): + 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={'HEAD' if i % 2 else 'GET'}") + 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") diff --git a/test/pyhttpd/mod_aptest/mod_aptest.c b/test/pyhttpd/mod_aptest/mod_aptest.c index 68ccb9c2311..4410d750332 100644 --- a/test/pyhttpd/mod_aptest/mod_aptest.c +++ b/test/pyhttpd/mod_aptest/mod_aptest.c @@ -141,14 +141,31 @@ static int aptest_getline_echo(request_rec *r) * * 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; +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); + } } } @@ -174,6 +191,7 @@ 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")) { @@ -190,12 +208,16 @@ static int aptest_pool_probe(request_rec *r) } 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, pconf, process); + " 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 "\n", - pconf, process); + ap_rprintf(r, "pconf=%" APR_INT64_T_FMT " process=%" APR_INT64_T_FMT + "%s\n", pconf, process, hcheck); return OK; #endif }