Skip to content

Commit

Permalink
feat: Improve test URLs output
Browse files Browse the repository at this point in the history
  • Loading branch information
Glutexo committed Dec 16, 2024
1 parent 01e00a2 commit 03aa24f
Showing 1 changed file with 45 additions and 47 deletions.
92 changes: 45 additions & 47 deletions insights/client/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ def _init_session(self):
session.trust_env = False
return session

def _http_request(self, url, method, log_response_text=True, **kwargs):
def _http_request(self, url, method, log_response_text=True, log_prefix="", log_level=NETWORK, **kwargs):
'''
Perform an HTTP request, net logging, and error handling
Parameters
Expand All @@ -174,7 +174,7 @@ def _http_request(self, url, method, log_response_text=True, **kwargs):
Returns
HTTP response object
'''
log_message = "{method} {url}".format(method=method, url=url)
log_message = "{log_prefix}{method} {url}".format(log_prefix=log_prefix, method=method, url=url)
if "data" in kwargs.keys():
log_message += " data={data}".format(data=kwargs["data"])
if "json" in kwargs.keys():
Expand All @@ -189,14 +189,14 @@ def _http_request(self, url, method, log_response_text=True, **kwargs):
else:
attachments.append(name)
log_message += " attachments={files}".format(files=",".join(attachments))
logger.log(NETWORK, log_message)
logger.log(log_level, log_message)
try:
res = self.session.request(url=url, method=method, timeout=self.config.http_timeout, **kwargs)
except Exception:
raise
logger.log(NETWORK, "HTTP Status: %d %s", res.status_code, res.reason)
logger.log(log_level, "%sHTTP Status: %d %s", log_prefix, res.status_code, res.reason)
if log_response_text or res.status_code // 100 != 2:
logger.log(NETWORK, "HTTP Response Text: %s", res.text)
logger.log(log_level, "%sHTTP Response Text: %s", log_prefix, res.text)
return res

def get(self, url, **kwargs):
Expand Down Expand Up @@ -353,28 +353,28 @@ def _legacy_test_urls(self, url, method):
test_url = url.scheme + "://" + url.netloc
last_ex = None
paths = (url.path + '/', '', '/r', '/r/insights')
log_level = NETWORK if self.config.verbose else logging.DEBUG
for ext in paths:
try:
logger.log(NETWORK, "Testing: %s", test_url + ext)
logger.info(" Testing %s", test_url + ext)
if ext == url.path + "/":
raise requests.exceptions.ConnectionError("errr")
if method == "POST":
test_req = self.post(test_url + ext, data=test_flag)
test_req = self.post(test_url + ext, data=test_flag, log_prefix=" ", log_level=log_level)
elif method == "GET":
test_req = self.get(test_url + ext)
test_req = self.get(test_url + ext, log_prefix=" ", log_level=log_level)
# Strata returns 405 on a GET sometimes, this isn't a big deal
if test_req.status_code in (200, 201):
logger.info(
"Successfully connected to: %s", test_url + ext)
return True
else:
logger.info("Connection failed")
logger.error(" Failed.")
return False
except REQUEST_FAILED_EXCEPTIONS as exc:
last_ex = exc
logger.error(
"Could not successfully connect to: %s", test_url + ext)
print(exc)
if last_ex:
raise last_ex
logger.debug(" Caught %s: %s", type(exc).__name__, exc)
logger.error(" Failed.")

return not last_ex

def _test_urls(self, url, method):
'''
Expand All @@ -383,28 +383,27 @@ def _test_urls(self, url, method):
if self.config.legacy_upload:
return self._legacy_test_urls(url, method)
try:
logger.log(NETWORK, 'Testing %s', url)
logger.info(' Testing %s', url)
# raise requests.exceptions.ConnectionError("errrrr")

log_prefix = " "
log_level = NETWORK if self.config.verbose else logging.DEBUG
if method == 'POST':
test_tar = TemporaryFile(mode='rb', suffix='.tar.gz')
test_files = {
'file': ('test.tar.gz', test_tar, 'application/vnd.redhat.advisor.collection+tgz'),
'metadata': '{\"test\": \"test\"}'
}
test_req = self.post(url, files=test_files)
test_req = self.post(url, files=test_files, log_prefix=log_prefix, log_level=log_level)
elif method == "GET":
test_req = self.get(url)
test_req = self.get(url, log_prefix=log_prefix, log_level=log_level)
if test_req.status_code in (200, 201, 202):
logger.info(
"Successfully connected to: %s", url)
return True
else:
logger.info("Connection failed")
return False
except REQUEST_FAILED_EXCEPTIONS as exc:
logger.error(
"Could not successfully connect to: %s", url)
print(exc)
raise
logger.debug(" Caught %s: %s", type(exc).__name__, exc)
return False

def _test_auth_config(self):
errors = []
Expand Down Expand Up @@ -489,29 +488,28 @@ def test_connection(self, rc=0):
self._dump_urls()

logger.info("Running Connection Tests...")
logger.info("")

try:
logger.info("=== Begin Upload URL Connection Test ===")
upload_success = self._test_urls(self.upload_url, "POST")
logger.info("=== End Upload URL Connection Test: %s ===\n",
"SUCCESS" if upload_success else "FAILURE")
logger.info("=== Begin API URL Connection Test ===")
api_success = self._test_urls(self.ping_url, 'GET')
logger.info("=== End API URL Connection Test: %s ===\n",
"SUCCESS" if api_success else "FAILURE")
if upload_success and api_success:
logger.info("Connectivity tests completed successfully")
print("See %s for more details." % self.config.logging_file)
for description, url, method in [
("Uploading a file to Ingress", self.upload_url, "POST"),
("Pinging the API", self.ping_url, "GET"),
]:
logger.info(" %s...", description)

success = self._test_urls(url, method)
if success:
logger.info(" SUCCESS.")
logger.info("")
else:
logger.info("Connectivity tests completed with some errors")
print("See %s for more details." % self.config.logging_file)
rc = 1
except REQUEST_FAILED_EXCEPTIONS:
logger.error('Connectivity test failed! '
'Please check your network configuration')
print('Additional information may be in %s' % self.config.logging_file)
return 1
return rc
logger.error(" FAILED.")
logger.error("")
logger.error(" Please check your network configuration")
logger.error(" Additional information may be in %s" % self.config.logging_file)
logger.error("")
return 1
else:
logger.info(" See %s for more details." % self.config.logging_file)
return rc

def handle_fail_rcs(self, req):
"""
Expand Down

0 comments on commit 03aa24f

Please sign in to comment.