aboutsummaryrefslogtreecommitdiffstats
path: root/aria/aria-rest-server/src/main/python/aria-rest/aria_rest/rest.py
blob: 7b9223d1c90d2e51d7d26801e0df610d63f09c18 (plain)
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
#
# ============LICENSE_START===================================================
# Copyright (c) 2017 Cloudify.co.  All rights reserved.
# ===================================================================
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
# ============LICENSE_END====================================================
#


import os
from flask import Flask, request, jsonify
from flask_autodoc.autodoc import Autodoc
from aria import install_aria_extensions
from aria.parser import consumption
from aria.utils import formatting, collections
from aria.cli.core import aria
from aria.cli import utils
from aria.exceptions import ParsingError, DependentServicesError
from aria.core import Core
from aria.cli import service_template_utils
from aria.storage import exceptions as storage_exceptions
from aria.utils import threading
from aria.orchestrator.workflow_runner import WorkflowRunner
from aria.orchestrator.workflows.executor.dry import DryExecutor
import util
import tempfile
import shutil

version_id = "0.1"
route_base = "/api/" + version_id + "/"
app = Flask("onap-aria-rest")
auto = Autodoc(app)

# TODO Garbage collect this dict somehow
execution_state = util.SafeDict()


def main():
    install_aria_extensions()
    app.run(host='0.0.0.0', port=5000, threaded=True)


@app.route("/")
@app.route("/api")
@app.route("/docs")
def index():
    return auto.html()


###
# TEMPLATES
###

# add template
@app.route(route_base + "templates/<template_name>", methods=['PUT'])
@auto.doc()
@aria.pass_model_storage
@aria.pass_resource_storage
@aria.pass_plugin_manager
@aria.pass_logger
def install_template(template_name, model_storage, resource_storage,
                     plugin_manager, logger):

    """
    installs a template in Aria storage

    3 modes possible:

      1. PUT JSON body which points to a CSAR URL.  Content-type must be
         application/json. PUT data is a JSON object/map with the following
         keys.:
          * service_template_path (required): URL to CSAR
          * service_template_filename (optional): service template file.

      2. PUT with service template file body.  Content-type must be
         text/plain.

      3. PUT with binary CSAR body.  Content-type must be application/zip.
         Optional query string arg "template_filename" can indicate the
         service template filename in the CSAR.  Defaults to
         "service-template.yaml".
    """

    service_template_path = None
    service_template_filename = "service-template.yaml"

    rtype = "unknown"
    if request.is_json:
        rtype = "json"
    elif request.headers['Content-Type'] == "application/zip":
        rtype = "zip"
        suffix = ".csar"
    elif request.headers['Content-Type'] == "text/plain":
        rtype = "yaml"
        suffix = ".yaml"

    if rtype == "zip" or rtype == "yaml":
        with tempfile.NamedTemporaryFile(prefix = "ariatmp_",
                                         suffix = suffix,
                                         delete = False) as f:
            f.write(request.data)
            service_template_path = f.name
        if request.headers['Content-Type'] == "application/zip":
            if "template_filename" in request.args:
                service_template_filename = request.args["template_filename"]

    elif rtype == "json":

        body = request.json or {}

        # Check body
        if "service_template_path" in body:
            service_template_path = body["service_template_path"]
        else:
            return "request body missing service_template_path", 501

        if "service_template_filename" in body:
            service_template_filename = body["service_template_filename"]
        else:
            service_template_filename = "service-template.yaml"

    else:
        return "Unrecognized content type",400

    service_template_file_path = service_template_utils.get(
        service_template_path, service_template_filename)

    core = Core(model_storage, resource_storage, plugin_manager)

    try:
        core.create_service_template(service_template_file_path,
                                     os.path.dirname(service_template_path),
                                     template_name)
    except storage_exceptions.StorageError as e:
        logger.error("storage exception")
        utils.check_overriding_storage_exceptions(
            e, 'service template', template_name)
        return e.message, 500
    except Exception as e:
        logger.error("catchall exception")
        return e.message, 500
    finally:
        # cleanup
        if rtype == "zip" or rtype == "yaml":
            os.remove(service_template_path)
        if rtype == "zip":
            shutil.rmtree(os.path.dirname(service_template_file_path))

    return "service template installed", 200

