Reconcile exporters during regular monitoring runs and refresh timer

This commit is contained in:
juvenal.diaz 2026-12-03 08:18:38 -06:00
parent e51d13006a
commit f13ea0f6d1
6 changed files with 191 additions and 46 deletions

View File

@ -57,8 +57,11 @@ The migration does not repair the Orange Pi SSD or migrate Loki. A down Loki
target remains a real failure, rather than being hidden by this move. Original
PVCs and backups should be retained until recovery requirements are reviewed.
`./jeannie monitoring exporters` repairs and validates the Debian and OCI email
node-exporter targets. On Debian it removes only retired CNI TCP/9100 hostPort
`./jeannie monitoring apply`, `migrate` and `refresh` automatically check and
repair the Debian and OCI email node-exporter targets. The five-minute refresh
timer uses the same installed code, independent of the source checkout.
`./jeannie platform monitoring` also invokes this reconciliation.
`./jeannie monitoring exporters` remains an optional focused retry. On Debian it removes only retired CNI TCP/9100 hostPort
rules when all Kubernetes services and runtime processes are absent; shared
HTTP/HTTPS rules and other firewall policy remain intact. Rule backups are
saved under `~/.local/share/homelab/exporter-backups`.
@ -70,7 +73,10 @@ a source-restricted TCP/9100 INPUT allowance before the Oracle image's default
REJECT rule, including after reboot. It saves email-specific CIDR
overrides in the canonical OCI configuration so subsequent foundation applies
retain the new source. Existing UFW permissions are not reset or removed, and
edge access rules remain unchanged. Re-run after a home public-IP change.
The command finishes only after both exporters return metrics and Prometheus
observes both jobs UP. It needs the existing managed email rules, OCI CLI
edge access rules remain unchanged. Scheduled refresh detects public-IP changes
and repairs access automatically. When targets are already UP and the recorded
source matches, it avoids SSH, OCI updates and service changes. A disabled
email VM is skipped. Status and validation commands remain read-only.
Reconciliation finishes only after Prometheus observes the expected jobs UP;
exporter failures fail the monitoring run and are visible in the timer journal. It needs the existing managed email rules, OCI CLI
credentials, SSH key and passwordless sudo; it does not recreate either host.

View File

