Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[1.29] feat: Enable automatic cloud registration v2 again #3453

Draft
wants to merge 3 commits into
base: subscription-manager-1.29
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions src/rhsm/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -500,10 +500,14 @@ class RateLimitExceededException(RestlibException):
The retry_after attribute may not be included in the response.
"""

def __init__(self, code: int, msg: str = None, headers: str = None) -> None:
def __init__(self, code: int, msg: str = None, headers: dict = None) -> None:
super(RateLimitExceededException, self).__init__(code, msg)
self.headers = headers or {}
self.retry_after = safe_int(self.headers.get("retry-after"))
self.retry_after = None
for header, value in self.headers.items():
if header.lower() == "retry-after":
self.retry_after = safe_int(value)
break
self.msg = msg or "Access rate limit exceeded"
if self.retry_after is not None:
self.msg += ", retry access after: %s seconds." % self.retry_after
Expand Down Expand Up @@ -1515,11 +1519,10 @@ def getCloudJWT(self, cloud_id: str, metadata: str, signature: str) -> Dict[str,
}
headers = {
"Content-Type": "application/json",
"Accept": "text/plain",
}

return self.conn.request_post(
method="/cloud/authorize",
method="/cloud/authorize?version=2",
params=data,
headers=headers,
description=_("Fetching cloud token"),
Expand Down
46 changes: 33 additions & 13 deletions src/subscription_manager/scripts/rhsmcertd_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ def _auto_register(cp_provider: "CPProvider") -> ExitStatus:

# Obtain automatic registration token
try:
token: Dict[str, str] = cache.CloudTokenCache._get_from_server(
token: Dict[str, str] = cache.CloudTokenCache.get(
uep=uep,
cloud_id=cloud_info["cloud_id"],
metadata=cloud_info["metadata"],
Expand All @@ -201,14 +201,29 @@ def _auto_register(cp_provider: "CPProvider") -> ExitStatus:
log.exception("Cloud token could not be obtained. Unable to perform automatic registration.")
return ExitStatus.NO_REGISTRATION_TOKEN

try:
_auto_register_standard(uep=uep, token=token)
except Exception:
log.exception("Standard automatic registration failed.")
return ExitStatus.REGISTRATION_FAILED
else:
log.info("Standard automatic registration was successful.")
return ExitStatus.OK
if token["tokenType"] == "CP-Cloud-Registration":
try:
_auto_register_standard(uep=uep, token=token)
except Exception:
log.exception("Standard automatic registration failed.")
return ExitStatus.REGISTRATION_FAILED
else:
log.info("Standard automatic registration was successful.")
return ExitStatus.OK

if token["tokenType"] == "CP-Anonymous-Cloud-Registration":
try:
_auto_register_anonymous(uep=uep, token=token)
cache.CloudTokenCache.delete_cache()
except Exception:
log.exception("Anonymous automatic registration failed.")
return ExitStatus.REGISTRATION_FAILED
else:
log.info("Anonymous automatic registration was successful.")
return ExitStatus.OK

log.error(f"Unsupported token type for automatic registration: {token['tokenType']}.")
return ExitStatus.BAD_TOKEN_TYPE


def _auto_register_standard(uep: "UEPConnection", token: Dict[str, str]) -> None:
Expand All @@ -221,7 +236,7 @@ def _auto_register_standard(uep: "UEPConnection", token: Dict[str, str]) -> None
log.debug("Registering the system through standard automatic registration.")

service = RegisterService(cp=uep)
service.register(org=None, jwt_token=token)
service.register(org=None, jwt_token=token["token"])


def _auto_register_anonymous(uep: "UEPConnection", token: Dict[str, str]) -> None:
Expand Down Expand Up @@ -277,15 +292,20 @@ def _auto_register_anonymous(uep: "UEPConnection", token: Dict[str, str]) -> Non
log.debug(report)
return
except connection.RateLimitExceededException as exc:
if exc.headers.get("Retry-After", None) is None:
if exc.retry_after is None:
log.warning(
"Server did not include Retry-After header in rate-limited response. "
f"headers={exc.headers}"
)
raise
delay = int(exc.headers["Retry-After"])
delay = exc.retry_after
log.debug(
f"Got response with status code {exc.code} and Retry-After header, "
f"will try again in {delay} seconds."
)
time.sleep(delay)
except Exception:
except Exception as exc:
log.warning(f"Anonymous registration failed, server returned {exc}.")
raise

# In theory, this should not happen, it means that something has gone wrong server-side.
Expand Down
12 changes: 12 additions & 0 deletions test/rhsm/unit/test_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -871,6 +871,18 @@ def test_429_body(self):
else:
self.fail("Should have raised a RateLimitExceededException")

def test_429_weird_case(self):
content = '{"errors": ["TooFast"]}'
headers = {"RETry-aFteR": 20}
try:
self.vr("429", content, headers)
except RateLimitExceededException as e:
self.assertEqual(20, e.retry_after)
self.assertEqual("TooFast, retry access after: 20 seconds.", e.msg)
self.assertEqual("429", e.code)
else:
self.fail("Should have raised a RateLimitExceededException")

def test_500_empty(self):
try:
self.vr("500", "")
Expand Down
Loading