/
app.py
executable file
·499 lines (435 loc) · 14.9 KB
/
app.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
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
"""
Oasis API server application endpoints.
"""
from __future__ import absolute_import, unicode_literals
import os
import logging
import time
import uuid
from celery import Celery
from oasislmf.utils import http, status
from oasislmf.utils.log import oasis_log
from ..common import data
from flask import Flask, Response, request, jsonify
from flask_swagger import swagger
from flask.helpers import send_from_directory
from ..conf.settings import settings
from ..conf import celery as celery_conf
APP = Flask(__name__)
TAR_FILE_SUFFIX = '.tar'
GZIP_FILE_SUFFIX = '.gz'
CELERY = Celery()
CELERY.config_from_object(celery_conf)
def _get_exposure_summary(filename):
filepath = os.path.join(settings.get('server', 'INPUTS_DATA_DIRECTORY'), filename)
if not filepath.endswith(TAR_FILE_SUFFIX):
return None
if not os.path.isfile(filepath):
return None
size_in_bytes = os.path.getsize(filepath)
created_date = time.ctime(os.path.getctime(filepath))
return data.ExposureSummary(
location=filename.replace(TAR_FILE_SUFFIX, ''),
size=size_in_bytes,
created_date=created_date
)
@APP.route('/exposure_summary', defaults={'location': None}, methods=["GET"])
@APP.route('/exposure_summary/<location>', methods=["GET"])
@oasis_log()
def get_exposure_summary(location):
"""
Get exposure summary
---
definitions:
schema:
id: ExposureSummary
properties:
location:
type: string
description: The location of the exposure data.
size:
type: integer
description: The size of the uncompressed exposure data in bytes.
created_date:
type: string
format: dateTime
description: The date when the exposure data was uploaded.
description: Gets a summary of a exposure resources and their contents.
If location parameter is not supplied returns a summary of
all exposures.
produces:
- application/json
responses:
200:
description: A list of exposure summaries.
schema:
type: array
items:
$ref: "#/definitions/ExposureSummary"
404:
description: Resource not found
parameters:
- name: location
in: path
description: The location of the exposure resource to summarise.
required: true
type: string
"""
logging.debug("Location: {}".format(location))
if location is None:
return jsonify({
'exposures': [ex for ex in map(_get_exposure_summary, sorted(os.listdir(settings.get('server', 'INPUTS_DATA_DIRECTORY')))) if ex]
})
else:
exposure = _get_exposure_summary('{}{}'.format(location, TAR_FILE_SUFFIX))
if not exposure:
return Response(status=http.HTTP_RESPONSE_RESOURCE_NOT_FOUND)
return jsonify({'exposures': [exposure]})
@APP.route('/exposure/<location>', methods=["GET"])
@oasis_log()
def get_exposure(location):
"""
Get an exposure resource
---
description: Returns an exposure resource.
produces:
- application/json
responses:
200:
description: A compressed tar file containing the Oasis exposure files.
404:
description: Resource not found
parameters:
- name: location
in: path
description: The location of the exposure resource.
required: true
type: string
"""
logging.debug("Location: {}".format(location))
return send_from_directory(settings.get('server', 'INPUTS_DATA_DIRECTORY'), location + TAR_FILE_SUFFIX)
@APP.route('/exposure', methods=["POST"])
@oasis_log()
def post_exposure():
"""
Upload an exposure resource
---
description: Uploads an exposure resource by posting an exposure tar file.
The tar file can be compressed or uncompressed.
produces:
- application/json
responses:
200:
description: The exposure summary of the created exposure resource.
schema:
$ref: '#/definitions/ExposureSummary'
"""
request_file = request.files['file']
filename = uuid.uuid4().hex
filepath = os.path.join(settings.get('server', 'INPUTS_DATA_DIRECTORY'), filename) + TAR_FILE_SUFFIX
request_file.save(filepath)
# Check the content, and if invalid delete
size_in_bytes = os.path.getsize(filepath)
created_date = time.ctime(os.path.getctime(filepath))
exposure = {
"location": filename,
"size": size_in_bytes,
"created_date": created_date
}
return jsonify({'exposures': [exposure]})
@APP.route('/exposure', defaults={'location': None}, methods=["DELETE"])
@APP.route('/exposure/<location>', methods=["DELETE"])
@oasis_log()
def delete_exposure(location):
"""
Delete an exposure resource
---
description: Deletes an exposure resource. If no location is given all exposure resources will be deleted.
produces:
- application/json
responses:
200:
description: OK
404:
description: Resource not found
parameters:
- name: location
in: path
description: location of exposure resource to delete.
required: true
type: string
"""
logging.debug("Location: {}".format(location))
if location is None:
for filename in os.listdir(settings.get('server', 'INPUTS_DATA_DIRECTORY')):
filepath = os.path.join(settings.get('server', 'INPUTS_DATA_DIRECTORY'), filename)
if not filepath.endswith(TAR_FILE_SUFFIX):
continue
if not os.path.isfile(filepath):
continue
os.remove(filepath)
response = Response(status=http.HTTP_RESPONSE_OK)
else:
filename = str(location) + TAR_FILE_SUFFIX
filepath = os.path.join(settings.get('server', 'INPUTS_DATA_DIRECTORY'), filename)
if not os.path.exists(filepath):
response = Response(status=http.HTTP_RESPONSE_RESOURCE_NOT_FOUND)
else:
os.remove(filepath)
response = Response(status=http.HTTP_RESPONSE_OK)
return response
@APP.route('/analysis/<input_location>', methods=["POST"])
@oasis_log()
def post_analysis(input_location):
"""
Start an analysis
---
description: Starts an analysis by creating an analysis status resource.
produces:
- application/json
responses:
200:
description: The analysis status resource for the new analysis.
schema:
$ref: '#/definitions/AnalysisStatus'
produces:
- application/json
parameters:
- name: input_location
in: path
description: The location of the input resource to analyse.
required: true
type: string
- name: analysis_settings
in: formData
description: The analysis settings
required: true
type: file
"""
analysis_settings = request.json or {}
if not validate_analysis_settings(analysis_settings) or not _get_exposure_summary('{}.tar'.format(input_location)):
return Response(status=http.HTTP_RESPONSE_BAD_REQUEST)
else:
module_supplier_id = analysis_settings['analysis_settings']['module_supplier_id']
model_version_id = analysis_settings['analysis_settings']['model_version_id']
logging.info("Model supplier - version = {} {}".format(module_supplier_id, model_version_id))
result = CELERY.send_task(
'run_analysis',
(input_location, [analysis_settings]),
queue='{}-{}'.format(module_supplier_id, model_version_id)
)
task_id = result.task_id
return jsonify({'location': task_id})
def _get_analysis_status(location):
"""
Get the status of an analysis
"""
result = CELERY.AsyncResult(location)
logging.debug("celery result:{}".format(result.result))
if result.state == status.STATUS_SUCCESS:
analysis_status = data.AnalysisStatus(
id=-1,
status=status.STATUS_SUCCESS,
message="",
outputs_location=result.result)
elif result.state == status.STATUS_FAILURE:
analysis_status = data.AnalysisStatus(
id=-1,
status=status.STATUS_FAILURE,
message=repr(result.result),
outputs_location=None)
else:
analysis_status = data.AnalysisStatus(
id=-1,
status=result.state,
message="",
outputs_location=None)
return analysis_status
@APP.route('/analysis_status/<location>', methods=["GET"])
@oasis_log()
def get_analysis_status(location):
"""
Get an analysis status resource
---
definitions:
- schema:
id: AnalysisStatus
properties:
id:
type: string
description: The analysis ID.
status:
type: string
description: The analysis status.
message:
type: string
description: The analysis status message.
outputs_summary:
type: OutputsSummary
description: Summary of the outputs.
id: OutputsSummary
properties:
location:
type: string
description: The location of the data.
size:
type: integer
description: The size of the uncompressed data in bytes.
created_date:
type: string
format: dateTime
description: The date when the data was created.
description: Gets an analysis status resource. If no location is given
all exposure status resources are returned.
produces:
- application/json
responses:
200:
description: A list of analysis status resources.
schema:
type: array
items:
$ref: '#/definitions/AnalysisStatus'
404:
description: Resource not found.
parameters:
- name: location
in: path
description: The location of the outputs resource to download.
required: true
type: string
"""
analysis_status = _get_analysis_status(location)
# If there is no location for a successful analysis, retry once
# and then fail the analysis as something has gone wrong
if (analysis_status.status == status.STATUS_SUCCESS and analysis_status.outputs_location is None):
logging.info("Successful analysis has no location - retrying")
time.sleep(5)
analysis_status = _get_analysis_status(location)
if (analysis_status.status == status.STATUS_SUCCESS and analysis_status.outputs_location is None):
logging.info("Successful analysis still has no location - fail")
analysis_status.status = status.STATUS_FAILURE
response = jsonify(analysis_status)
logging.debug("Response: {}".format(response.data))
return response
@APP.route('/analysis_status', methods=["DELETE"])
@APP.route('/analysis_status/<location>', methods=["DELETE"])
@oasis_log()
def delete_analysis_status(location): # pragma: no cover
"""
Delete an analysis status resource
---
description: Deletes an analysis status resource. If no location
is given all analysis status resources will be deleted.
produces:
- application/json
responses:
200:
description: OK
404:
description: Resource not found
parameters:
- name: location
in: path
description: The location of the analysis status resource to delete.
required: true
type: string
"""
raise Exception("Not implemented")
try:
logging.debug("Location: {}".format(location))
except Exception:
logging.exception("Failed to delete analysis status")
response = Response(status=http.HTTP_RESPONSE_INTERNAL_SERVER_ERROR)
return response
@APP.route('/outputs/<location>', methods=["GET"])
@oasis_log()
def get_outputs(location):
"""
Get a outputs resource
---
description: Gets a outputs resource, returning a compressed outputs tar file.
produces:
- application/json
responses:
200:
description: A compressed tar of the outputs generated by an analysis.
404:
description: Resource not found.
parameters:
- name: location
in: path
description: The location of the outputs resource to download.
required: true
type: string
"""
logging.debug("Location: {}".format(location))
return send_from_directory(settings.get('server', 'OUTPUTS_DATA_DIRECTORY'), location + TAR_FILE_SUFFIX)
@APP.route('/outputs', defaults={'location': None}, methods=["DELETE"])
@APP.route('/outputs/<location>', methods=["DELETE"])
@oasis_log()
def delete_outputs(location):
"""
download_directory = '/var/www/oasis/download'
Delete a outputs resource
---
description: Deletes a outputs resource. If no location is given all
outputs resources will be deleted.
produces:
- application/json
responses:
200:
description: OK
404:
description: Resource not found
parameters:
- name: location
in: path
description: The location of the outputs resource to delete.
required: true
type: string
"""
logging.debug("Location: {}".format(location))
if location is None:
for filename in os.listdir(settings.get('server', 'OUTPUTS_DATA_DIRECTORY')):
filepath = os.path.join(settings.get('server', 'OUTPUTS_DATA_DIRECTORY'), filename)
if not filepath.endswith(TAR_FILE_SUFFIX):
continue
if not os.path.isfile(filepath):
continue
os.remove(filepath)
response = Response(status=http.HTTP_RESPONSE_OK)
else:
filename = str(location) + TAR_FILE_SUFFIX
filepath = os.path.join(settings.get('server', 'OUTPUTS_DATA_DIRECTORY'), filename)
if not os.path.exists(filepath):
response = Response(status=http.HTTP_RESPONSE_RESOURCE_NOT_FOUND)
else:
os.remove(filepath)
response = Response(status=http.HTTP_RESPONSE_OK)
return response
@APP.route("/spec")
@oasis_log()
def spec():
"""
Create Swagger docs
"""
swag = swagger(APP)
swag['info']['version'] = "0.1"
swag['info']['title'] = "Oasis API"
return jsonify(swag)
@APP.route('/healthcheck', methods=['GET'])
@oasis_log()
def get_healthcheck():
'''
Basic healthcheck response.
'''
# TODO: check job management connections
logging.info("get_healthcheck")
return "OK"
def validate_analysis_settings(analysis_settings):
return (
'analysis_settings' in analysis_settings and
'module_supplier_id' in analysis_settings['analysis_settings'] and
'model_version_id' in analysis_settings['analysis_settings']
)