Skip to content

Commit 58fd9e6

Browse files
Update confirm_access to handle failure in constructor
Refactor error handling in failed_net_message
1 parent 26e0c6e commit 58fd9e6

File tree

2 files changed

+38
-18
lines changed

2 files changed

+38
-18
lines changed

firefly_client/env.py

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -93,12 +93,20 @@ def find_default_firefly_html(cls): return cls.firefly_html
9393

9494
@classmethod
9595
def failed_net_message(cls, location, status_code=-1):
96-
s_str = 'with status: %s' % status_code if (status_code > -1) else ''
97-
check = 'You may want to check the URL with your web browser.\n'
98-
err_message = 'Connection fail to URL %s %s\n%s' % (location, s_str, check)
99-
if cls.firefly_lab_extension and cls.firefly_url_lab:
100-
err_message += ('\nCheck the Firefly URL in ~/.jupyter/jupyter_notebook_config.py' +
101-
' or ~/.jupyter/jupyter_notebook_config.json')
102-
elif cls.firefly_url:
103-
err_message += 'Check setting of FIREFLY_URL environment variable: %s' % cls.firefly_url
96+
status_str = f'with status: {status_code}' if status_code > -1 else ''
97+
check_msg = 'You may want to check the URL with your web browser.\n'
98+
err_message = f'Connection failed to URL {location} {status_str}\n{check_msg}'
99+
100+
# url sources in order of precedence
101+
url_sources = []
102+
if cls.firefly_url: # any environment
103+
url_sources.append(f'environment variable "{ENV_FF_URL}"')
104+
if cls.firefly_lab_extension and cls.firefly_url_lab: # lab environment
105+
url_sources += [
106+
'~/.jupyter/jupyter_notebook_config.json',
107+
'~/.jupyter/jupyter_notebook_config.py',
108+
]
109+
err_message += (f'\nCheck if the Firefly URL is correct, which is '
110+
f'passed as a parameter, or is set via {" or ".join(url_sources)}.')
111+
104112
return err_message

firefly_client/firefly_client.py

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -232,17 +232,34 @@ def __init__(self, url, channel, html_file=_def_html_file, token=None, viewer_ov
232232
self.auth_headers = {'Authorization': 'Bearer {}'.format(token)} if token and ssl else None
233233
self.header_from_ws = {'FF-channel': channel}
234234
self.lab_env_tab_type = UNKNOWN
235+
235236
# urls for cmd service and browser
236237
protocol = 'https' if ssl else 'http'
237238
self.url_cmd_service = urljoin('{}://{}/'.format(protocol, self.location), 'sticky/CmdSrv')
238239
self.url_browser = urljoin(urljoin('{}://{}/'.format(protocol, self.location), html_file), '?__wsch=')
239240
self.url_bw = self.url_browser # keep around for backward compatibility
241+
240242
self.session = requests.Session()
241243
token and ssl and self.session.headers.update(self.auth_headers)
242244
not ssl and token and warn('token ignored: should be None when url starts with http://')
243245
self.firefly_viewer = FireflyClient.get_viewer_mode(html_file,viewer_override)
244-
FireflyClient.confirm_access(url, token)
245-
debug('new instance: %s' % url)
246+
247+
access = FireflyClient.confirm_access(url, token)
248+
if not access['success']:
249+
debug(f'Failed to access url: {url}, with token: {token}\n'
250+
f'Response status: {access["response"].status_code} ({access["response"].reason})\n'
251+
f'Response headers: {dict_to_str(access["response"].headers)}\n'
252+
f'Response text: {access["response"].text}')
253+
url_err_msg = Env.failed_net_message(url, access['response'].status_code)
254+
token_err_msg = (
255+
'Check if the passed `token` is valid and has the necessary '
256+
'authorization to access the above URL.'
257+
if token else
258+
'If an authorization token is required to access the above URL, '
259+
'the `token` parameter must be passed.'
260+
)
261+
raise ValueError(f'{url_err_msg}\n\n{token_err_msg}')
262+
debug(f'new instance: {url}')
246263

247264
def _lab_env_tab_start(self, tab_type, html_file):
248265
"""start a tab in the lab environment, tab_type must be 'lab' or 'browser' """
@@ -276,17 +293,12 @@ def get_viewer_mode(html_file, viewer_override):
276293
return FireflyClient.SLATE_VIEWER if html_file == 'slate.html' else FireflyClient.TRIVIEW_VIEWER
277294

278295
@staticmethod
279-
def confirm_access(url, token):
296+
def confirm_access(url, token=None):
280297
headers = {'Authorization': f'Bearer {token}'} if token else None
281298
healthz_url = url + ('healthz' if url.endswith('/') else '/healthz')
299+
# disable redirects that may happen in the absence of a token
282300
response = requests.get(healthz_url, headers=headers, allow_redirects=False)
283-
if response.status_code == 200:
284-
return True
285-
else:
286-
raise ValueError(
287-
f"Access to {url} failed with status code {response.status_code}.\n"
288-
f"GET Headers: {response.headers}"
289-
)
301+
return {'success': response.status_code == 200, 'response': response}
290302

291303
def _send_url_as_get(self, url):
292304
return self.call_response(self.session.get(url, headers=self.header_from_ws))

0 commit comments

Comments
 (0)