Skip to content

Commit 4dca350

Browse files
Second attempt at fixing the diagnostics issues (#1755)
* Second attempt at fixing the diagnostics issues * Second attempt at fixing the diagnostics issues
1 parent 4e29385 commit 4dca350

File tree

4 files changed

+97
-10
lines changed

4 files changed

+97
-10
lines changed

DESCRIPTION.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ https://docs.snowflake.com/
77
Source code is also available at: https://github.com/snowflakedb/snowflake-connector-python
88

99
# Release Notes
10+
- v3.2.2(TBD)
11+
- Fixed issue with connection diagnostics failing to complete certificate checks.
1012

1113
- v3.3.0(October 10,2023)
1214

src/snowflake/connector/connection.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import pathlib
1111
import re
1212
import sys
13+
import traceback
1314
import uuid
1415
import warnings
1516
import weakref
@@ -626,6 +627,7 @@ def connect(self, **kwargs) -> None:
626627
TelemetryService.get_instance().update_context(kwargs)
627628

628629
if self.enable_connection_diag:
630+
exceptions_dict = {}
629631
connection_diag = ConnectionDiagnostic(
630632
account=self.account,
631633
host=self.host,
@@ -640,15 +642,22 @@ def connect(self, **kwargs) -> None:
640642
connection_diag.run_test()
641643
self.__open_connection()
642644
connection_diag.cursor = self.cursor()
643-
except Exception as e:
644-
logger.warning(f"Exception during connection test: {e}")
645-
645+
except Exception:
646+
exceptions_dict["connection_test"] = traceback.format_exc()
647+
logger.warning(
648+
f"""Exception during connection test:\n{exceptions_dict["connection_test"]} """
649+
)
646650
try:
647651
connection_diag.run_post_test()
648-
except Exception as e:
649-
logger.warning(f"Exception during post connection test: {e}")
652+
except Exception:
653+
exceptions_dict["post_test"] = traceback.format_exc()
654+
logger.warning(
655+
f"""Exception during post connection test:\n{exceptions_dict["post_test"]} """
656+
)
650657
finally:
651658
connection_diag.generate_report()
659+
if exceptions_dict:
660+
raise Exception(str(exceptions_dict))
652661
else:
653662
self.__open_connection()
654663

src/snowflake/connector/connection_diagnostic.py

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,19 @@
3030
import winreg
3131

3232

33+
def _decode_dict(d):
34+
result = {}
35+
for key, value in d.items():
36+
if isinstance(key, bytes):
37+
key = key.decode()
38+
if isinstance(value, bytes):
39+
value = value.decode()
40+
elif isinstance(value, dict):
41+
value = _decode_dict(value)
42+
result.update({key: value})
43+
return result
44+
45+
3346
class ConnectionDiagnostic:
3447
"""Implementation of a connection test utility for Snowflake connector
3548
@@ -360,10 +373,12 @@ def __https_host_report(
360373
f"{host}:{port}: URL Check: Failed: Certificate mismatch: Host not in subject or alt names",
361374
)
362375
self.__append_message(host_type, f"{host}: Cert info:")
363-
self.__append_message(
364-
host_type, f"{host}: subject: {result['subject']}"
365-
)
366-
self.__append_message(host_type, f"{host}: issuer: {result['issuer']}")
376+
377+
subject_str = _decode_dict(result["subject"])
378+
self.__append_message(host_type, f"{host}: subject: {subject_str}")
379+
380+
issuer_str = _decode_dict(result["issuer"])
381+
self.__append_message(host_type, f"{host}: issuer: {issuer_str}")
367382
self.__append_message(
368383
host_type, f"{host}: serialNumber: {result['serialNumber']}"
369384
)
@@ -414,7 +429,9 @@ def __https_host_report(
414429

415430
def __get_issuer_string(self, issuer: dict[bytes, bytes]) -> str:
416431
issuer_str: str = (
417-
re.sub('[{}"]', "", json.dumps(issuer)).replace(": ", "=").replace(",", ";")
432+
re.sub('[{}"]', "", json.dumps(_decode_dict(issuer)))
433+
.replace(": ", "=")
434+
.replace(",", ";")
418435
)
419436
return issuer_str
420437

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
#!/usr/bin/env python
2+
#
3+
# Copyright (c) 2012-2023 Snowflake Computing Inc. All rights reserved.
4+
#
5+
6+
from __future__ import annotations
7+
8+
import snowflake.connector
9+
from snowflake.connector.connection_diagnostic import ConnectionDiagnostic, _decode_dict
10+
11+
12+
def test_https_host_report(caplog):
13+
connection_diag = ConnectionDiagnostic(
14+
account="test", host="test.snowflakecomputing.com"
15+
)
16+
https_host_report = connection_diag._ConnectionDiagnostic__https_host_report
17+
https_host_report(
18+
host="client-telemetry.snowflakecomputing.com",
19+
port=443,
20+
host_type="OUT_OF_BAND_TELEMETRY",
21+
)
22+
23+
assert "DNS:client-telemetry.snowflakecomputing.com" in ".".join(
24+
connection_diag.test_results["OUT_OF_BAND_TELEMETRY"]
25+
)
26+
27+
28+
def test_decode_dict():
29+
test_dict = {b"CN": b"client-telemetry.snowflakecomputing.com"}
30+
result = _decode_dict(test_dict)
31+
32+
assert result == {
33+
"CN": "client-telemetry.snowflakecomputing.com"
34+
}, "_decode_dict method failed, binary dict not converted."
35+
36+
37+
def test_exception_raise_during_diag_fail(monkeypatch, caplog):
38+
def mock_run_post_test(self):
39+
raise ValueError("Diagnostic Test Failure")
40+
41+
monkeypatch.setattr(
42+
snowflake.connector.connection_diagnostic.ConnectionDiagnostic,
43+
"run_post_test",
44+
mock_run_post_test,
45+
)
46+
47+
try:
48+
snowflake.connector.connect(
49+
account="testaccount",
50+
user="testuser",
51+
password="testpassword",
52+
database="TESTDB",
53+
warehouse="TESTWH",
54+
enable_connection_diag=True,
55+
)
56+
except BaseException:
57+
pass
58+
59+
assert "Diagnostic Test Failure" in caplog.text

0 commit comments

Comments
 (0)