# validate template
@app.route(route_base + "templates", methods=['POST'])
@auto.doc()
@aria.pass_model_storage
@aria.pass_resource_storage
@aria.pass_plugin_manager
@aria.pass_logger
def validate_template(model_storage, resource_storage, plugin_manager, logger):
    """
    Validates a TOSCA template
    """
    body = request.json or {}

    # Check body
    if "service_template_path" in body:
        service_template_path = body["service_template_path"]
    else:
        return "request body missing service_template_path", 501
    if "service_template_filename" in body:
        service_template_filename = body["service_template_filename"]
    else:
        service_template_filename = "service-template.yaml"

    service_template_path = service_template_utils.get(
        service_template_path, service_template_filename)

    core = Core(model_storage, resource_storage, plugin_manager)
    try:
        context = core.validate_service_template(service_template_path)
    except ParsingError as e:
        return e.message, 400

    logger.info('Service template {} validated'.format(service_template_path))
    return "", 200


# delete template
@app.route(route_base + "templates/<template_id>", methods=['DELETE'])
@auto.doc()
@aria.pass_model_storage
@aria.pass_resource_storage
@aria.pass_plugin_manager
@aria.pass_logger
def delete_template(
        template_id,
        model_storage,
        resource_storage,
        plugin_manager,
        logger):
    """
    Deletes a template from Aria storage
    """

    logger.info('Deleting service template {}'.format(template_id))
    core = Core(model_storage, resource_storage, plugin_manager)
    try:
        core.delete_service_template(template_id)
    except DependentServicesError as e:
        logger.error("dependent services error")
        return e.message, 400
    except Exception as e:
        logger.error("failed")
        return "Failed to delete template", 500

    logger.info('Service template {} deleted'.format(template_id))
    return "", 200


# get template json
@app.route(route_base + "templates/<template_id>/json", methods=['GET'])
@auto.doc()
@aria.pass_model_storage
@aria.pass_logger
def get_template_json(template_id, model_storage, logger):
    """ get JSON representation of template """
    template = model_storage.service_template.get(template_id)
    consumption.ConsumptionContext()
    body = formatting.json_dumps(collections.prune(template.as_raw))
    return body


# list templates
@app.route(route_base + "templates", methods=['GET'])
@auto.doc()
@aria.pass_model_storage
@aria.pass_logger
def list_templates(model_storage, logger):
    """
    Lists templates installed in Aria storage
    """
    list = model_storage.service_template.list()
    templates = []
    for item in list:
        templates.append({"name": item.name,
                          "id": item.id,
                          "description": item.description
                          })
    return jsonify(templates)


# list nodes
@app.route(route_base + "templates/<template_id>/nodes", methods=['GET'])
@auto.doc()
@aria.pass_model_storage
@aria.pass_logger
def list_nodes_by_template(template_id, model_storage, logger):
    """
    Lists node templates in specified Aria template
    """
    service_template = model_storage.service_template.get(template_id)
    filters = dict(service_template=service_template)
    nodes = model_storage.node_template.list(filters=filters)
    nodelist = []

    for node in nodes:
        nodelist.append({
            "id": node.id,
            "name": node.name,
            "description": node.description,
            "service_template_id": service_template.id,
            "type_name": node.type_name
        })
    return jsonify(nodelist), 200


# show node details
@app.route(route_base + "nodes/<node_id>", methods=['GET'])
@auto.doc()
@aria.pass_model_storage
@aria.pass_logger
def get_node(node_id, model_storage, logger):
    """
    Get node details
    """
    node_template = model_storage.node_template.get(node_id)
    service_template = model_storage.service_template.get_by_name(
        node_template.service_template_name)
    retmap = {}
    retmap['id'] = node_id
    retmap['name'] = node_template.name
    retmap['description'] = node_template.description
    retmap['service_template_id'] = service_template.id
    retmap['type_name'] = node_template.type_name
    return jsonify(retmap), 200

###
# SERVICES
###


# list services
@app.route(route_base + "services", methods=['GET'])
@auto.doc()
@aria.pass_model_storage
@aria.pass_logger
def list_services(model_storage, logger):
    """
    Lists all services
    """
    services_list = model_storage.service.list()
    outlist = []
    for service in services_list:
        outlist.append({"id": service.id,
                        "description": service.description,
                        "name": service.name,
                        "service_template": service.service_template.name,
                        "created": service.created_at,
                        "updated": service.updated_at})
    return jsonify(outlist), 200


# show service
@app.route(route_base + "services/<service_id>", methods=['GET'])
def show_service(service_id):
    """
    Returns details for specified servie
    """
    return "not implemented", 501


