-
Notifications
You must be signed in to change notification settings - Fork 3
/
zvm.py
273 lines (208 loc) · 9.47 KB
/
zvm.py
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
import string
import random
import traceback
import os
import time
from copy import deepcopy
from typing import Union
import requests
from bson.json_util import loads
''' zvm - programmatically interact with ZTF Variable Marshal's API '''
__version__ = '0.0.1'
Num = Union[int, float]
QueryPart = Union['task', 'result']
Method = Union['get', 'post', 'put', 'patch', 'delete']
class zvm(object):
"""
zvm :: programmatically interact with ZTF Variable Marshal's API
"""
# def __init__(self, protocol='http', host='127.0.0.1', port=8000, verbose=False,
# username=None, password=None):
def __init__(self, protocol='https', host='skipper.caltech.edu', port=443, verbose=False,
username=None, password=None):
assert username is not None, 'username must be specified'
assert password is not None, 'password must be specified'
self.v = verbose
self.protocol = protocol
self.host = host
self.port = port
self.base_url = f'{self.protocol}://{self.host}:{self.port}'
self.username = username
self.password = password
self.session = requests.Session()
self.access_token = self.authenticate()
self.headers = {'Authorization': self.access_token}
self.methods = {'get': self.session.get,
'post': self.session.post,
'put': self.session.put,
'patch': self.session.patch,
'delete': self.session.delete}
# use with "with":
def __enter__(self):
# print('Starting')
return self
def __exit__(self, *exc):
# print('Finishing')
# run shut down procedure
self.close()
return False
def close(self):
"""
Shutdown session gracefully
:return:
"""
try:
self.session.close()
return True
except Exception as e:
if self.v:
print(e)
return False
def authenticate(self, retries: int = 3):
"""
Authenticate user, return access token
:return:
"""
for retry in range(retries):
# post username and password, get access token
auth = self.session.post(f'{self.base_url}/auth',
json={"username": self.username, "password": self.password,
"zvm.__version__": __version__})
if auth.status_code == requests.codes.ok:
if self.v:
print(auth.json())
# mimic a web login, too
auth_web = self.session.post(f'{self.base_url}/login',
json={"username": self.username, "password": self.password,
"zvm.__version__": __version__})
if 'token' not in auth.json():
print('Authentication failed')
raise Exception(auth.json()['message'])
access_token = auth.json()['token']
if self.v:
print('Successfully authenticated')
return access_token
else:
# bad status code? sleep before retrying, maybe no connections available due to high load
time.sleep(0.5)
def api(self, data: dict, endpoint: str = None, method: Method = None, timeout: Num = 30, retries: int = 3):
try:
assert endpoint is not None, 'endpoint not specified'
# assert data is not None, 'api call not specified'
assert method in ['get', 'post', 'put', 'patch', 'delete'], f'unsupported method: {method}'
cookies = {'jwt_token': self.access_token, 'user_id': self.username}
for retry in range(retries):
if method.lower() != 'get':
resp = self.methods[method.lower()](os.path.join(self.base_url, endpoint),
json=data, headers=self.headers, timeout=timeout,
cookies=cookies)
else:
resp = self.methods[method.lower()](os.path.join(self.base_url, endpoint),
params=data, headers=self.headers, timeout=timeout,
cookies=cookies)
# print(resp.text)
if resp.status_code == requests.codes.ok:
return loads(resp.text)
else:
# bad status code? sleep before retrying, maybe no connections available due to high load
time.sleep(0.5)
except Exception as _e:
_err = traceback.format_exc()
return {'status': 'failed', 'message': _err}
def query(self, query, timeout: Num = 5*3600, retries: int = 3):
try:
_query = deepcopy(query)
# by default, [unless enqueue_only is requested]
# all queries are not registered in the db and the task/results are stored on disk as json files
# giving a significant execution speed up. this behaviour can be overridden.
if ('kwargs' in _query) and ('enqueue_only' in _query['kwargs']) and _query['kwargs']['enqueue_only']:
save = True
else:
save = _query['kwargs']['save'] if (('kwargs' in _query) and ('save' in _query['kwargs'])) else False
if save:
if 'kwargs' not in _query:
_query['kwargs'] = dict()
if '_id' not in _query['kwargs']:
# generate a unique hash id and store it in query if saving query in db on Kowalski is requested
_id = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits)
for _ in range(32)).lower()
_query['kwargs']['_id'] = _id
for retry in range(retries):
resp = self.session.put(os.path.join(self.base_url, 'query'),
json=_query, headers=self.headers, timeout=timeout,
cookies={'jwt_token': self.access_token, 'user_id': self.username})
# print(resp.text)
if resp.status_code == requests.codes.ok:
return loads(resp.text)
else:
# bad status code? sleep before retrying, maybe no connections available due to high load
time.sleep(0.5)
except Exception as _e:
_err = traceback.format_exc()
return {'status': 'failed', 'message': _err}
def get_query(self, query_id: str, part: QueryPart = 'result', retries: int = 3):
"""
Fetch json for task or result by query id
:param query_id:
:param part:
:param retries:
:return:
"""
try:
for retry in range(retries):
result = self.session.post(os.path.join(self.base_url, 'query'),
json={'task_id': query_id, 'part': part}, headers=self.headers)
if result.status_code == requests.codes.ok:
_result = {'task_id': query_id, 'result': loads(result.text)}
return _result
else:
# bad status code? sleep before retrying, maybe no connections available due to high load
time.sleep(0.5)
except Exception as _e:
_err = traceback.format_exc()
return {'status': 'failed', 'message': _err}
def delete_query(self, query_id: str, retries: int = 3):
"""
Delete query by query_id
:param query_id:
:param retries:
:return:
"""
try:
for retry in range(retries):
result = self.session.delete(os.path.join(self.base_url, 'query'),
json={'task_id': query_id}, headers=self.headers)
if result.status_code == requests.codes.ok:
_result = loads(result.text)
return _result
else:
# bad status code? sleep before retrying, maybe no connections available due to high load
time.sleep(0.5)
except Exception as _e:
_err = traceback.format_exc()
return {'status': 'failed', 'message': _err}
def check_connection(self, collection='sources') -> bool:
"""
Check connection to ZVM with a trivial query
:return: True if connection ok, False otherwise
"""
try:
_query = {"query_type": "find",
"query": {
"catalog": collection,
"filter": {},
"projection": {'_id': 1}
},
"kwargs": {"limit": 1, "save": False}
}
if self.v:
print(_query)
_result = self.query(query=_query, timeout=3)
if self.v:
print(_result)
status = _result.get('result', dict()).get('status', None)
return True if status == 'done' else False
except Exception as _e:
_err = traceback.format_exc()
print(_err)
return False