🔊 swu: more verbosity in case of API errors

Implements #4332
This commit is contained in:
Gina Häußge committed 2022-02-28 18:05:07 +01:00
1 parent fd73e89c93
commit e6541938db
7 files changed
+81 -43

No files matched your search

@@ -1862,6 +1862,12 @@ class SoftwareUpdatePlugin(
)
update_possible = False
error = "network"
except exceptions.ApiCheckError as exc:
self._logger.warning(
f"Could not check {target} for updates due to an API error: {exc}"
)
update_possible = False
error = "api"
except exceptions.RateLimitCheckError as exc:
self._logger.warning(
"Could not check {} for updates due to running into a rate limit: {}".format(
@@ -42,6 +42,14 @@ class CheckError(Exception):
return self.message
class ApiCheckError(CheckError):
API = "API"
def __init__(self, status_code, message):
self.status_code = status_code
super().__init__(f"{self.API} error: {message} (HTTP {status_code})")
class RateLimitCheckError(CheckError):
def __init__(self, message, remaining=None, limit=None, reset=None):
super().__init__(message)
@@ -661,7 +661,14 @@ $(function () {
return gettext("Cannot check for update, need online connection");
}
case "network": {
return gettext("Network error while checking for update");
return gettext(
"Network error while checking for update, please check the logs"
);
}
case "api": {
return gettext(
"API error while checking for update, please check the logs"
);
}
case "ratelimit": {
return gettext(
@@ -669,7 +676,9 @@ $(function () {
);
}
case "check": {
return gettext("Check internal error while checking for update");
return gettext(
"Check internal error while checking for update, please check the logs"
);
}
case "unknown": {
return gettext(
@@ -2,7 +2,7 @@ __author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
from ..exceptions import RateLimitCheckError
from ..exceptions import ApiCheckError, RateLimitCheckError
from . import ( # noqa: F401
always_current,
bitbucket_commit,
@@ -18,16 +18,36 @@ from . import ( # noqa: F401
)
class GithubRateLimitCheckError(RateLimitCheckError):
class GitHubRateLimitCheckError(RateLimitCheckError):
def __init__(self, remaining, ratelimit, reset):
if reset:
message = f"Github rate limit exceeded, reset at {reset}"
message = f"GitHub rate limit exceeded, reset at {reset}"
else:
message = "Github rate limit exceeded"
message = "GitHub rate limit exceeded"
super().__init__(message, remaining=remaining, limit=ratelimit, reset=reset)
def log_github_ratelimit(logger, r):
class GitHubApiError(ApiCheckError):
API = "GitHub API"
def check_github_apiresponse(logger, r, ok_codes=None):
if ok_codes is None:
ok_codes = (200,)
if r.status_code not in ok_codes:
try:
data = r.json()
message = data.get("message", "Unknown error")
except Exception:
message = "Not a valid JSON response"
exc = GitHubApiError(r.status_code, message)
logger.error(exc.message)
raise exc
def check_github_ratelimit(logger, r):
try:
ratelimit = int(r.headers.get("X-RateLimit-Limit", None))
except Exception:
@@ -55,4 +75,4 @@ def log_github_ratelimit(logger, r):
)
if remaining == 0:
raise GithubRateLimitCheckError(remaining, ratelimit, reset)
raise GitHubRateLimitCheckError(remaining, ratelimit, reset)
@@ -6,6 +6,8 @@ import logging
import requests
from . import ApiCheckError
BRANCH_HEAD_URL = (
"https://api.bitbucket.org/2.0/repositories/{user}/{repo}/commit/{branch}"
)
@@ -15,6 +17,26 @@ logger = logging.getLogger(
)
class BitbucketApiError(ApiCheckError):
API = "Bitbucket API"
def check_bitbucket_api_response(logger, r, ok_codes=None):
if ok_codes is None:
ok_codes = [requests.codes.ok]
if r.status_code not in ok_codes:
try:
data = r.json()
message = data.get("message", "Unknown error")
except Exception:
message = "Not a valid JSON response"
exc = BitbucketApiError(r.status_code, message)
logger.error(exc.message)
raise exc
def _get_latest_commit(user, repo, branch, api_user=None, api_password=None):
from ..exceptions import NetworkError
@@ -31,12 +53,11 @@ def _get_latest_commit(user, repo, branch, api_user=None, api_password=None):
except requests.ConnectionError as exc:
raise NetworkError(cause=exc)
if not r.status_code == requests.codes.ok:
return None
check_bitbucket_api_response(logger, r)
reference = r.json()
if "hash" not in reference:
return None
raise BitbucketApiError(r.status_code, "No commit hash found in response")
return reference["hash"]
@@ -30,12 +30,10 @@ def _get_latest_commit(user, repo, branch, apikey=None):
except requests.ConnectionError as exc:
raise NetworkError(cause=exc)
from . import log_github_ratelimit
from . import check_github_apiresponse, check_github_ratelimit
log_github_ratelimit(logger, r)
if not r.status_code == requests.codes.ok:
return None
check_github_ratelimit(logger, r)
check_github_apiresponse(logger, r)
reference = r.json()
if "object" not in reference or "sha" not in reference["object"]:
@@ -105,8 +105,6 @@ def _get_latest_release(
):
from ..exceptions import NetworkError
nothing = None, None, None
headers = {}
if apikey:
auth = "token " + apikey
@@ -119,12 +117,10 @@ def _get_latest_release(
except requests.ConnectionError as exc:
raise NetworkError(cause=exc)
from . import log_github_ratelimit
from . import check_github_apiresponse, check_github_ratelimit
log_github_ratelimit(logger, r)
if not r.status_code == requests.codes.ok:
return nothing
check_github_ratelimit(logger, r)
check_github_apiresponse(logger, r)
releases = r.json()
@@ -172,26 +168,6 @@ def _get_sanitized_version(version_string):
return version_string
def _get_base_from_version_tuple(version_tuple):
"""
Reduces version tuple to base version.
Tests:
>>> _get_base_from_version_tuple(("1", "2", "15"))
('1', '2', '15')
>>> _get_base_from_version_tuple(("1", "2", "15", "*", "dev12"))
('1', '2', '15')
"""
base_version = []
for part in version_tuple:
if part.startswith("*"):
break
base_version.append(part)
return tuple(base_version)
def _get_comparable_version_semantic(version_string, force_base=True):
import semantic_version