# get service outputs
@app.route(route_base + "services/<service_id>/outputs", methods=['GET'])
@auto.doc()
@aria.pass_model_storage
@aria.pass_logger
def get_service_outputs(service_id, model_storage, logger):
    """
    Gets outputs for specified service
    """
    service = model_storage.service.get(service_id)
    outlist = []
    for output_name, output in service.outputs.iteritems():
        outlist.append({"name": output_name, "description": output.description,
                        "value": output.value})
    return jsonify(outlist)


# get service inputs
@app.route(route_base + "services/<service_id>/inputs", methods=['GET'])
@auto.doc()
@aria.pass_model_storage
@aria.pass_logger
def get_service_inputs(service_id, model_storage, logger):
    """
    Gets inputs for specified service
    """
    service = model_storage.service.get(service_id)
    outlist = []
    for input_name, input in service.inputs.iteritems():
        outlist.append({"name": input_name, "description": input.description,
                        "value": input.value})
    return jsonify(outlist)


# create service
@app.route(route_base + "templates/<template_id>/services/<service_name>",
           methods=['POST'])
@auto.doc()
@aria.pass_model_storage
@aria.pass_resource_storage
@aria.pass_plugin_manager
@aria.pass_logger
def create_service(template_id, service_name, model_storage, resource_storage,
                   plugin_manager, logger):
    """
    Creates a service from the specified service template
    """
    body = request.json or {}
    inputs = {}
    if 'inputs' in body:
        inputs = body['inputs']
    core = Core(model_storage, resource_storage, plugin_manager)
    service = core.create_service(template_id, inputs, service_name)

    logger.info("service {} created".format(service.name))
    return "service {} created".format(service.name), 200


# delete service
@app.route(route_base + "services/<service_id>", methods=['DELETE'])
@auto.doc()
@aria.pass_model_storage
@aria.pass_resource_storage
@aria.pass_plugin_manager
@aria.pass_logger
def delete_service(
        service_id,
        model_storage,
        resource_storage,
        plugin_manager,
        logger):
    """
    Deletes the specified servi e
    """
    service = model_storage.service.get(service_id)
    core = Core(model_storage, resource_storage, plugin_manager)
    core.delete_service(service_id, force=True)
    return "service {}  deleted".format(service.id), 200


###
# WORKFLOWS
###


# list workflows
@app.route(route_base + "services/<service_id>/workflows", methods=['GET'])
@auto.doc()
@aria.pass_model_storage
@aria.pass_logger
def list_workflows(service_id, model_storage, logger):
    """
    Lists all defined user workflows for the specified service
    """
    service = model_storage.service.get(service_id)
    workflows = service.workflows.itervalues()
    outlist = []
    for workflow in workflows:
        outlist.append(workflow.name)
    return jsonify(outlist), 200


# show workflow
@app.route(
    route_base +
    "services/<service_id>/workflow/<workflow_name>",
    methods=['GET'])
def show_workflow(service_name, workflow_name):
    """
    Returns details of specified workflow
    """
    return "not implemented", 501

###
# EXECUTIONS
###


# list all executions
@app.route(route_base + "executions", methods=['GET'])
@auto.doc()
@aria.pass_model_storage
@aria.pass_logger
def list_executions(model_storage, logger):
    """
    Return all executions
    """
    elist = model_storage.execution.list()
    outlist = []
    for execution in elist:
        outlist.append(
            {"execution_id": execution.id,
             "workflow_name": execution.workflow_name,
             "service_template_name": execution.service_template_name,
             "service_name": execution.service_name,
             "status": execution.status})
    return jsonify(outlist), 200


# list executions for service
@app.route(route_base + "services/<service_id>/executions", methods=['GET'])
@auto.doc()
@aria.pass_model_storage
@aria.pass_logger
def list_service_executions(service_id, model_storage, logger):
    """
    Return all executions for specified service
    """
    service = model_storage.service.get(service_id)
    elist = model_storage.execution.list(filters=dict(service=service))
    outlist = []
    for execution in elist:
        outlist.append(
            {"execution_id": execution.id,
             "workflow_name": execution.workflow_name,
             "service_template_name": execution.service_template_name,
             "service_name": execution.service_name,
             "status": execution.status})
    return jsonify(outlist), 200


# show execution
@app.route(route_base + "executions/<execution_id>", methods=['GET'])
@auto.doc()
@aria.pass_model_storage
@aria.pass_logger
def show_execution(execution_id, model_storage, logger):
    """
    Return details of specified execution
    """
    try:
        execution = model_storage.execution.get(execution_id)
    except BaseException:
        return "Execution {} not found".format(execution_id), 404

    return jsonify({"execution_id": execution_id,
                    "service_name": execution.service_name,
                    "service_template_name": execution.service_template_name,
                    "workflow_name": execution.workflow_name,
                    "status": execution.status}), 200