@ -17,47 +17,33 @@ configure_platform_grafana_sso() {
fi
}
monitoring_exporter_install() {
local root="$1"
install -m 755 "${REPO_ROOT}/scripts/monitoring-exporter-access.py" "${root}/monitoring-exporter-access.py" || return 1
install -m 755 "${REPO_ROOT}/scripts/monitoring-host-exporter.sh" "${root}/monitoring-host-exporter.sh" || return 1
install -m 644 "${REPO_ROOT}/scripts/oci-foundation-resolve.py" "${root}/oci-foundation-resolve.py" || return 1
# The canonical name allowlist is declared in commands.sh before dispatch.
# shellcheck disable=SC2154
MONITORING_OCI_CLI="${OCI_CLI_BIN:-${HOME}/.local/share/homelab/venvs/oci-cli/bin/oci}" \
MONITORING_EMAIL_KEY="${LAB_EMAIL_SSH_PRIVATE_KEY:-${HOME}/.ssh/id_ed25519}" \
MONITORING_EMAIL_USER="${LAB_EMAIL_SSH_USER:-ubuntu}" \
python3 - "${root}" "$(oci_foundation_config_file)" "${oci_foundation_config_names[@]}" <<'PYEXPORT'
import json, os, pathlib, sys
path = pathlib.Path(sys.argv[1]) / 'exporter-settings.json'
settings = dict(config=sys.argv[2], names=sys.argv[3:], cli=os.environ['MONITORING_OCI_CLI'],
ssh_key=os.environ['MONITORING_EMAIL_KEY'], ssh_user=os.environ['MONITORING_EMAIL_USER'])
path.write_text(json.dumps(settings, indent=2))
path.chmod(0o600)
PYEXPORT
}
monitoring_exporters() {
require_debian_server "monitoring exporters"
local foundation_lock
exec {foundation_lock}>"${REPO_ROOT}/bootstrap/oci/.jeannie-foundation.lock"
if ! flock -n "${foundation_lock}"; then
echo "Another OCI foundation operation is active; retry exporter repair after it finishes." >&2
return 1
fi
record_change_journal monitoring-exporters
bash "${REPO_ROOT}/scripts/monitoring-host-exporter.sh" || return 1
local cidr cli email_ip
cidr="$(curl --noproxy '*' -4 -fsS --connect-timeout 5 --max-time 15 https://api.ipify.org)/32" || return 1
cli="${OCI_CLI_BIN:-${HOME}/.local/share/homelab/venvs/oci-cli/bin/oci}"
python3 "${REPO_ROOT}/scripts/monitoring-exporter-access.py" email \
--state "${LAB_OCI_FOUNDATION_STATE_FILE:?OCI foundation state required}" --cidr "${cidr}" --cli "${cli}" || return 1
export LAB_OCI_EMAIL_ADMIN_CIDR="${cidr}" LAB_OCI_EMAIL_MONITORING_CIDR="${cidr}"
oci_foundation_save_config || return 1
email_ip="${LAB_EMAIL_PUBLIC_IP:?Email VM address required}"
# Repair only monitoring access on the mail host; do not reinstall/reset mail or UFW.
ssh -T -o BatchMode=yes -o ConnectTimeout=10 -i "${LAB_EMAIL_SSH_PRIVATE_KEY:-${HOME}/.ssh/id_ed25519}" \
"${LAB_EMAIL_SSH_USER:-ubuntu}@${email_ip}" \
"temporary=\$(mktemp /tmp/jeannie-email-exporter.XXXXXX.py); trap 'rm -f \"\$temporary\"' EXIT; cat >\"\$temporary\"; sudo -n python3 \"\$temporary\" email-host --cidr '${cidr}'" \
<"${REPO_ROOT}/scripts/monitoring-exporter-access.py" || return 1
python3 - "${email_ip}" <<'PYEXPORT'
import json, sys, time, urllib.request
for host in ('127.0.0.1', sys.argv[1]):
with urllib.request.urlopen('http://' + host + ':9100/metrics', timeout=10) as response:
if b'node_exporter_build_info' not in response.read():
raise SystemExit('Node exporter metrics missing for ' + host)
print('Exporter metrics verified: ' + host)
deadline = time.monotonic() + 90
while True:
targets = json.load(urllib.request.urlopen('http://127.0.0.1:19090/api/v1/targets', timeout=15))['data']['activeTargets']
selected = {t['scrapePool']: t for t in targets if t['scrapePool'] in ('debian-host', 'oci-email-node')}
if len(selected) == 2 and all(t['health'] == 'up' for t in selected.values()):
for name, target in selected.items(): print(name + ': UP ' + target['scrapeUrl'])
break
if time.monotonic() >= deadline:
raise SystemExit('Exporter HTTP works but Prometheus has not confirmed both targets UP')
time.sleep(5)
PYEXPORT
local root="${LAB_MONITORING_INSTALL_DIR:-/data/homelab-monitoring}"
sudo -n install -d -m 750 -o "$(id -un)" -g "$(id -gn)" "${root}" || return 1
monitoring_exporter_install "${root}" || return 1
flock -n "${root}/.lock" python3 "${root}/monitoring-exporter-access.py" reconcile --root "${root}"
}
monitoring_debian() {
@ -81,6 +67,7 @@ monitoring_debian() {
install -m 755 "${REPO_ROOT}/scripts/monitoring-debian.py" "${root}/manager.py" || return 1
install -m 755 "${REPO_ROOT}/scripts/monitoring-helm-postrender.py" "${root}/postrender.py" || return 1
install -m 640 "${REPO_ROOT}/infra/monitoring-debian/compose.yaml" "${root}/compose.yaml" || return 1
monitoring_exporter_install "${root}" || return 1
MONITORING_ROOT="${root}" LAB_DEBIAN_LAN_IP="${LAB_DEBIAN_LAN_IP}" \
LAB_PIMOX_HOST="${LAB_PIMOX_HOST}" LAB_PIMOX_USER="${LAB_PIMOX_USER}" \
LAB_MONITORING_SERVICE_CIDR="${LAB_MONITORING_SERVICE_CIDR:-10.43.0.0/16}" python3 - <<'PY' || return 1

View File

@ -131,6 +131,12 @@ class Monitoring:
for path, content in previous.items():
write(path, content, 0o644)
raise
if reload:
self.reconcile_exporters()
def reconcile_exporters(self):
run([sys.executable, self.root / 'monitoring-exporter-access.py', 'reconcile', '--root', self.root])
print('Expected host exporters: UP')
def _refresh(self, reload=True):
self.verify_identity()
@ -368,6 +374,8 @@ class Monitoring:
run(['sudo', '-n', 'chown', '-R', '472:472' if role == 'grafana' else '65534:65534', destination])
write(backup / (role + '.copied'), 'copied\n')
self.compose('up', '-d', '--force-recreate')
self.wait_for(self.http_ready)
self.reconcile_exporters()
self.wait_for(self.validate)
write(self.root / 'migration-complete.json', json.dumps({'volumes': volumes, 'cluster_uid': self.settings['cluster_uid']}))
self.install_timer()

View File

@ -164,12 +164,76 @@ def email(state_path, cidr, cli):
print('Managed email SSH/exporter NSG rules already match the Debian public IPv4.')
def healthy_targets():
import urllib.request
with urllib.request.urlopen('http://127.0.0.1:19090/api/v1/targets', timeout=15) as response:
return {t['scrapePool']: t for t in json.load(response)['data']['activeTargets']}
def reconcile(root):
"""Used by apply and the installed refresh timer, without a source checkout."""
import importlib.util
import time
import urllib.request
root = Path(root)
settings = json.loads((root / 'exporter-settings.json').read_text())
spec = importlib.util.spec_from_file_location('foundation', root / 'oci-foundation-resolve.py')
foundation = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foundation)
config = Path(settings['config'])
names = set(settings['names'])
run(['bash', str(root / 'monitoring-host-exporter.sh')])
with foundation.config_lock(config):
values = foundation.read_config(config, names)
enabled = values.get('LAB_OCI_EMAIL_ENABLED', 'false').lower() in ('true', '1', 'yes')
expected = {'debian-host'}
if enabled:
expected.add('oci-email-node')
with urllib.request.urlopen('https://api.ipify.org', timeout=15) as response:
cidr = public_source(response.read().decode().strip() + '/32')
state = values.get('LAB_OCI_FOUNDATION_STATE_FILE')
if not state or not Path(state).is_absolute():
raise RuntimeError('Automatic exporter repair requires an absolute canonical foundation state path')
foundation.recorded(values, foundation.read_state(Path(state)))
target = healthy_targets().get('oci-email-node', {})
unchanged = all(values.get(name) == cidr for name in
('LAB_OCI_EMAIL_ADMIN_CIDR', 'LAB_OCI_EMAIL_MONITORING_CIDR'))
# Healthy targets need checks, not repeated SSH/systemd/OCI updates.
repair_email = not (target.get('health') == 'up' and unchanged)
if repair_email:
email(state, cidr, settings['cli'])
values.update(LAB_OCI_EMAIL_ADMIN_CIDR=cidr, LAB_OCI_EMAIL_MONITORING_CIDR=cidr)
foundation.atomic_write(config, foundation.config_text({k: v for k, v in values.items() if k in names}))
email_ip = values.get('LAB_EMAIL_PUBLIC_IP')
ipaddress.IPv4Address(email_ip)
if enabled and repair_email:
command = ('temporary=$(mktemp /tmp/jeannie-email-exporter.XXXXXX.py); '
'trap \'rm -f "$temporary"\' EXIT; cat >"$temporary"; '
'sudo -n python3 "$temporary" email-host --cidr ' + shlex.quote(cidr))
key = settings['ssh_key']
user = settings['ssh_user']
subprocess.run(['ssh', '-T', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=10',
'-i', key, user + '@' + email_ip, command],
input=Path(__file__).read_bytes(), check=True, timeout=120)
deadline = time.monotonic() + 90
while True:
targets = healthy_targets()
if all(targets.get(name, {}).get('health') == 'up' for name in expected):
print('Exporter checks: ' + ', '.join(name + '=UP' for name in sorted(expected)))
return
if time.monotonic() >= deadline:
raise RuntimeError('Prometheus has not confirmed expected exporter targets UP')
time.sleep(5)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=['host', 'email', 'email-host', 'email-firewall'])
parser.add_argument('--state'); parser.add_argument('--cidr'); parser.add_argument('--cli')
parser.add_argument('action', choices=['host', 'email', 'email-host', 'email-firewall', 'reconcile'])
parser.add_argument('--root'); parser.add_argument('--state'); parser.add_argument('--cidr'); parser.add_argument('--cli')
args = parser.parse_args()
if args.action == 'host':
if args.action == 'reconcile':
reconcile(args.root)
elif args.action == 'host':
host()
elif args.action == 'email-host':
email_host(args.cidr)

