Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions changes-entries/proxy-hcheck-req-pool.txt
Original file line number Diff line number Diff line change
@@ -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]
18 changes: 16 additions & 2 deletions modules/proxy/mod_proxy_hcheck.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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 once rebuilt, cleared when rebuilt again */
} wctx_t;

typedef struct {
Expand Down Expand Up @@ -599,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, 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;
}
Expand Down
77 changes: 77 additions & 0 deletions test/modules/proxy/test_09_hcheck_log_uri.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@
all in the logs (PR 66042).
"""

import http.client
import os
import re
import time
import urllib.parse

import pytest

Expand Down Expand Up @@ -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([
'<Proxy "balancer://hcuchange">',
f' BalancerMember "http://127.0.0.1:{env.http_port}" '
'hcmethod=GET hcuri=/hcu-change hcinterval=1',
'</Proxy>',
'ProxyPass "/hcc/" "balancer://hcuchange/"',
'<Location /balancer-manager>',
' SetHandler balancer-manager',
' Require all granted',
'</Location>',
])
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}"
99 changes: 92 additions & 7 deletions test/modules/proxy/test_14_watchdog_pools.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand All @@ -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":
Expand Down Expand Up @@ -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', '<Proxy "balancer://hcchange">']
lines += [f' BalancerMember "{worker % i}" '
'hcmethod=GET hcuri=/hcc hcinterval=100ms'
for i in range(members)]
lines += [
'</Proxy>',
'<Location /balancer-manager>',
' SetHandler balancer-manager',
' Require all granted',
'</Location>',
]
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")
Expand Down
30 changes: 26 additions & 4 deletions test/pyhttpd/mod_aptest/mod_aptest.c
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
}

Expand All @@ -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")) {
Expand All @@ -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
}
Expand Down
Loading