forked from singlestore-labs/singlestoredb-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmanager.py
More file actions
302 lines (253 loc) · 8.82 KB
/
manager.py
File metadata and controls
302 lines (253 loc) · 8.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
#!/usr/bin/env python
"""SingleStoreDB Base Manager."""
import os
import sys
import time
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
from typing import Union
from urllib.parse import urljoin
import jwt
import requests
from .. import config
from ..exceptions import ManagementError
from .utils import get_token
def set_organization(kwargs: Dict[str, Any]) -> None:
"""Set the organization ID in the dictionary."""
if kwargs.get('params', {}).get('organizationID', None):
return
org = os.environ.get('SINGLESTOREDB_ORGANIZATION')
if org:
if 'params' not in kwargs:
kwargs['params'] = {}
kwargs['params']['organizationID'] = org
def is_jwt(token: str) -> bool:
"""Is the given token a JWT?"""
try:
jwt.decode(token, options={'verify_signature': False})
return True
except jwt.DecodeError:
return False
class Manager(object):
"""SingleStoreDB manager base class."""
#: Management API version if none is specified.
default_version = config.get_option('management.version') or 'v1'
#: Base URL if none is specified.
default_base_url = config.get_option('management.base_url') \
or 'https://api.singlestore.com'
#: Object type
obj_type = ''
def __init__(
self, access_token: Optional[str] = None, version: Optional[str] = None,
base_url: Optional[str] = None, *, organization_id: Optional[str] = None,
):
from .. import __version__ as client_version
new_access_token = (
access_token or get_token()
)
if not new_access_token:
raise ManagementError(msg='No management token was configured.')
self._is_jwt = not access_token and new_access_token and is_jwt(new_access_token)
self._sess = requests.Session()
self._sess.headers.update({
'Authorization': f'Bearer {new_access_token}',
'Content-Type': 'application/json',
'Accept': 'application/json',
'User-Agent': f'SingleStoreDB-Python/{client_version}',
})
self._base_url = urljoin(
base_url
or config.get_option('management.base_url')
or type(self).default_base_url,
version or type(self).default_version,
) + '/'
self._params: Dict[str, str] = {}
if organization_id:
self._params['organizationID'] = organization_id
def _check(
self, res: requests.Response, url: str, params: Dict[str, Any],
) -> requests.Response:
"""
Check the HTTP response status code and raise an exception as needed.
Parameters
----------
res : requests.Response
HTTP response to check
Returns
-------
requests.Response
"""
if config.get_option('debug.queries'):
print(os.path.join(self._base_url, url), params, file=sys.stderr)
if res.status_code >= 400:
txt = res.text.strip()
msg = f'{txt}: /{url}'
if params:
new_params = params.copy()
if 'json' in new_params:
for k, v in new_params['json'].items():
if 'password' in k.lower() and v:
new_params['json'][k] = '*' * len(v)
msg += ': {}'.format(str(new_params))
raise ManagementError(errno=res.status_code, msg=msg, response=txt)
return res
def _doit(
self,
method: str,
path: str,
*args: Any,
**kwargs: Any,
) -> requests.Response:
"""Perform HTTP request."""
# Refresh the JWT as needed
if self._is_jwt:
self._sess.headers.update({'Authorization': f'Bearer {get_token()}'})
return getattr(self._sess, method.lower())(
urljoin(self._base_url, path), *args, **kwargs,
)
def _get(self, path: str, *args: Any, **kwargs: Any) -> requests.Response:
"""
Invoke a GET request.
Parameters
----------
path : str
Path of the resource
*args : positional arguments, optional
Arguments to add to the GET request
**kwargs : keyword arguments, optional
Keyword arguments to add to the GET request
Returns
-------
requests.Response
"""
if self._params:
kwargs.setdefault('params', {}).update(self._params)
set_organization(kwargs)
return self._check(self._doit('get', path, *args, **kwargs), path, kwargs)
def _post(self, path: str, *args: Any, **kwargs: Any) -> requests.Response:
"""
Invoke a POST request.
Parameters
----------
path : str
Path of the resource
*args : positional arguments, optional
Arguments to add to the POST request
**kwargs : keyword arguments, optional
Keyword arguments to add to the POST request
Returns
-------
requests.Response
"""
if self._params:
kwargs.setdefault('params', {}).update(self._params)
set_organization(kwargs)
return self._check(self._doit('post', path, *args, **kwargs), path, kwargs)
def _put(self, path: str, *args: Any, **kwargs: Any) -> requests.Response:
"""
Invoke a PUT request.
Parameters
----------
path : str
Path of the resource
*args : positional arguments, optional
Arguments to add to the POST request
**kwargs : keyword arguments, optional
Keyword arguments to add to the POST request
Returns
-------
requests.Response
"""
if self._params:
kwargs.setdefault('params', {}).update(self._params)
set_organization(kwargs)
return self._check(self._doit('put', path, *args, **kwargs), path, kwargs)
def _delete(self, path: str, *args: Any, **kwargs: Any) -> requests.Response:
"""
Invoke a DELETE request.
Parameters
----------
path : str
Path of the resource
*args : positional arguments, optional
Arguments to add to the DELETE request
**kwargs : keyword arguments, optional
Keyword arguments to add to the DELETE request
Returns
-------
requests.Response
"""
if self._params:
kwargs.setdefault('params', {}).update(self._params)
set_organization(kwargs)
return self._check(self._doit('delete', path, *args, **kwargs), path, kwargs)
def _patch(self, path: str, *args: Any, **kwargs: Any) -> requests.Response:
"""
Invoke a PATCH request.
Parameters
----------
path : str
Path of the resource
*args : positional arguments, optional
Arguments to add to the PATCH request
**kwargs : keyword arguments, optional
Keyword arguments to add to the PATCH request
Returns
-------
requests.Response
"""
if self._params:
kwargs.setdefault('params', {}).update(self._params)
set_organization(kwargs)
return self._check(self._doit('patch', path, *args, **kwargs), path, kwargs)
def _wait_on_state(
self,
out: Any,
state: Union[str, List[str]],
interval: int = 20,
timeout: int = 600,
) -> Any:
"""
Wait on server state before continuing.
Parameters
----------
out : Any
Current object
state : str or List[str]
State(s) to wait for
interval : int, optional
Interval between each server poll
timeout : int, optional
Maximum time to wait before raising an exception
Raises
------
ManagementError
If timeout is reached
Returns
-------
Same object type as `out`
"""
states = [
x.lower().strip()
for x in (isinstance(state, str) and [state] or state)
]
if getattr(out, 'state', None) is None:
raise ManagementError(
msg='{} object does not have a `state` attribute'.format(
type(out).__name__,
),
)
while True:
if getattr(out, 'state').lower() in states:
break
if timeout <= 0:
raise ManagementError(
msg=f'Exceeded waiting time for {self.obj_type} to become '
'{}.'.format(', '.join(states)),
)
time.sleep(interval)
timeout -= interval
out = getattr(self, f'get_{self.obj_type}')(out.id)
return out