View File

@ -20,6 +20,25 @@ RENDER = module('monitoring-helm-postrender')
class MonitoringMigrationTests(unittest.TestCase):
def test_scheduled_refresh_checks_exporters_but_preflight_does_not(self):
with tempfile.TemporaryDirectory() as directory:
manager = MANAGER.Monitoring.__new__(MANAGER.Monitoring)
manager.root = Path(directory)
with patch.object(manager, '_refresh'), patch.object(manager, 'reconcile_exporters') as check:
manager.refresh(reload=False)
check.assert_not_called()
manager.refresh()
check.assert_called_once()
def test_exporter_failure_fails_monitoring_refresh(self):
with tempfile.TemporaryDirectory() as directory:
manager = MANAGER.Monitoring.__new__(MANAGER.Monitoring)
manager.root = Path(directory)
with patch.object(manager, '_refresh'), \
patch.object(manager, 'reconcile_exporters', side_effect=RuntimeError('exporter down')):
with self.assertRaisesRegex(RuntimeError, 'exporter down'):
manager.refresh()
def test_failed_export_restores_last_valid_rules_and_configuration(self):
with tempfile.TemporaryDirectory() as directory:
manager = MANAGER.Monitoring.__new__(MANAGER.Monitoring)

View File

@ -103,5 +103,66 @@ class ExporterAccessTests(unittest.TestCase):
self.assertTrue(all('description' not in c for c in changes))
class ScheduledExporterTests(unittest.TestCase):
def exercise(self, *, enabled=True, address_changed=False, down=False, timeout=False):
import io
import shutil
import urllib.request
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
shutil.copyfile(ROOT / 'scripts/oci-foundation-resolve.py', root / 'oci-foundation-resolve.py')
state = root / 'state.json'
state.write_text(json.dumps({'version': 4, 'resources': []}))
source = '9.9.9.9/32' if address_changed else '8.8.8.8/32'
values = {'LAB_OCI_EMAIL_ENABLED': str(enabled).lower(), 'LAB_EMAIL_PUBLIC_IP': '1.1.1.1',
'LAB_OCI_FOUNDATION_STATE_FILE': str(state), 'LAB_OCI_EMAIL_ADMIN_CIDR': source,
'LAB_OCI_EMAIL_MONITORING_CIDR': source, 'LAB_TEST_PRESERVED': 'test-value'}
config = root / 'foundation.env'
config.write_text(''.join('export ' + k + '=' + v + '\n' for k, v in values.items()))
original = config.read_text()
(root / 'exporter-settings.json').write_text(json.dumps({
'config': str(config), 'names': list(values), 'cli': 'oci',
'ssh_key': '/test/key', 'ssh_user': 'ubuntu'}))
up = {'debian-host': {'health': 'up'}, 'oci-email-node': {'health': 'up'}}
unhealthy = {**up, 'oci-email-node': {'health': 'down'}}
samples = [unhealthy if down else up, unhealthy if timeout else up] if enabled else [up]
with patch.object(ACCESS, 'run', return_value='') as local, \
patch.object(ACCESS, 'email') as repair, \
patch.object(ACCESS.subprocess, 'run') as ssh, \
patch.object(ACCESS, 'healthy_targets', side_effect=samples), \
patch.object(urllib.request, 'urlopen', return_value=io.BytesIO(b'8.8.8.8')) as public_ip, \
patch('time.monotonic', side_effect=[0, 100]):
if timeout:
with self.assertRaisesRegex(RuntimeError, 'expected exporter targets UP'):
ACCESS.reconcile(root)
else:
ACCESS.reconcile(root)
local.assert_called_once()
needs_repair = enabled and (down or address_changed)
self.assertEqual(repair.call_count, int(needs_repair))
self.assertEqual(ssh.call_count, int(needs_repair))
self.assertEqual(public_ip.call_count, int(enabled))
if needs_repair:
self.assertIn('export LAB_TEST_PRESERVED=test-value', config.read_text())
self.assertIn('export LAB_OCI_EMAIL_MONITORING_CIDR=8.8.8.8/32', config.read_text())
else:
self.assertEqual(config.read_text(), original)
def test_healthy_unchanged_exporters_avoid_cloud_and_ssh_mutations(self):
self.exercise()
def test_down_email_exporter_triggers_repair(self):
self.exercise(down=True)
def test_public_ip_change_triggers_repair_even_before_scrape_fails(self):
self.exercise(address_changed=True)
def test_disabled_email_has_no_external_dependencies(self):
self.exercise(enabled=False)
def test_unrecovered_exporter_fails_scheduled_run(self):
self.exercise(down=True, timeout=True)
if __name__ == '__main__':
unittest.main()