Add per-source status tracking, /health sources block and /sources
Collectors record the result of every source (schema v3, table source_status); /health reports failing sources (failures in a row >= source_failure_threshold) and turns degraded; GET /sources shows the full state; runs end with a summary log line instead of "data saved". Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ab89c87321
commit
cb935fef0d
8 files changed
+351
-13
No files matched your search
@@ -140,3 +140,71 @@ def test_ripestat_session_retries_and_sourceapp(files, monkeypatch):
|
||||
class Response: # сервер просит подождать час: пауза ограничена потолком
|
||||
headers = {"Retry-After": "3600"}
|
||||
assert retry.get_retry_after(Response()) == cc.MAX_RETRY_AFTER
|
||||
|
||||
|
||||
def test_source_status_is_recorded(files, monkeypatch):
|
||||
(files / "config.json").write_text('{"asns": [1, 2], "fqdns": ["ok.example", "dead.example", "private.example"]}')
|
||||
|
||||
def statuses():
|
||||
with db.session() as conn:
|
||||
return db.source_statuses(conn)
|
||||
|
||||
# ASN 1 отвечает, ASN 2 сбоит трижды подряд: счётчик растёт, last_success не появляется
|
||||
def fetch_all(collector, broken):
|
||||
def fetch(asn):
|
||||
if asn in broken:
|
||||
collector.errors[str(asn)] = "http_5xx"
|
||||
return None
|
||||
return ["1.0.0.0/24"]
|
||||
return fetch
|
||||
|
||||
for _ in range(3):
|
||||
collector = cc.CIDRCollector()
|
||||
monkeypatch.setattr(collector, "fetch_prefixes", fetch_all(collector, {2}))
|
||||
collector.run_collection()
|
||||
state = statuses()
|
||||
assert state["asn", "1"]["failures"] == 0 and state["asn", "1"]["last_success"]
|
||||
assert state["asn", "2"]["failures"] == 3 and state["asn", "2"]["error_kind"] == "http_5xx"
|
||||
assert state["asn", "2"]["last_success"] is None
|
||||
|
||||
# Успех сбрасывает счётчик; источник, удалённый из конфигурации, теряет состояние
|
||||
collector = cc.CIDRCollector()
|
||||
monkeypatch.setattr(collector, "fetch_prefixes", fetch_all(collector, set()))
|
||||
collector.run_collection()
|
||||
assert statuses()["asn", "2"]["failures"] == 0 and statuses()["asn", "2"]["error_kind"] is None
|
||||
(files / "config.json").write_text('{"asns": [1], "fqdns": ["ok.example", "dead.example", "private.example"]}')
|
||||
collector = cc.CIDRCollector()
|
||||
monkeypatch.setattr(collector, "fetch_prefixes", lambda asn: ["1.0.0.0/24"])
|
||||
collector.run_collection()
|
||||
assert ("asn", "2") not in statuses()
|
||||
|
||||
# FQDN: DNS-сбой и «только неглобальные адреса» - разные категории
|
||||
def getaddrinfo(name, *args, **kwargs):
|
||||
if name == "dead.example":
|
||||
raise cc.socket.gaierror("no such host")
|
||||
address = "93.184.216.34" if name == "ok.example" else "10.0.0.5"
|
||||
return [(2, 1, 6, "", (address, 0))]
|
||||
|
||||
monkeypatch.setattr(cc.socket, "getaddrinfo", getaddrinfo)
|
||||
cc.FQDNCollector().run_collection()
|
||||
state = statuses()
|
||||
assert state["fqdn", "ok.example"]["failures"] == 0
|
||||
assert state["fqdn", "dead.example"]["error_kind"] == "dns"
|
||||
assert state["fqdn", "private.example"]["error_kind"] == "no_global_addresses"
|
||||
|
||||
# Категории ошибок (текст наружу не отдаётся)
|
||||
requests = cc.requests.exceptions
|
||||
assert cc.classify_error(requests.ConnectTimeout("x")) == "timeout"
|
||||
assert cc.classify_error(requests.ConnectionError("Read timed out")) == "timeout"
|
||||
assert cc.classify_error(requests.ConnectionError("refused")) == "connection"
|
||||
assert cc.classify_error(requests.RetryError("too many 429 error responses")) == "http_429"
|
||||
assert cc.classify_error(requests.HTTPError(response=type("R", (), {"status_code": 503})())) == "http_5xx"
|
||||
assert cc.classify_error(requests.HTTPError(response=type("R", (), {"status_code": 404})())) == "http_4xx"
|
||||
assert cc.classify_error(ValueError("bad json")) == "invalid_response" and cc.classify_error(KeyError()) == "unknown"
|
||||
|
||||
# База версии 2 (без таблицы состояния) обновляется при открытии, данные остаются
|
||||
with db.session() as conn:
|
||||
conn.execute("DROP TABLE source_status")
|
||||
conn.execute("PRAGMA user_version = 2")
|
||||
with db.session() as conn:
|
||||
assert db.source_statuses(conn) == {} and db.get_values(conn, "asn") == ["1.0.0.0/24"]
|
||||
@@ -145,3 +145,47 @@ def test_health_hides_internal_paths(env):
|
||||
|
||||
def json_dump_has_no_paths(text):
|
||||
return "/data" not in text and "corrupt" not in text and "not a database" not in text
|
||||
|
||||
|
||||
def test_health_reports_failing_sources(env):
|
||||
cc.add_to_config_list("asns", 62041)
|
||||
cc.add_to_config_list("fqdns", "example.com")
|
||||
save_json_atomic(cc.STATUS_FILE, {"updated_at": datetime.datetime.now().isoformat(), "jobs": {}}) # демон "жив"
|
||||
now = datetime.datetime.now()
|
||||
|
||||
def fail(times):
|
||||
for _ in range(times):
|
||||
with db.session() as conn, db.transaction(conn):
|
||||
db.record_source_result(conn, "asn", "62041", now, "http_5xx")
|
||||
|
||||
# До порога (3 сбоя подряд) источник не считается неисправным
|
||||
fail(2)
|
||||
health = env.get("/health").json()
|
||||
assert health["status"] == "ok" and health["sources"] == {"asn": {"total": 1, "failing": []},
|
||||
"fqdn": {"total": 1, "failing": []}}
|
||||
|
||||
# На пороге: degraded, источник в списке, наружу - только категория ошибки
|
||||
fail(1)
|
||||
health = env.get("/health").json()
|
||||
assert health["status"] == "degraded"
|
||||
assert health["sources"]["asn"]["failing"] == [{"source": "62041", "failures": 3, "last_success": None,
|
||||
"error_kind": "http_5xx"}]
|
||||
|
||||
# Полная картина: адреса источника и состояние; неопрошенный источник - пустое состояние
|
||||
with db.session() as conn, db.transaction(conn):
|
||||
db.merge_source(conn, "asn", "62041", {"1.0.0.0/24", "2.0.0.0/24"}, now, 90)
|
||||
report = env.get("/sources").json()
|
||||
assert report["failure_threshold"] == 3
|
||||
asn, fqdn = report["sources"]
|
||||
assert (asn["kind"], asn["source"], asn["addresses"], asn["failures"]) == ("asn", "62041", 2, 3)
|
||||
assert (fqdn["source"], fqdn["addresses"], fqdn["last_attempt"], fqdn["failures"]) == ("example.com", 0, None, 0)
|
||||
|
||||
# Успех сбрасывает счётчик, /health снова ok
|
||||
with db.session() as conn, db.transaction(conn):
|
||||
db.record_source_result(conn, "asn", "62041", now)
|
||||
assert env.get("/health").json()["status"] == "ok"
|
||||
|
||||
# Порог настраивается ключом source_failure_threshold
|
||||
cc.update_config(lambda config: config.update(source_failure_threshold=1))
|
||||
fail(1)
|
||||
assert env.get("/health").json()["status"] == "degraded"
|
||||
Reference in new issue
Block a user