Skip to content

Commit cab0ee6

Browse files
authored
Merge pull request #1 from msmygit/ez-astra
Improvized Astra DB connection based on the given region
2 parents 9ac1704 + f764ade commit cab0ee6

File tree

1 file changed

+58
-10
lines changed

1 file changed

+58
-10
lines changed

cassandra/cluster.py

Lines changed: 58 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
import os
4141
import urllib.request
4242
import json
43+
from typing import Optional
4344

4445
import weakref
4546
from weakref import WeakValueDictionary
@@ -1042,6 +1043,19 @@ def default_retry_policy(self, policy):
10421043
'use_default_tempdir': True # use the system temp dir for the zip extraction
10431044
}
10441045
1046+
(or)
1047+
1048+
{
1049+
# Astra DB cluster UUID. Only if secure_connect_bundle is not provided
1050+
'db_id': 'db_id',
1051+
1052+
# required with db_id. Astra DB token
1053+
'token': 'AstraCS:change_me:change_me'
1054+
1055+
# optional with db_id & token. Astra DB region
1056+
'db_region': 'us-east1',
1057+
}
1058+
10451059
The zip file will be temporarily extracted in the same directory to
10461060
load the configuration and certificates.
10471061
"""
@@ -1174,13 +1188,17 @@ def __init__(self,
11741188
uses_eventlet = EventletConnection and issubclass(self.connection_class, EventletConnection)
11751189

11761190
# Check if we need to download the secure connect bundle
1177-
if 'db_id' in cloud and 'token' in cloud:
1191+
if all(akey in cloud for akey in ('db_id', 'token')):
11781192
# download SCB if necessary
11791193
if 'secure_connect_bundle' not in cloud:
1180-
bundle_path = f'astra-secure-connect-{cloud["db_id"]}.zip'
1194+
bundle_path = f'astradb-scb-{cloud["db_id"]}'
1195+
if 'db_region' in cloud:
1196+
bundle_path += f'-{cloud["db_region"]}.zip'
1197+
else:
1198+
bundle_path += '.zip'
11811199
if not os.path.exists(bundle_path):
1182-
print('Downloading Secure Cloud Bundle')
1183-
url = self._get_astra_bundle_url(cloud['db_id'], cloud['token'])
1200+
log.info('Downloading Secure Cloud Bundle...')
1201+
url = self._get_astra_bundle_url(cloud['db_id'], cloud['token'], cloud["db_region"])
11841202
try:
11851203
with urllib.request.urlopen(url) as r:
11861204
with open(bundle_path, 'wb') as f:
@@ -2208,21 +2226,51 @@ def get_control_connection_host(self):
22082226
return self.metadata.get_host(endpoint) if endpoint else None
22092227

22102228
@staticmethod
2211-
def _get_astra_bundle_url(db_id, token):
2229+
def _get_astra_bundle_url(db_id, token, db_region: Optional[str] = None):
2230+
"""
2231+
Retrieves the secure connect bundle URL for an Astra DB cluster based on the provided 'db_id',
2232+
'db_region' (optional) and 'token'.
2233+
2234+
Args:
2235+
db_id (str): The Astra DB cluster UUID.
2236+
token (str): The Astra token.
2237+
db_region (optional str): The Astra DB cluster region.
2238+
2239+
Returns:
2240+
str: The secure connect bundle URL for the given inputs.
2241+
2242+
Raises:
2243+
URLError: If the request to the Astra DB API fails.
2244+
"""
22122245
# set up the request
2213-
url = f"https://api.astra.datastax.com/v2/databases/{db_id}/secureBundleURL"
2246+
url = f"https://api.astra.datastax.com/v2/databases/{db_id}/datacenters"
22142247
headers = {
22152248
"Authorization": f"Bearer {token}",
22162249
"Content-Type": "application/json"
22172250
}
22182251

2219-
req = urllib.request.Request(url, method="POST", headers=headers, data=b"")
2252+
req = urllib.request.Request(url, method="GET", headers=headers, data=b"")
22202253
try:
22212254
with urllib.request.urlopen(req) as response:
22222255
response_data = json.loads(response.read().decode())
2223-
# happy path
2224-
if 'downloadURL' in response_data:
2225-
return response_data['downloadURL']
2256+
2257+
if db_region is not None and len(db_region) > 0:
2258+
for datacenter in response_data:
2259+
if 'secureBundleUrl' in datacenter and datacenter['secureBundleUrl']:
2260+
# happy path
2261+
if db_region == datacenter['region']:
2262+
return datacenter['secureBundleUrl']
2263+
else:
2264+
log.warning("Astra DB cluster region [%s] does not match input [%s]", datacenter['region'], db_region)
2265+
else:
2266+
raise ValueError("'secureBundleUrl' is missing from the Astra DB API response")
2267+
else:
2268+
# Return just the primary region SCB URL
2269+
if 'secureBundleUrl' in response_data[0] and response_data[0]['secureBundleUrl']:
2270+
return response_data[0]['secureBundleUrl']
2271+
else:
2272+
raise ValueError("'secureBundleUrl' is missing from the Astra DB API response for the primary region")
2273+
22262274
# handle errors
22272275
if 'errors' in response_data:
22282276
raise Exception(response_data['errors'][0]['message'])

0 commit comments

Comments
 (0)