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

Provide a non-lock version for UrlCredentialsProvider #326

Merged
merged 1 commit into from
Dec 27, 2024
Merged
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
55 changes: 55 additions & 0 deletions tosfs/certification.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,3 +236,58 @@ def _try_get_credentials(self) -> Optional[Credentials]:
):
return None
return self.credentials


class NoLockUrlCredentialsProvider(CredentialsProvider):
"""The class provides the credentials from an url.

It does not use lock to protect the credentials.
Due to threading.Lock is not serializable,
it can not be used in Ray remote function.
"""

def __init__(self, credential_url: str):
"""Initialize the UrlCredentialsProvider."""
if not credential_url:
raise TosfsCertificationError("The credential_url param must not be empty.")
self.expires: Optional[datetime] = None
self.credentials = None
self.credential_url = credential_url

def get_credentials(self) -> Credentials:
"""Get the credentials from the url."""
res = self._try_get_credentials()
if res is not None:
return res
try:
res = self._try_get_credentials()
if res is not None:
return res

res = requests.get(self.credential_url, timeout=30)
res_body = res.json()
self.credentials = Credentials(
res_body.get("AccessKeyId"),
res_body.get("SecretAccessKey"),
res_body.get("SessionToken"),
)
self.expires = datetime.strptime(
res_body.get("ExpiredTime"), ECS_DATE_FORMAT
)
return self.credentials
except Exception as e:
if self.expires is not None and (
datetime.now().timestamp() < self.expires.timestamp()
):
return self.credentials
raise TosfsCertificationError("Get token failed") from e

def _try_get_credentials(self) -> Optional[Credentials]:
if self.expires is None or self.credentials is None:
return None
if (
datetime.now().timestamp()
> (self.expires - timedelta(minutes=10)).timestamp()
):
return None
return self.credentials
Loading