Debian Codegraph @

cassandra/datastax/cloud/__init__.py

raw
1 # Copyright DataStax, Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import os
16 import logging
17 import json
18 import sys
19 import tempfile
20 import shutil
21 from urllib.request import urlopen
22
23 _HAS_SSL = True
24 try:
25 from ssl import SSLContext, PROTOCOL_TLS, CERT_REQUIRED
26 except:
27 _HAS_SSL = False
28
29 from zipfile import ZipFile
30
31 # 2.7 vs 3.x
32 try:
33 from zipfile import BadZipFile
34 except:
35 from zipfile import BadZipfile as BadZipFile
36
37 from cassandra import DriverException
38
39 log = logging.getLogger(__name__)
40
41 __all__ = ['get_cloud_config']
42
43 DATASTAX_CLOUD_PRODUCT_TYPE = "DATASTAX_APOLLO"
44
45
46 class CloudConfig(object):
47
48 username = None
49 password = None
50 host = None
51 port = None
52 keyspace = None
53 local_dc = None
54 ssl_context = None
55
56 sni_host = None
57 sni_port = None
58 host_ids = None
59
60 @classmethod
61 def from_dict(cls, d):
62 c = cls()
63
64 c.port = d.get('port', None)
65 try:
66 c.port = int(d['port'])
67 except:
68 pass
69
70 c.username = d.get('username', None)
71 c.password = d.get('password', None)
72 c.host = d.get('host', None)
73 c.keyspace = d.get('keyspace', None)
74 c.local_dc = d.get('localDC', None)
75
76 return c
77
78
79 def get_cloud_config(cloud_config, create_pyopenssl_context=False):
80 if not _HAS_SSL:
81 raise DriverException("A Python installation with SSL is required to connect to a cloud cluster.")
82
83 if 'secure_connect_bundle' not in cloud_config:
84 raise ValueError("The cloud config doesn't have a secure_connect_bundle specified.")
85
86 try:
87 config = read_cloud_config_from_zip(cloud_config, create_pyopenssl_context)
88 except BadZipFile:
89 raise ValueError("Unable to open the zip file for the cloud config. Check your secure connect bundle.")
90
91 config = read_metadata_info(config, cloud_config)
92 if create_pyopenssl_context:
93 config.ssl_context = config.pyopenssl_context
94 return config
95
96
97 def read_cloud_config_from_zip(cloud_config, create_pyopenssl_context):
98 secure_bundle = cloud_config['secure_connect_bundle']
99 use_default_tempdir = cloud_config.get('use_default_tempdir', None)
100 with ZipFile(secure_bundle) as zipfile:
101 base_dir = tempfile.gettempdir() if use_default_tempdir else os.path.dirname(secure_bundle)
102 tmp_dir = tempfile.mkdtemp(dir=base_dir)
103 try:
104 zipfile.extractall(path=tmp_dir)
105 return parse_cloud_config(os.path.join(tmp_dir, 'config.json'), cloud_config, create_pyopenssl_context)
106 finally:
107 shutil.rmtree(tmp_dir)
108
109
110 def parse_cloud_config(path, cloud_config, create_pyopenssl_context):
111 with open(path, 'r') as stream:
112 data = json.load(stream)
113
114 config = CloudConfig.from_dict(data)
115 config_dir = os.path.dirname(path)
116
117 if 'ssl_context' in cloud_config:
118 config.ssl_context = cloud_config['ssl_context']
119 else:
120 # Load the ssl_context before we delete the temporary directory
121 ca_cert_location = os.path.join(config_dir, 'ca.crt')
122 cert_location = os.path.join(config_dir, 'cert')
123 key_location = os.path.join(config_dir, 'key')
124 # Regardless of if we create a pyopenssl context, we still need the builtin one
125 # to connect to the metadata service
126 config.ssl_context = _ssl_context_from_cert(ca_cert_location, cert_location, key_location)
127 if create_pyopenssl_context:
128 config.pyopenssl_context = _pyopenssl_context_from_cert(ca_cert_location, cert_location, key_location)
129
130 return config
131
132
133 def read_metadata_info(config, cloud_config):
134 url = "https://{}:{}/metadata".format(config.host, config.port)
135 timeout = cloud_config['connect_timeout'] if 'connect_timeout' in cloud_config else 5
136 try:
137 response = urlopen(url, context=config.ssl_context, timeout=timeout)
138 except Exception as e:
139 log.exception(e)
140 raise DriverException("Unable to connect to the metadata service at %s. "
141 "Check the cluster status in the cloud console. " % url)
142
143 if response.code != 200:
144 raise DriverException(("Error while fetching the metadata at: %s. "
145 "The service returned error code %d." % (url, response.code)))
146 return parse_metadata_info(config, response.read().decode('utf-8'))
147
148
149 def parse_metadata_info(config, http_data):
150 try:
151 data = json.loads(http_data)
152 except:
153 msg = "Failed to load cluster metadata"
154 raise DriverException(msg)
155
156 contact_info = data['contact_info']
157 config.local_dc = contact_info['local_dc']
158
159 proxy_info = contact_info['sni_proxy_address'].split(':')
160 config.sni_host = proxy_info[0]
161 try:
162 config.sni_port = int(proxy_info[1])
163 except:
164 config.sni_port = 9042
165
166 config.host_ids = [host_id for host_id in contact_info['contact_points']]
167
168 return config
169
170
171 def _ssl_context_from_cert(ca_cert_location, cert_location, key_location):
172 ssl_context = SSLContext(PROTOCOL_TLS)
173 ssl_context.load_verify_locations(ca_cert_location)
174 ssl_context.verify_mode = CERT_REQUIRED
175 ssl_context.load_cert_chain(certfile=cert_location, keyfile=key_location)
176
177 return ssl_context
178
179
180 def _pyopenssl_context_from_cert(ca_cert_location, cert_location, key_location):
181 try:
182 from OpenSSL import SSL
183 except ImportError as e:
184 raise ImportError(
185 "PyOpenSSL must be installed to connect to Astra with the Eventlet or Twisted event loops")\
186 .with_traceback(e.__traceback__)
187 ssl_context = SSL.Context(SSL.TLSv1_METHOD)
188 ssl_context.set_verify(SSL.VERIFY_PEER, callback=lambda _1, _2, _3, _4, ok: ok)
189 ssl_context.use_certificate_file(cert_location)
190 ssl_context.use_privatekey_file(key_location)
191 ssl_context.load_verify_locations(ca_cert_location)
192
193 return ssl_context