# start execution


# TODO allow executors other than default and dry to be used
@app.route(
    route_base +
    "services/<service_id>/executions/<workflow_name>",
    methods=['POST'])
@auto.doc()
@aria.pass_model_storage
@aria.pass_resource_storage
@aria.pass_plugin_manager
@aria.pass_logger
def start_execution(
        service_id,
        workflow_name,
        model_storage,
        resource_storage,
        plugin_manager,
        logger):
    """
    Start an execution for the specified service
    """
    body = request.json or {}
    executor = DryExecutor(
        ) if 'executor' in body and body['executor'] == 'dry' else None

    inputs = body['inputs'] if 'inputs' in body else None
    task_max_attempts = (body['task_max_attempts']
                         if 'task_max_attempts' in body else 30)
    task_retry_interval = (body['task_retry_interval']
                           if 'task_retry_interval' in body else 30)

    runner = WorkflowRunner(model_storage, resource_storage, plugin_manager,
                            service_id=service_id,
                            workflow_name=workflow_name,
                            inputs=inputs,
                            executor=executor,
                            task_max_attempts=task_max_attempts,
                            task_retry_interval=task_retry_interval)

    service = model_storage.service.get(service_id)
    tname = '{}_{}_{}'.format(service.name, workflow_name, runner.execution_id)
    thread = threading.ExceptionThread(target=runner.execute,
                                       name=tname)
    thread.start()
    execution_state[str(runner.execution_id)] = [runner, thread]
    return jsonify({"id": runner.execution_id}), 202


# resume execution
@app.route(route_base + "executions/<execution_id>", methods=['POST'])
@auto.doc()
@aria.pass_model_storage
@aria.pass_resource_storage
@aria.pass_plugin_manager
@aria.pass_logger
def resume_execution(
        execution_id,
        model_storage,
        resource_storage,
        plugin_manager,
        logger):
    """
    Resume the specified execution
    """
    body = request.json or {}
    execution = model_storage.execution.get(execution_id)
    if execution.status != execution.status.CANCELLED:
        return "cancelled execution cannot be resumed", 400
    executor = DryExecutor(
        ) if 'executor' in body and body['executor'] == 'dry' else None
    retry_failed_tasks = body['retry_failed_tasks'] \
        if 'retry_failed_tasks' in body else False

    runner = WorkflowRunner(model_storage, resource_storage, plugin_manager,
                            execution_id=execution_id,
                            executor=executor,
                            retry_failed_tasks=retry_failed_tasks)

    tname = '{}_{}_{}'.format(execution.service.name, execution.workflow_name,
                              runner.execution_id)
    thread = threading.ExceptionThread(target=runner.execute,
                                       name=tname,
                                       daemon=True)
    thread.start()
    execution_state[str(runner.execution_id)] = [runner, thread]
    return jsonify({"id": runner.execution_id}), 202


# cancel execution
@app.route(route_base + "executions/<execution_id>", methods=['DELETE'])
@auto.doc()
@aria.pass_model_storage
@aria.pass_logger
def cancel_execution(execution_id, model_storage, logger):
    """
    Cancel the specified execution
    """
    logger.info("cancelling execution {}".format(execution_id))
    body = request.json or {}

    try:
        execution = model_storage.execution.get(execution_id)
    except BaseException:
        return "Execution {} not found".format(execution_id), 404

    if (not execution.status == execution.PENDING and
            not execution.status == execution.STARTED):
        return "Cancel ignored.  Execution state = {}".format(
            execution.status), 200

    if execution_id not in execution_state:
        logger.error("id {} not found".format(execution_id))
        return "execution id {} not found".format(execution_id), 400

    einfo = execution_state[execution_id]
    runner = einfo[0]
    thread = einfo[1]
    timeout = 30  # seconds to wait for thread death
    if 'timeout' in body:
        timeout = body['timeout']

    runner.cancel()
    while thread.is_alive() and timeout > 0:
        thread.join(1)
        if not thread.is_alive():
            return "execution {} cancelled".format(execution_id), 200
        timeout = timeout - 1
    if timeout == 0:
        return "execution cancel timed out", 500
    return "execution {} cancelled".format(execution_id), 200


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000, threaded=True)