isabl-cli 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- isabl_cli/VERSION +1 -0
- isabl_cli/__init__.py +25 -0
- isabl_cli/__main__.py +13 -0
- isabl_cli/api.py +815 -0
- isabl_cli/app.py +1926 -0
- isabl_cli/batch_systems/__init__.py +7 -0
- isabl_cli/batch_systems/local.py +44 -0
- isabl_cli/batch_systems/lsf.py +175 -0
- isabl_cli/batch_systems/sge.py +194 -0
- isabl_cli/batch_systems/slurm.py +180 -0
- isabl_cli/cli.py +91 -0
- isabl_cli/commands.py +480 -0
- isabl_cli/data/README.md +7 -0
- isabl_cli/data.py +1240 -0
- isabl_cli/exceptions.py +48 -0
- isabl_cli/factories.py +99 -0
- isabl_cli/options.py +407 -0
- isabl_cli/settings.py +315 -0
- isabl_cli/signals.py +23 -0
- isabl_cli/test/__init__.py +1 -0
- isabl_cli/test/utils.py +159 -0
- isabl_cli/utils.py +346 -0
- isabl_cli/validators.py +100 -0
- isabl_cli-0.1.0.dist-info/LICENSE.md +23 -0
- isabl_cli-0.1.0.dist-info/METADATA +40 -0
- isabl_cli-0.1.0.dist-info/RECORD +43 -0
- isabl_cli-0.1.0.dist-info/WHEEL +5 -0
- isabl_cli-0.1.0.dist-info/entry_points.txt +2 -0
- isabl_cli-0.1.0.dist-info/top_level.txt +2 -0
- tests/__init__.py +0 -0
- tests/conftest.py +26 -0
- tests/test_api.py +124 -0
- tests/test_app.py +1254 -0
- tests/test_batch_systems.py +87 -0
- tests/test_cli.py +34 -0
- tests/test_commands.py +341 -0
- tests/test_data.py +450 -0
- tests/test_options.py +28 -0
- tests/test_signals.py +59 -0
- tests/test_testutils.py +24 -0
- tests/test_utils.py +154 -0
- tests/test_validators.py +128 -0
- tests/test_version.py +8 -0
isabl_cli/api.py
ADDED
|
@@ -0,0 +1,815 @@
|
|
|
1
|
+
"""Logic to interact with API."""
|
|
2
|
+
|
|
3
|
+
from functools import lru_cache
|
|
4
|
+
from itertools import islice
|
|
5
|
+
from os import environ
|
|
6
|
+
from os.path import basename
|
|
7
|
+
from urllib.parse import urljoin
|
|
8
|
+
from urllib.parse import urlparse
|
|
9
|
+
import collections
|
|
10
|
+
import json
|
|
11
|
+
import shutil
|
|
12
|
+
import subprocess
|
|
13
|
+
import sys
|
|
14
|
+
import time
|
|
15
|
+
import traceback
|
|
16
|
+
|
|
17
|
+
from munch import Munch
|
|
18
|
+
from requests.packages.urllib3.exceptions import InsecureRequestWarning
|
|
19
|
+
from six import iteritems
|
|
20
|
+
import analytics
|
|
21
|
+
import click
|
|
22
|
+
import requests
|
|
23
|
+
|
|
24
|
+
from isabl_cli import exceptions
|
|
25
|
+
from isabl_cli import utils
|
|
26
|
+
from isabl_cli.settings import import_from_string
|
|
27
|
+
from isabl_cli.settings import system_settings
|
|
28
|
+
from isabl_cli.settings import user_settings
|
|
29
|
+
|
|
30
|
+
requests.packages.urllib3.disable_warnings( # pylint: disable=E1101
|
|
31
|
+
InsecureRequestWarning
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def isablfy(obj):
|
|
36
|
+
"""Convert objects to IsablDicts recursively."""
|
|
37
|
+
if isinstance(obj, dict):
|
|
38
|
+
if obj.get("model_name") == "Experiment":
|
|
39
|
+
factory = Experiment
|
|
40
|
+
elif obj.get("model_name") == "Analysis" or "wait_time" in obj:
|
|
41
|
+
factory = Analysis
|
|
42
|
+
elif obj.get("model_name") == "Assembly":
|
|
43
|
+
factory = Assembly
|
|
44
|
+
else:
|
|
45
|
+
factory = IsablDict
|
|
46
|
+
return factory((k, isablfy(v)) for k, v in iteritems(obj))
|
|
47
|
+
elif isinstance(obj, (list, tuple)):
|
|
48
|
+
return type(obj)(isablfy(v) for v in obj)
|
|
49
|
+
else:
|
|
50
|
+
return obj
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class IsablDict(Munch):
|
|
54
|
+
def __init__(self, *args, **kwargs):
|
|
55
|
+
"""If first argument is int or str, use it to retrieve an instance."""
|
|
56
|
+
if len(args) == 1 and isinstance(args[0], (str, int)):
|
|
57
|
+
super().__init__(isablfy(get_instance(self.api_endpoint, args[0])))
|
|
58
|
+
else:
|
|
59
|
+
super().__init__(*args, **kwargs)
|
|
60
|
+
|
|
61
|
+
@classmethod
|
|
62
|
+
def fromDict(cls, d):
|
|
63
|
+
"""Transform a dictionary into IsablDicts recursively."""
|
|
64
|
+
return isablfy(d)
|
|
65
|
+
|
|
66
|
+
def get(self, k, default=None):
|
|
67
|
+
"""Check first if k is a custom field."""
|
|
68
|
+
if self._is_custom_field(k):
|
|
69
|
+
return self.custom_fields.get(k, default)
|
|
70
|
+
return super().get(k, default)
|
|
71
|
+
|
|
72
|
+
def pop(self, k, default=None):
|
|
73
|
+
"""Check first if k is a custom field."""
|
|
74
|
+
if self._is_custom_field(k):
|
|
75
|
+
return self.custom_fields.pop(k, default)
|
|
76
|
+
return super().pop(k, default)
|
|
77
|
+
|
|
78
|
+
def _is_custom_field(self, k):
|
|
79
|
+
return k != "custom_fields" and k in self.get("custom_fields", {})
|
|
80
|
+
|
|
81
|
+
def __contains__(self, k):
|
|
82
|
+
if self._is_custom_field(k):
|
|
83
|
+
return True
|
|
84
|
+
return dict.__contains__(self, k)
|
|
85
|
+
|
|
86
|
+
def __setitem__(self, k, v):
|
|
87
|
+
if self._is_custom_field(k):
|
|
88
|
+
self.custom_fields[k] = v
|
|
89
|
+
return super().__setitem__(k, v)
|
|
90
|
+
|
|
91
|
+
def __getitem__(self, k):
|
|
92
|
+
if self._is_custom_field(k):
|
|
93
|
+
return self.custom_fields[k]
|
|
94
|
+
return super().__getitem__(k)
|
|
95
|
+
|
|
96
|
+
def __delitem__(self, k):
|
|
97
|
+
if self._is_custom_field(k):
|
|
98
|
+
return self.custom_fields.__delitem__(k)
|
|
99
|
+
return super().__delitem__(k)
|
|
100
|
+
|
|
101
|
+
def __dir__(self):
|
|
102
|
+
return super(dict, self).__dir__() + list( # pylint: disable=bad-super-call
|
|
103
|
+
self.get("custom_fields", {}).keys()
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
def __repr__(self):
|
|
107
|
+
identifier = getattr(
|
|
108
|
+
self, "system_id", getattr(self, "slug", getattr(self, "pk", None))
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
return (
|
|
112
|
+
f"{getattr(self, 'model_name', self.__class__.__name__)}({identifier})"
|
|
113
|
+
if identifier
|
|
114
|
+
else super().__repr__()
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class Analysis(IsablDict):
|
|
119
|
+
|
|
120
|
+
api_endpoint = "analyses"
|
|
121
|
+
|
|
122
|
+
def __repr__(self):
|
|
123
|
+
"""Get better representation for analyses."""
|
|
124
|
+
identifier = getattr(self, "pk", None)
|
|
125
|
+
application = getattr(self, "application", {})
|
|
126
|
+
return (
|
|
127
|
+
super().__repr__()
|
|
128
|
+
if not identifier
|
|
129
|
+
else (
|
|
130
|
+
f"{application.get('name', 'Analysis')} "
|
|
131
|
+
f"{application.get('version', 'No Version Available')}"
|
|
132
|
+
f"({identifier})"
|
|
133
|
+
)
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class Assembly(IsablDict):
|
|
138
|
+
|
|
139
|
+
api_endpoint = "assemblies"
|
|
140
|
+
|
|
141
|
+
def __repr__(self): # pragma: no cover
|
|
142
|
+
"""Get better representation for assemblies."""
|
|
143
|
+
identifier = getattr(self, "name", getattr(self, "pk", None))
|
|
144
|
+
return super().__repr__() if not identifier else f"Assembly({identifier})"
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class Experiment(IsablDict):
|
|
148
|
+
|
|
149
|
+
api_endpoint = "experiments"
|
|
150
|
+
|
|
151
|
+
def get_fastq(self):
|
|
152
|
+
"""
|
|
153
|
+
Get experiment fastq R1 and R2 files.
|
|
154
|
+
|
|
155
|
+
Raises:
|
|
156
|
+
MissingDataError: if number of R1 and R2 files is not the same.
|
|
157
|
+
|
|
158
|
+
Returns:
|
|
159
|
+
tuple: list of R1 fastq, list of R2.
|
|
160
|
+
"""
|
|
161
|
+
read_1, read_2 = [], []
|
|
162
|
+
|
|
163
|
+
for i in self.raw_data:
|
|
164
|
+
if i["file_type"] == "FASTQ_R1":
|
|
165
|
+
read_1.append(i["file_url"])
|
|
166
|
+
elif i["file_type"] == "FASTQ_R2":
|
|
167
|
+
read_2.append(i["file_url"])
|
|
168
|
+
|
|
169
|
+
if read_2 and len(read_1) != len(read_2): # pragma: no cover
|
|
170
|
+
raise exceptions.MissingDataError(
|
|
171
|
+
f"The # of read 1 files ({len(read_1)}) "
|
|
172
|
+
f"and read 2 ({len(read_2)}) should be the same "
|
|
173
|
+
f"for paired-end sequencing, found: {read_1 + read_2}"
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
return sorted(read_1), sorted(read_2)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def chunks(array, size):
|
|
180
|
+
"""Yield successive n-sized chunks from ``array``."""
|
|
181
|
+
array = iter(array)
|
|
182
|
+
return iter(lambda: tuple(islice(array, size)), ())
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def get_api_url(url):
|
|
186
|
+
"""Get an API URL."""
|
|
187
|
+
# hmm, don't like this messing around with slashes
|
|
188
|
+
base_url = environ.get("ISABL_API_URL", "http://localhost:8000/api/v1/")
|
|
189
|
+
base_url = base_url if base_url[-1] == "/" else f"{base_url}/"
|
|
190
|
+
|
|
191
|
+
if not url.startswith(base_url):
|
|
192
|
+
url = urljoin(base_url, url[1:] if url.startswith("/") else url)
|
|
193
|
+
|
|
194
|
+
return url
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def retry_request(method, **kwargs):
|
|
198
|
+
"""Retry request operation multiple times."""
|
|
199
|
+
for i in [0.2, 1, 5, 10, 60, 90, 120, 300, 900]: # attempt some retries
|
|
200
|
+
try:
|
|
201
|
+
error = None
|
|
202
|
+
response = getattr(requests, method)(verify=False, **kwargs)
|
|
203
|
+
except requests.exceptions.RequestException as request_error: # pragma: no cover
|
|
204
|
+
error = request_error
|
|
205
|
+
response = None
|
|
206
|
+
|
|
207
|
+
if response is not None and not str(response.status_code).startswith("50"):
|
|
208
|
+
break
|
|
209
|
+
else: # pragma: no cover
|
|
210
|
+
msg = f"Request failed with error: {error}, retrying in {i}s..."
|
|
211
|
+
click.secho(msg, fg="yellow", err=True)
|
|
212
|
+
time.sleep(i)
|
|
213
|
+
|
|
214
|
+
return response
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
@lru_cache(None)
|
|
218
|
+
def get_token_headers():
|
|
219
|
+
"""Get an API token and store it in user's home directory."""
|
|
220
|
+
headers = {"Authorization": f"Token {user_settings.api_token}"}
|
|
221
|
+
auth_url = get_api_url("/rest-auth/user/")
|
|
222
|
+
response = retry_request("get", url=auth_url, headers=headers)
|
|
223
|
+
|
|
224
|
+
try:
|
|
225
|
+
assert "username" in response.json()
|
|
226
|
+
except (json.JSONDecodeError, AssertionError):
|
|
227
|
+
testing = (
|
|
228
|
+
basename(sys.argv[0]) in ("pytest", "py.test")
|
|
229
|
+
) or "pytest" in sys.modules
|
|
230
|
+
|
|
231
|
+
response = retry_request(
|
|
232
|
+
"post",
|
|
233
|
+
url=get_api_url("/rest-auth/login/"),
|
|
234
|
+
data={
|
|
235
|
+
"username": click.prompt("username", type=str, hide_input=False)
|
|
236
|
+
if not testing
|
|
237
|
+
else "admin",
|
|
238
|
+
"password": click.prompt("password", type=str, hide_input=True)
|
|
239
|
+
if not testing
|
|
240
|
+
else "admin",
|
|
241
|
+
},
|
|
242
|
+
)
|
|
243
|
+
|
|
244
|
+
if (
|
|
245
|
+
not response.ok and "non_field_errors" in response.text and not testing
|
|
246
|
+
): # pragma: no cover
|
|
247
|
+
click.secho("\n".join(response.json()["non_field_errors"]), err=True, fg="red")
|
|
248
|
+
get_token_headers.cache_clear()
|
|
249
|
+
return get_token_headers()
|
|
250
|
+
elif not response.ok: # pragma: no cover
|
|
251
|
+
click.secho(f"Request Error: {response.url}", err=True, fg="red")
|
|
252
|
+
response.raise_for_status()
|
|
253
|
+
|
|
254
|
+
user_settings.api_token = response.json()["key"] # pylint: disable=invalid-name
|
|
255
|
+
headers = {"Authorization": f"Token {user_settings.api_token}"}
|
|
256
|
+
click.secho("Successful authorization! Token stored.", fg="green")
|
|
257
|
+
|
|
258
|
+
# Authenticate user for analytics
|
|
259
|
+
send_analytics(user=response.json())
|
|
260
|
+
|
|
261
|
+
return headers
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def send_analytics(user):
|
|
265
|
+
"""Send analytics about the identity and group of the user."""
|
|
266
|
+
from isabl_cli import __version__
|
|
267
|
+
|
|
268
|
+
if user.get("username"):
|
|
269
|
+
username = user["username"]
|
|
270
|
+
api_url = get_api_url("/")
|
|
271
|
+
if "localhost" in api_url or "0.0.0.0" in api_url or "isabl-api" in api_url:
|
|
272
|
+
domain = urlparse(api_url).netloc
|
|
273
|
+
subdomain = ""
|
|
274
|
+
group_id = "DEV"
|
|
275
|
+
else:
|
|
276
|
+
subdomain, domain, *_, = urlparse(api_url).netloc.split(".")
|
|
277
|
+
group_id = f"{subdomain.upper()} {domain.upper()}"
|
|
278
|
+
|
|
279
|
+
analytics.identify(username, user)
|
|
280
|
+
analytics.group(
|
|
281
|
+
username,
|
|
282
|
+
group_id,
|
|
283
|
+
{
|
|
284
|
+
"subdomain": subdomain,
|
|
285
|
+
"domain": domain,
|
|
286
|
+
"component": "cli",
|
|
287
|
+
"version": __version__,
|
|
288
|
+
},
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def api_request(method, url, authenticate=True, **kwargs):
|
|
293
|
+
"""Perform any request operation using a naive retry implementation."""
|
|
294
|
+
kwargs["params"] = kwargs.get("params", {})
|
|
295
|
+
kwargs["params"]["format"] = "json"
|
|
296
|
+
kwargs["url"] = get_api_url(url)
|
|
297
|
+
|
|
298
|
+
if authenticate:
|
|
299
|
+
kwargs["headers"] = get_token_headers()
|
|
300
|
+
|
|
301
|
+
response = retry_request(method, **kwargs)
|
|
302
|
+
|
|
303
|
+
if not response.ok:
|
|
304
|
+
try:
|
|
305
|
+
msg = click.style(str(response.json()), fg="red")
|
|
306
|
+
except Exception: # pylint: disable=broad-except
|
|
307
|
+
msg = ""
|
|
308
|
+
|
|
309
|
+
click.echo(f"Request Error: {response.url}\n{msg}", err=True)
|
|
310
|
+
response.raise_for_status()
|
|
311
|
+
|
|
312
|
+
return response
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def process_api_filters(**filters):
|
|
316
|
+
"""
|
|
317
|
+
Process filters for API.
|
|
318
|
+
|
|
319
|
+
Arguments:
|
|
320
|
+
filters (dict): name, value pairs for API filtering.
|
|
321
|
+
|
|
322
|
+
Returns:
|
|
323
|
+
dict: a `requests` formatted `params` dict.
|
|
324
|
+
"""
|
|
325
|
+
filters = filters or {}
|
|
326
|
+
filters_dict = {}
|
|
327
|
+
|
|
328
|
+
for key, value in filters.items():
|
|
329
|
+
key = key.replace(".", "__")
|
|
330
|
+
|
|
331
|
+
if isinstance(value, (str, int, float, type(None))):
|
|
332
|
+
if key == "fields" and "pk" not in value: # pk is required
|
|
333
|
+
value = ",".join(value.split(",") + ["pk"])
|
|
334
|
+
filters_dict[key] = value
|
|
335
|
+
elif isinstance(value, collections.abc.Iterable):
|
|
336
|
+
is_in = key.endswith("__in") or key.endswith("__in!")
|
|
337
|
+
value = list(map(str, value))
|
|
338
|
+
filters_dict[key] = [",".join(value)] if is_in else value
|
|
339
|
+
else: # pragma: no cover
|
|
340
|
+
raise click.UsageError(f"Invalid filter: {key}, {value}")
|
|
341
|
+
|
|
342
|
+
return filters_dict
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def iterate(url, **filters):
|
|
346
|
+
"""
|
|
347
|
+
Iterate through a paginated API endpoint and yield instances.
|
|
348
|
+
|
|
349
|
+
Arguments:
|
|
350
|
+
url (str): API URL address.
|
|
351
|
+
filters (dict): name, value pairs for API filtering.
|
|
352
|
+
|
|
353
|
+
Returns:
|
|
354
|
+
list: of objects in the 'results' key of the API response.
|
|
355
|
+
"""
|
|
356
|
+
limit = int(filters.get("limit", 5000)) # default limit to 5000 per hit
|
|
357
|
+
filters["limit"] = limit
|
|
358
|
+
filters = process_api_filters(**filters)
|
|
359
|
+
nexturl = url
|
|
360
|
+
objects = []
|
|
361
|
+
|
|
362
|
+
while nexturl:
|
|
363
|
+
filters = filters if nexturl == url else {} # nexturl includes params
|
|
364
|
+
response = api_request("get", url=nexturl, params=filters)
|
|
365
|
+
results = response.json()
|
|
366
|
+
nexturl = results["next"]
|
|
367
|
+
objects += results["results"]
|
|
368
|
+
|
|
369
|
+
if len(objects) >= limit: # pragma: no cover
|
|
370
|
+
message = f'retrieved {len(objects)} out of {results["count"]}...'
|
|
371
|
+
click.echo(message, err=True)
|
|
372
|
+
|
|
373
|
+
return objects
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def get_instance(endpoint, identifier, fields=None):
|
|
377
|
+
"""
|
|
378
|
+
Get database instance given any identifier.
|
|
379
|
+
|
|
380
|
+
Arguments:
|
|
381
|
+
identifier (str): a primary key, system_id, email or username.
|
|
382
|
+
endpoint (str): endpoint without API base URL (e.g. `analyses`).
|
|
383
|
+
fields (str): comma separated list of fields to be retrieved.
|
|
384
|
+
|
|
385
|
+
Returns:
|
|
386
|
+
types.SimpleNamespace: loaded with data returned from the API.
|
|
387
|
+
"""
|
|
388
|
+
return isablfy(
|
|
389
|
+
api_request(
|
|
390
|
+
"get",
|
|
391
|
+
url=f"/{endpoint}/{identifier}",
|
|
392
|
+
params={"fields": fields} if fields else {},
|
|
393
|
+
).json()
|
|
394
|
+
)
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def create_instance(endpoint, **data):
|
|
398
|
+
"""
|
|
399
|
+
Create database instance.
|
|
400
|
+
|
|
401
|
+
Arguments:
|
|
402
|
+
endpoint (str): endpoint without API base URL (e.g. `analyses`).
|
|
403
|
+
data (dict): fields to be created.
|
|
404
|
+
|
|
405
|
+
Returns:
|
|
406
|
+
types.SimpleNamespace: loaded with data returned from the API.
|
|
407
|
+
"""
|
|
408
|
+
return isablfy(api_request("post", url=endpoint, json=data).json())
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def patch_instance(endpoint, instance_id, **data):
|
|
412
|
+
"""
|
|
413
|
+
Patch database instance.
|
|
414
|
+
|
|
415
|
+
Arguments:
|
|
416
|
+
instance_id (str): a primary key, system_id, email or username.
|
|
417
|
+
endpoint (str): endpoint without API base URL (e.g. `analyses`).
|
|
418
|
+
data (dict): fields to be patched.
|
|
419
|
+
|
|
420
|
+
Returns:
|
|
421
|
+
types.SimpleNamespace: loaded with data returned from the API.
|
|
422
|
+
"""
|
|
423
|
+
from isabl_cli.data import symlink_analysis_to_targets
|
|
424
|
+
from isabl_cli.data import symlink_experiment_to_projects
|
|
425
|
+
from isabl_cli.data import trigger_analyses_merge
|
|
426
|
+
|
|
427
|
+
run_status_change_signals = False
|
|
428
|
+
run_data_import_signals = False
|
|
429
|
+
|
|
430
|
+
if (
|
|
431
|
+
endpoint == "analyses"
|
|
432
|
+
and data.get("status")
|
|
433
|
+
and Analysis(instance_id).status != data.get("status")
|
|
434
|
+
):
|
|
435
|
+
run_status_change_signals = True
|
|
436
|
+
|
|
437
|
+
if (
|
|
438
|
+
endpoint == "experiments"
|
|
439
|
+
and data.get("raw_data")
|
|
440
|
+
and Experiment(instance_id).raw_data != data.get("raw_data")
|
|
441
|
+
):
|
|
442
|
+
run_data_import_signals = True
|
|
443
|
+
|
|
444
|
+
instance = isablfy(
|
|
445
|
+
api_request("patch", url=f"/{endpoint}/{instance_id}", json=data).json()
|
|
446
|
+
)
|
|
447
|
+
|
|
448
|
+
if run_status_change_signals:
|
|
449
|
+
signals = system_settings.ON_STATUS_CHANGE + [trigger_analyses_merge]
|
|
450
|
+
|
|
451
|
+
if system_settings.CREATE_SYMLINKS:
|
|
452
|
+
signals.append(symlink_analysis_to_targets)
|
|
453
|
+
|
|
454
|
+
_run_signals("analyses", instance, signals)
|
|
455
|
+
|
|
456
|
+
if run_data_import_signals:
|
|
457
|
+
signals = system_settings.ON_DATA_IMPORT
|
|
458
|
+
|
|
459
|
+
if system_settings.CREATE_SYMLINKS:
|
|
460
|
+
signals.append(symlink_experiment_to_projects)
|
|
461
|
+
|
|
462
|
+
_run_signals("experiments", instance, signals)
|
|
463
|
+
|
|
464
|
+
return instance
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
def delete_instance(endpoint, identifier):
|
|
468
|
+
"""
|
|
469
|
+
Delete database instance.
|
|
470
|
+
|
|
471
|
+
Arguments:
|
|
472
|
+
identifier (str): a primary key, system_id, email or username.
|
|
473
|
+
endpoint (str): endpoint without API base URL (e.g. `analyses`).
|
|
474
|
+
"""
|
|
475
|
+
api_request("delete", url=f"/{endpoint}/{identifier}")
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def get_instances(endpoint, identifiers=None, verbose=True, **filters):
|
|
479
|
+
"""
|
|
480
|
+
Return instances from a list API endpoint.
|
|
481
|
+
|
|
482
|
+
If not `identifiers` and not `filters` retrieves all objects in database.
|
|
483
|
+
if `identifiers` and `filters`, identifieres might be filtered.
|
|
484
|
+
|
|
485
|
+
Arguments:
|
|
486
|
+
endpoint (str): endpoint without API base URL (e.g. `analyses`).
|
|
487
|
+
identifiers (list): List of identifiers.
|
|
488
|
+
filters (dict): name, value pairs for API filtering.
|
|
489
|
+
verbose (bool): print to stderr how many instances will be retrieved.
|
|
490
|
+
|
|
491
|
+
Raises:
|
|
492
|
+
click.UsageError: if string identifier and endpoint not in individuals,
|
|
493
|
+
samples or workdflows.
|
|
494
|
+
|
|
495
|
+
Returns:
|
|
496
|
+
list: of types.SimpleNamespace objects loaded with dicts from API.
|
|
497
|
+
"""
|
|
498
|
+
check_system_id = endpoint in {"individuals", "samples", "experiments"}
|
|
499
|
+
check_name = endpoint in {"assemblies", "techniques", "tags"}
|
|
500
|
+
instances = []
|
|
501
|
+
|
|
502
|
+
if verbose:
|
|
503
|
+
count = len(identifiers or [])
|
|
504
|
+
count += 0 if identifiers else get_instances_count(endpoint, **filters)
|
|
505
|
+
ids_msg = " at most " if identifiers else " " # ids may be in filters
|
|
506
|
+
count = f"Retrieving{ids_msg}{count} from {endpoint} API endpoint..."
|
|
507
|
+
click.echo(count, err=True)
|
|
508
|
+
|
|
509
|
+
if identifiers is None:
|
|
510
|
+
instances += iterate(endpoint, **filters)
|
|
511
|
+
else:
|
|
512
|
+
for chunk in chunks(identifiers or [], 10000):
|
|
513
|
+
filters["url"] = endpoint
|
|
514
|
+
primary_keys = set()
|
|
515
|
+
names = set()
|
|
516
|
+
ids = set()
|
|
517
|
+
|
|
518
|
+
for i in map(str, chunk):
|
|
519
|
+
if i.isdigit():
|
|
520
|
+
primary_keys.add(i)
|
|
521
|
+
elif check_name:
|
|
522
|
+
names.add(i)
|
|
523
|
+
elif check_system_id:
|
|
524
|
+
ids.add(i)
|
|
525
|
+
else: # pragma: no cover
|
|
526
|
+
msg = f"msg invalid identifier for {endpoint}: {i}"
|
|
527
|
+
raise click.UsageError(msg)
|
|
528
|
+
|
|
529
|
+
if primary_keys:
|
|
530
|
+
instances += iterate(**{"pk__in": ",".join(primary_keys), **filters})
|
|
531
|
+
|
|
532
|
+
if ids:
|
|
533
|
+
instances += iterate(**{"system_id__in": ",".join(ids), **filters})
|
|
534
|
+
|
|
535
|
+
if names:
|
|
536
|
+
instances += iterate(**{"name__in": ",".join(names), **filters})
|
|
537
|
+
|
|
538
|
+
return isablfy(instances)
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
def get_experiments(identifiers=None, **filters):
|
|
542
|
+
"""Get experiments give identifiers or filters."""
|
|
543
|
+
return get_instances("experiments", identifiers=identifiers, **filters)
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def get_analyses(identifiers=None, **filters):
|
|
547
|
+
"""Get analyses give identifiers or filters."""
|
|
548
|
+
return get_instances("analyses", identifiers=identifiers, **filters)
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
def get_projects(identifiers=None, **filters):
|
|
552
|
+
"""Get projects give identifiers or filters."""
|
|
553
|
+
return get_instances("projects", identifiers=identifiers, **filters)
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
def get_instances_count(endpoint, **filters):
|
|
557
|
+
"""
|
|
558
|
+
Return the count of a list url.
|
|
559
|
+
|
|
560
|
+
Arguments:
|
|
561
|
+
endpoint (str): endpoint without API base URL (e.g. `analyses`).
|
|
562
|
+
filters (dict): name, value pairs for API filtering.
|
|
563
|
+
|
|
564
|
+
Returns:
|
|
565
|
+
int: count of objects matching the provided filters.
|
|
566
|
+
"""
|
|
567
|
+
filters = process_api_filters(**filters)
|
|
568
|
+
filters["limit"] = 1
|
|
569
|
+
return int(api_request("get", url=endpoint, params=filters).json()["count"])
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
def get_tree(identifier):
|
|
573
|
+
"""Get everything for an individual."""
|
|
574
|
+
return isablfy(get_instance("individuals/tree", identifier))
|
|
575
|
+
|
|
576
|
+
|
|
577
|
+
def get_trees(identifiers=None, **filters):
|
|
578
|
+
"""Get everything for multiple individuals."""
|
|
579
|
+
return isablfy(get_instances("individuals/tree", identifiers, **filters))
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
def patch_analyses_status(analyses, status):
|
|
583
|
+
"""
|
|
584
|
+
Patch the `status` of multiple `analyses`.
|
|
585
|
+
|
|
586
|
+
Arguments:
|
|
587
|
+
analyses (list): of analyses instances.
|
|
588
|
+
status (str): status to be updated to.
|
|
589
|
+
|
|
590
|
+
Raises:
|
|
591
|
+
AssertionError: if status not in {'SUBMITTED', 'STAGED'}.
|
|
592
|
+
|
|
593
|
+
Returns:
|
|
594
|
+
list: of updated analyses.
|
|
595
|
+
"""
|
|
596
|
+
analyses = isablfy(analyses)
|
|
597
|
+
data = {"ids": [], "status": status, "ran_by": system_settings.api_username}
|
|
598
|
+
assert status in {"SUBMITTED", "STAGED"}, f"status not supported: {status}"
|
|
599
|
+
|
|
600
|
+
for i in analyses: # change locally, bulk_update doesn't return instances
|
|
601
|
+
i["status"] = status
|
|
602
|
+
i["ran_by"] = data.get("ran_by", i["ran_by"])
|
|
603
|
+
data["ids"].append(i["pk"])
|
|
604
|
+
|
|
605
|
+
api_request("patch", url="/analyses/bulk_update/", json=data)
|
|
606
|
+
|
|
607
|
+
for i in analyses:
|
|
608
|
+
_run_signals("analyses", i, system_settings.ON_STATUS_CHANGE)
|
|
609
|
+
|
|
610
|
+
return analyses
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
def patch_analysis_status(analysis, status):
|
|
614
|
+
"""
|
|
615
|
+
Patch a successful analysis.
|
|
616
|
+
|
|
617
|
+
Make sure analysis is owned by admin user and that results field is updated.
|
|
618
|
+
|
|
619
|
+
Arguments:
|
|
620
|
+
analysis (dict): analysis instance.
|
|
621
|
+
status (dict): analysis status.
|
|
622
|
+
|
|
623
|
+
Returns:
|
|
624
|
+
dict: patched analysis instance.
|
|
625
|
+
"""
|
|
626
|
+
data = {"status": status}
|
|
627
|
+
storage_url = analysis["storage_url"]
|
|
628
|
+
analysis["status"] = status # make sure that the analysis status is updated
|
|
629
|
+
_set_analysis_permissions(analysis)
|
|
630
|
+
|
|
631
|
+
if status in {"FAILED", "SUCCEEDED", "IN_PROGRESS", "REJECTED"}:
|
|
632
|
+
data["storage_usage"] = utils.get_tree_size(storage_url)
|
|
633
|
+
|
|
634
|
+
if status == "STARTED":
|
|
635
|
+
data["ran_by"] = system_settings.api_username
|
|
636
|
+
|
|
637
|
+
if status in {"SUCCEEDED", "IN_PROGRESS"}:
|
|
638
|
+
try:
|
|
639
|
+
data["results"] = _get_analysis_results(analysis, raise_error=True)
|
|
640
|
+
except Exception as error: # pragma: no cover
|
|
641
|
+
data["status"] = "FAILED"
|
|
642
|
+
patch_instance("analyses", analysis["pk"], **data)
|
|
643
|
+
raise error
|
|
644
|
+
|
|
645
|
+
return patch_instance("analyses", analysis["pk"], **data)
|
|
646
|
+
|
|
647
|
+
|
|
648
|
+
def send_error_email(recipients, subject, message):
|
|
649
|
+
"""
|
|
650
|
+
Send an error message to recipients.
|
|
651
|
+
|
|
652
|
+
Arguments:
|
|
653
|
+
recipients (list): email recipients.
|
|
654
|
+
subject (str): email subject.
|
|
655
|
+
message (str): error message.
|
|
656
|
+
|
|
657
|
+
Returns:
|
|
658
|
+
requests.models.Response: api request response.
|
|
659
|
+
"""
|
|
660
|
+
kwargs = {
|
|
661
|
+
"data": {
|
|
662
|
+
"recipients": recipients,
|
|
663
|
+
"subject": subject,
|
|
664
|
+
"content": message,
|
|
665
|
+
"html_template": "error",
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
return api_request("post", url=f"/send_email", **kwargs)
|
|
669
|
+
|
|
670
|
+
|
|
671
|
+
def _set_analysis_permissions(analysis):
|
|
672
|
+
protect_results = analysis.status == "SUCCEEDED"
|
|
673
|
+
unique_analysis_per_individual = False
|
|
674
|
+
application_protect_results = True
|
|
675
|
+
chgrp_cmd = (
|
|
676
|
+
["false"]
|
|
677
|
+
if not system_settings.DEFAULT_LINUX_GROUP
|
|
678
|
+
else ["chgrp", "-R", system_settings.DEFAULT_LINUX_GROUP, analysis.storage_url]
|
|
679
|
+
)
|
|
680
|
+
|
|
681
|
+
try:
|
|
682
|
+
application = import_from_string(analysis.application.application_class)()
|
|
683
|
+
unique_analysis_per_individual = application.unique_analysis_per_individual
|
|
684
|
+
application_protect_results = application.application_protect_results
|
|
685
|
+
except ImportError:
|
|
686
|
+
pass
|
|
687
|
+
|
|
688
|
+
if (
|
|
689
|
+
# dont protect results if project level analysis
|
|
690
|
+
analysis.project_level_analysis
|
|
691
|
+
# dont protect results if individual level automerge
|
|
692
|
+
or (analysis.individual_level_analysis and not unique_analysis_per_individual)
|
|
693
|
+
# dont protect results if the application says so
|
|
694
|
+
or not application_protect_results
|
|
695
|
+
):
|
|
696
|
+
protect_results = False
|
|
697
|
+
|
|
698
|
+
if protect_results:
|
|
699
|
+
utils.check_admin()
|
|
700
|
+
|
|
701
|
+
if analysis.ran_by != system_settings.api_username:
|
|
702
|
+
src = analysis.storage_url + "__tmp"
|
|
703
|
+
shutil.move(analysis.storage_url, src)
|
|
704
|
+
cmd = utils.get_rsync_command(src, analysis.storage_url, chmod="a-w")
|
|
705
|
+
try:
|
|
706
|
+
subprocess.check_call(cmd, shell=True)
|
|
707
|
+
except subprocess.CalledProcessError:
|
|
708
|
+
try:
|
|
709
|
+
version_stdout = subprocess.run(
|
|
710
|
+
["rsync", "--version"], capture_output=True, text=True
|
|
711
|
+
).stdout.split("\n")[0]
|
|
712
|
+
utils.check_rsync_version(version_stdout)
|
|
713
|
+
except Exception as e:
|
|
714
|
+
click.secho(f"Error running rsync and checking its version", err=True, fg="red")
|
|
715
|
+
raise(e)
|
|
716
|
+
else:
|
|
717
|
+
subprocess.check_call(["chmod", "-R", "a-w", analysis.storage_url])
|
|
718
|
+
|
|
719
|
+
try:
|
|
720
|
+
subprocess.check_output(chgrp_cmd, stderr=subprocess.STDOUT)
|
|
721
|
+
except subprocess.CalledProcessError:
|
|
722
|
+
pass
|
|
723
|
+
|
|
724
|
+
elif not protect_results or analysis.status in {"FAILED", "FINISHED"}:
|
|
725
|
+
for i in [chgrp_cmd, ["chmod", "-R", "g+rwX", analysis.storage_url]]:
|
|
726
|
+
try:
|
|
727
|
+
subprocess.check_output(i, stderr=subprocess.STDOUT)
|
|
728
|
+
except subprocess.CalledProcessError:
|
|
729
|
+
pass
|
|
730
|
+
|
|
731
|
+
|
|
732
|
+
def _get_analysis_results(analysis, raise_error=True):
|
|
733
|
+
"""Patch analysis results."""
|
|
734
|
+
app_name = f"{analysis.application.name} {analysis.application.version}"
|
|
735
|
+
error_msg = f"\tFailed to patch {app_name}({analysis.pk}, {analysis.storage_url}):"
|
|
736
|
+
results = analysis.results
|
|
737
|
+
|
|
738
|
+
try:
|
|
739
|
+
application = import_from_string(analysis.application.application_class)()
|
|
740
|
+
except ImportError as error:
|
|
741
|
+
click.secho(f"{error_msg} cant import application class", err=True, fg="red")
|
|
742
|
+
return results
|
|
743
|
+
|
|
744
|
+
if not analysis.storage_url: # pragma: no cover
|
|
745
|
+
analysis = application._patch_analysis(analysis)
|
|
746
|
+
|
|
747
|
+
try:
|
|
748
|
+
# just used to make sure the app results are patched
|
|
749
|
+
expected_app = application.primary_key
|
|
750
|
+
|
|
751
|
+
if analysis.project_level_analysis:
|
|
752
|
+
expected_app = application.project_level_auto_merge_application.pk
|
|
753
|
+
elif (
|
|
754
|
+
analysis.individual_level_analysis and application.has_individual_auto_merge
|
|
755
|
+
):
|
|
756
|
+
expected_app = application.individual_level_auto_merge_application.pk
|
|
757
|
+
|
|
758
|
+
assert analysis.application.pk == expected_app, (
|
|
759
|
+
f"{application.__class__} does not match: "
|
|
760
|
+
f"{analysis.application.application_class}"
|
|
761
|
+
)
|
|
762
|
+
|
|
763
|
+
results = application._get_analysis_results(analysis)
|
|
764
|
+
except Exception as error: # pragma: no cover pylint: disable=broad-except
|
|
765
|
+
click.secho(f"{error_msg} {error}", err=True, fg="red")
|
|
766
|
+
if raise_error:
|
|
767
|
+
raise error
|
|
768
|
+
print(traceback.format_exc())
|
|
769
|
+
|
|
770
|
+
return results
|
|
771
|
+
|
|
772
|
+
|
|
773
|
+
def _run_signals(endpoint, instance, signals, raise_error=False, create_record=True):
|
|
774
|
+
errors = []
|
|
775
|
+
on_failure = system_settings.ON_SIGNAL_FAILURE or (lambda *_, **__: None)
|
|
776
|
+
|
|
777
|
+
for signal in signals:
|
|
778
|
+
try:
|
|
779
|
+
signal(instance)
|
|
780
|
+
except Exception as error: # pragma: no cover pylint: disable=W0703
|
|
781
|
+
failure_traceback = traceback.format_exc()
|
|
782
|
+
errors.append((error, failure_traceback))
|
|
783
|
+
|
|
784
|
+
try:
|
|
785
|
+
on_failure(endpoint, instance, signal, error)
|
|
786
|
+
except Exception as on_failure_error: # pylint: disable=W0703
|
|
787
|
+
errors.append((on_failure_error, traceback.format_exc()))
|
|
788
|
+
failure_traceback += traceback.format_exc()
|
|
789
|
+
|
|
790
|
+
if not create_record:
|
|
791
|
+
continue
|
|
792
|
+
|
|
793
|
+
# get or create signal instance
|
|
794
|
+
signal_instance = create_instance(
|
|
795
|
+
"signals",
|
|
796
|
+
target_endpoint=endpoint,
|
|
797
|
+
target_id=instance.pk,
|
|
798
|
+
import_string=".".join([signal.__module__, signal.__name__]),
|
|
799
|
+
)
|
|
800
|
+
|
|
801
|
+
# patch signal with error message
|
|
802
|
+
signal_instance.data["failure_traceback"] = failure_traceback
|
|
803
|
+
patch_instance("signals", signal_instance.pk, data=signal_instance.data)
|
|
804
|
+
|
|
805
|
+
if errors:
|
|
806
|
+
msg = (
|
|
807
|
+
click.style("\nERROR:", fg="red")
|
|
808
|
+
+ " some signals failed!\n\n"
|
|
809
|
+
+ click.style("\n".join([f"{i}:\n\t{j}" for i, j in errors]), fg="red")
|
|
810
|
+
)
|
|
811
|
+
|
|
812
|
+
click.echo(msg, err=True)
|
|
813
|
+
|
|
814
|
+
if raise_error:
|
|
815
|
+
raise exceptions.AutomationError(msg)
|