Skip to content

Commit

Permalink
proxy: raise UpstreamRegistryError if we can't request upstream (#1220)
Browse files Browse the repository at this point in the history
requests will either throw a RequestException or a ConnectionError if it
fails to request the given url for whatever reason.
callers are only expected to treat UpstreamRegistryError, so we throw it
instead of the requests related exceptions, adding the original message
to the new exception.
  • Loading branch information
flavianmissi committed Mar 31, 2022
1 parent 7524171 commit b941a03
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions proxy/__init__.py
Expand Up @@ -6,6 +6,7 @@
import re

import requests
from requests.exceptions import RequestException

from app import model_cache
from data.cache import cache_key
Expand Down Expand Up @@ -119,14 +120,20 @@ def head(self, *args, **kwargs) -> requests.Response:
return self._request(self._session.head, *args, **kwargs)

def _request(self, request_func, *args, **kwargs) -> requests.Response:
resp = request_func(*args, **kwargs)
resp = self._safe_request(request_func, *args, **kwargs)
if resp.status_code == 401:
self._authorize(self._credentials(), force_renewal=True)
resp = request_func(*args, **kwargs)
resp = self._safe_request(request_func, *args, **kwargs)
if not resp.ok:
raise UpstreamRegistryError(resp.status_code)
return resp

def _safe_request(self, request_func, *args, **kwargs):
try:
return request_func(*args, **kwargs)
except (RequestException, ConnectionError) as e:
raise UpstreamRegistryError(str(e))

def _credentials(self) -> tuple[str, str] | None:
auth = None
username = self._config.upstream_registry_username
Expand Down Expand Up @@ -174,7 +181,7 @@ def _authorize(self, auth: tuple[str, str] | None = None, force_renewal: bool =
if auth is not None:
basic_auth = requests.auth.HTTPBasicAuth(auth[0], auth[1])

resp = self._session.get(auth_url, auth=basic_auth)
resp = self._safe_request(self._session.get, auth_url, auth=basic_auth)
if not resp.ok:
raise UpstreamRegistryError(
f"Failed to get token from: '{realm}', with status code: {resp.status_code}"
Expand Down

0 comments on commit b941a03

Please sign in to comment.