fix(vaults): log each vault failure once in one line without the request url

This commit is contained in:
imSp4rky
2026-11-27 09:47:49 -07:00
parent 5a6428521c
commit b719c44679
8 changed files with 274 additions and 48 deletions
+11 -6
View File
@@ -24,7 +24,7 @@ from unshackle.core.config import config
from unshackle.core.console import GradientPulseBarColumn, console
from unshackle.core.constants import context_settings
from unshackle.core.services import Services
from unshackle.core.vault import Vault, is_null_key
from unshackle.core.vault import Vault, brief, is_null_key
from unshackle.core.vaults import Vaults, load_config_vaults
@@ -114,7 +114,7 @@ def copy_service_data(
try:
content_keys = process_service_keys(from_vault, service, log)
except Exception as e:
log.warning(f"{service}: Could not read from {from_vault} ({e}), skipped")
log.warning(f"{service}: Could not read from {from_vault} ({brief(e)}), skipped")
return 0
content_keys = {kid: key for kid, key in content_keys.items() if not to_vault.is_bad_key(kid, key)}
@@ -129,6 +129,8 @@ def copy_service_data(
except PermissionError:
log.warning(f"{service}: No permission to create table in {to_vault}, skipped")
return 0
except Exception as e:
raise click.ClickException(f"Could not write to {to_vault} ({brief(e)})") from None
existed = total_count - added
@@ -213,7 +215,7 @@ def copy(
try:
services_to_copy = list(from_vault.get_services())
except Exception as e:
log.debug(f"{from_vault.name}: cannot list services ({e}), skipped")
log.debug(f"{from_vault.name}: cannot list services ({brief(e)}), skipped")
continue
if installed is not None:
@@ -313,7 +315,10 @@ def add(file: Path, service: str, vaults: list[str]) -> None:
for vault in vaults_:
log.info(f"Adding {total_count} Content Keys to {vault}")
added_count = add_keys_with_progress(vault, service, kid_keys, log)
try:
added_count = add_keys_with_progress(vault, service, kid_keys, log)
except Exception as e:
raise click.ClickException(f"Could not write to {vault} ({brief(e)})") from None
existed_count = total_count - added_count
log.info(f"{vault}: {added_count} newly added, {existed_count} already existed (skipped)")
@@ -327,7 +332,7 @@ def search_vault(vault: Vault, kid: str, services: list[str], log: logging.Logge
try:
key = vault.get_key(kid, svc)
except Exception as e:
log.debug(f"{vault} [{svc}]: lookup error ({e})")
log.debug(f"{vault} [{svc}]: lookup error ({brief(e)})")
return None
if key and not is_null_key(key):
return svc, key
@@ -392,7 +397,7 @@ def search(kid: str, service: str | None, vault_name: str | None) -> None:
try:
services_to_check = list(vault.get_services())
except Exception as e:
log.debug(f"{vault}: get_services() failed ({e})")
log.debug(f"{vault}: get_services() failed ({brief(e)})")
services_to_check = []
if not services_to_check:
services_to_check = list(Services.get_tags())
+35 -2
View File
@@ -1,14 +1,17 @@
import re
from abc import ABCMeta, abstractmethod
from collections.abc import Iterator
from urllib.parse import urlsplit
from uuid import UUID
from requests import ConnectionError as RequestsConnectionError
from requests import Session, Timeout
from requests import RequestException, Response, Session, Timeout
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from unshackle.core import __version__
from unshackle.core.session import POOL_MAX_SIZE
from unshackle.core.utils.redact import redact_text
RATE_LIMIT_RETRIES = 3
@@ -22,6 +25,36 @@ class RateLimited(Exception):
UNREACHABLE = (RequestsConnectionError, Timeout, ConnectionError, TimeoutError)
OS_REASON_RE = re.compile(r"\[(?:Errno -?\d+|WinError -?\d+|SSL: \w+)\] ([^'\"()\[\]]+)")
def brief(error: BaseException) -> str:
"""One line for a vault failure, without the request URL, whose query can hold the vault password."""
if not isinstance(error, RequestException) or (error.request is None and error.response is None):
text = (redact_text(str(error).strip().split("\n", 1)[0]) or "")[:200]
return text or type(error).__name__
url = getattr(error.request, "url", None)
host = urlsplit(url).netloc.rpartition("@")[2] if url else "vault"
if error.response is not None:
return f"HTTP {error.response.status_code} from {host}"
text = str(error)
reasons = OS_REASON_RE.findall(text)
reason = reasons[-1].strip() if reasons else "timed out" if "timed out" in text else ""
return f"{type(error).__name__} to {host}" + (f" ({reason})" if reason else "")
def json_body(r: Response) -> dict:
"""The response body as a JSON object. Any other body means the host is not a vault, so it is unreachable."""
try:
data = r.json()
except ValueError:
data = None
if not isinstance(data, dict):
mime = re.match(r"[\w.+-]{1,64}/[\w.+-]{1,64}", r.headers.get("Content-Type", ""))
content_type = mime.group() if mime else "unknown"
raise ConnectionError(f"HTTP {r.status_code} {content_type} response is not a JSON object")
return data
def is_null_key(key: str | None) -> bool:
"""True for a blank or all-zero content key, the null key that no vault stores."""
@@ -115,4 +148,4 @@ class Vault(metaclass=ABCMeta):
"""Forget a flagged KID:KEY, for example when a CDM licence confirmed it."""
__all__ = ("Vault",)
__all__ = ("Vault", "brief", "json_body")
+15 -4
View File
@@ -9,7 +9,7 @@ from uuid import UUID
from unshackle.core.config import config
from unshackle.core.utilities import get_debug_logger, import_module_by_path
from unshackle.core.vault import UNREACHABLE, RateLimited, Vault, is_null_key
from unshackle.core.vault import UNREACHABLE, RateLimited, Vault, brief, is_null_key
log = logging.getLogger(__name__)
@@ -30,6 +30,7 @@ class Vaults:
self.flagged: set[tuple[UUID | str, str]] = set()
self.candidates: dict[UUID | str, list[tuple[str, Vault]]] = {}
self.warned: set[tuple[str, UUID | str, str]] = set()
self.failed: set[tuple[str, str]] = set()
self.unreachable: set[Vault] = set()
self.unreported: dict[tuple[UUID | str, str], Vault] = {}
@@ -110,7 +111,7 @@ class Vaults:
except (PermissionError, NotImplementedError):
return None
except Exception as e:
log.warning(f"Failed to get key from Vault '{vault.name}': {e}")
self.warn_failure(vault, "get key from", e)
self.mark_unreachable(vault, e)
if dl:
dl.log_vault_query(
@@ -209,7 +210,7 @@ class Vaults:
except (PermissionError, NotImplementedError):
return 0
except Exception as e:
log.warning(f"Failed to add key to Vault '{vault.name}': {e}")
self.warn_failure(vault, "add key to", e)
self.mark_unreachable(vault, e)
if dl:
dl.log_vault_query(vault.name, "add_key", kid=str(kid), success=False, error=e)
@@ -240,7 +241,7 @@ class Vaults:
except (PermissionError, NotImplementedError):
return 0
except Exception as e:
log.warning(f"Failed to add keys to Vault '{vault.name}': {e}")
self.warn_failure(vault, "add keys to", e)
self.mark_unreachable(vault, e)
return 0
@@ -252,6 +253,16 @@ class Vaults:
"""True when a local vault already holds this KID:KEY."""
return any(self.query_vault(vault, kid) == key for vault in self.vaults if vault.local)
def warn_failure(self, vault: Vault, action: str, error: Exception) -> None:
"""Warn once per vault for each distinct failure; a repeat goes to the debug log."""
text = brief(error)
message = f"Failed to {action} Vault '{vault.name}': {text}"
if (vault.name, text) in self.failed:
log.debug(message)
else:
self.failed.add((vault.name, text))
log.warning(message)
def mark_unreachable(self, vault: Vault, error: Exception) -> None:
"""Skip a vault that is down or still rate limited for the rest of the run, so it costs one
timeout, not one per KID."""
+8 -9
View File
@@ -3,7 +3,7 @@ from uuid import UUID
from requests import HTTPError, Response
from unshackle.core.vault import RateLimited, Vault, vault_session
from unshackle.core.vault import RateLimited, Vault, json_body, vault_session
class API(Vault):
@@ -40,7 +40,7 @@ class API(Vault):
if response.status_code == 429:
raise Exceptions.TooManyRequests()
response.raise_for_status()
data = response.json()
data = json_body(response)
code = int(data.get("code", 0))
message = data.get("message")
@@ -76,7 +76,7 @@ class API(Vault):
allow_redirects=False,
)
response.raise_for_status()
data = response.json()
data = json_body(response)
code = int(data.get("code", 0))
message = data.get("message")
@@ -116,7 +116,7 @@ class API(Vault):
allow_redirects=False,
)
response.raise_for_status()
data = response.json()
data = json_body(response)
code = int(data.get("code", 0))
message = data.get("message")
@@ -173,9 +173,8 @@ class API(Vault):
if response.status_code == 429:
raise Exceptions.TooManyRequests()
response.raise_for_status()
data = response.json()
except (ValueError, HTTPError):
# an HTTP error or a broken JSON reply - try smaller batch
data = json_body(response)
except HTTPError:
if batch_size > 1:
if batch_size > 100:
batch_size -= 100
@@ -239,7 +238,7 @@ class API(Vault):
if response.status_code in (404, 405, 501):
return
response.raise_for_status()
data = response.json()
data = json_body(response)
code = int(data.get("code", 0))
if not code or code in ignore:
return
@@ -251,7 +250,7 @@ class API(Vault):
url=self.uri, headers={"Accept": "application/json"}, timeout=self.timeout, allow_redirects=False
)
response.raise_for_status()
data = response.json()
data = json_body(response)
code = int(data.get("code", 0))
message = data.get("message")
+9 -25
View File
@@ -1,11 +1,8 @@
import json
import re
from collections.abc import Iterator
from uuid import UUID
from requests import Response
from unshackle.core.vault import RateLimited, Vault, is_null_key, vault_session
from unshackle.core.vault import RateLimited, Vault, is_null_key, json_body, vault_session
class HTTP(Vault):
@@ -65,19 +62,6 @@ class HTTP(Vault):
elif self.api_mode not in ["query", "json", "decrypt_labs"]:
raise ValueError("api_mode must be either 'query', 'json', or 'decrypt_labs'")
@staticmethod
def parse_json(r: Response) -> dict:
"""The response body as a JSON object. Any other body means the host is not a vault, so it is unreachable."""
try:
data = r.json()
except ValueError:
data = None
if not isinstance(data, dict):
mime = re.match(r"[\w.+-]{1,64}/[\w.+-]{1,64}", r.headers.get("Content-Type", ""))
content_type = mime.group() if mime else "unknown"
raise ConnectionError(f"HTTP {r.status_code} {content_type} response is not a JSON object")
return data
def request(self, method: str, params: dict | None = None) -> dict:
"""Make a request to the JSON API vault."""
if self.api_mode != "json":
@@ -101,10 +85,10 @@ class HTTP(Vault):
raise RateLimited()
if not r.ok:
detail = self.parse_json(r).get("message") or r.reason.title()
detail = json_body(r).get("message") or r.reason.title()
raise ValueError(f"API returned HTTP Error {r.status_code}: {detail}")
res = self.parse_json(r)
res = json_body(r)
if res.get("status_code") != 200:
raise ValueError(f"API returned an error: {res['status_code']} - {res['message']}")
@@ -123,7 +107,7 @@ class HTTP(Vault):
if not response.ok:
return None
data = self.parse_json(response)
data = json_body(response)
if data.get("message") != "success":
return None
@@ -180,7 +164,7 @@ class HTTP(Vault):
timeout=self.timeout,
)
data = self.parse_json(response)
data = json_body(response)
if not data.get("keys"):
return None
@@ -201,7 +185,7 @@ class HTTP(Vault):
timeout=self.timeout,
)
data = self.parse_json(response)
data = json_body(response)
if data.get("status_code") != 200 or not data.get("keys"):
return
@@ -251,7 +235,7 @@ class HTTP(Vault):
timeout=self.timeout,
)
data = self.parse_json(response)
data = json_body(response)
return data.get("status_code") == 200
@@ -317,7 +301,7 @@ class HTTP(Vault):
timeout=self.timeout,
)
data = self.parse_json(response)
data = json_body(response)
if data.get("status_code") == 200 and data.get("inserted", True):
inserted_count += 1
@@ -342,7 +326,7 @@ class HTTP(Vault):
timeout=self.timeout,
)
data = self.parse_json(response)
data = json_body(response)
if data.get("status_code") != 200:
return