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

Handle error responses from API token endpoint #325

Merged
24 changes: 20 additions & 4 deletions nmdc_automation/api/nmdcapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@
from nmdc_automation.config import SiteConfig, UserConfig
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

SECONDS_IN_DAY = 86400

def _get_sha256(fn: Union[str, Path]) -> str:
"""
Expand Down Expand Up @@ -45,7 +49,7 @@ def expiry_dt_from_now(days=0, hours=0, minutes=0, seconds=0):

class NmdcRuntimeApi:
token = None
expires = 0
expires_in_seconds = 0
_base_url = None
client_id = None
client_secret = None
Expand All @@ -63,7 +67,7 @@ def __init__(self, site_configuration: Union[str, Path, SiteConfig]):
def refresh_token(func):
def _get_token(self, *args, **kwargs):
# If it expires in 60 seconds, refresh
if not self.token or self.expires + 60 > time():
if not self.token or self.expires_in_seconds + 60 > time():
self.get_token()
return func(self, *args, **kwargs)

Expand All @@ -84,8 +88,20 @@ def get_token(self):
}
url = self._base_url + "token"
resp = requests.post(url, headers=h, data=data).json()
expt = resp["expires"]
self.expires = time() + expt["minutes"] * 60
expires = resp["expires"]

# Expires can be in days, hours, minutes, seconds - sum them up and convert to seconds
expires = 0
if "days" in resp["expires"]:
expires += int(resp["expires"]["days"]) * SECONDS_IN_DAY
if "hours" in resp["expires"]:
expires += int(resp["expires"]["hours"]) * 3600
if "minutes" in resp["expires"]:
expires += int(resp["expires"]["minutes"]) * 60
if "seconds" in resp["expires"]:
expires += int(resp["expires"]["seconds"])

self.expires_in_seconds = time() + expires

self.token = resp["access_token"]
self.header = {
Expand Down
2 changes: 1 addition & 1 deletion nmdc_automation/workflow_automation/watch_nmdc.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ def get_unclaimed_jobs(self, allowed_workflows) -> List[WorkflowJob]:
"workflow.id": {"$in": allowed_workflows},
"claims": {"$size": 0}
}
job_records = self.runtime_api.list_jobs(filt=filt)
job_records = self.runtime_api.list_jobs(filt=filt)

for job in job_records:
jobs.append(WorkflowJob(self.config, workflow_state=job))
Expand Down
Loading