blob: f258e492119496315c4d69f50a6659c7d5bbc9a0 [file] [log] [blame]
peusterme26487b2016-03-08 14:00:21 +01001"""
2This module implements a simple REST API that behaves like SONATA's gatekeeper.
3
4It is only used to support the development of SONATA's SDK tools and to demonstrate
5the year 1 version of the emulator until the integration with WP4's orchestrator is done.
6"""
7
8import logging
9import os
10import uuid
11import hashlib
peusterm26455852016-03-08 14:23:53 +010012import json
peusterme26487b2016-03-08 14:00:21 +010013from flask import Flask, request
14import flask_restful as fr
15
16logging.getLogger("werkzeug").setLevel(logging.WARNING)
17
18
19UPLOAD_FOLDER = "/tmp/son-dummy-gk/uploads/"
20CATALOG_FOLDER = "/tmp/son-dummy-gk/catalog/"
21
22
23class Gatekeeper(object):
24
25 def __init__(self):
26 self.packages = dict()
27 self.instantiations = dict()
28 logging.info("Create SONATA dummy gatekeeper.")
29
30 def unpack_service_package(self, service_uuid):
31 # TODO implement method
32 # 1. unzip *.son file and store contents in CATALOG_FOLDER/services/<service_uuid>/
33 pass
34
35 def start_service(self, service_uuid):
36 # TODO implement method
37 # 1. parse descriptors
38 # 2. do the corresponding dc.startCompute(name="foobar") calls
39 # 3. store references to the compute objects in self.instantiations
40 pass
41
42
43"""
44Resource definitions and API endpoints
45"""
46
47
48class Packages(fr.Resource):
49
50 def post(self):
51 """
peusterm26455852016-03-08 14:23:53 +010052 Upload a *.son service package to the dummy gatekeeper.
53
peusterme26487b2016-03-08 14:00:21 +010054 We expect request with a *.son file and store it in UPLOAD_FOLDER
peusterm26455852016-03-08 14:23:53 +010055 :return: UUID
peusterme26487b2016-03-08 14:00:21 +010056 """
57 try:
58 # get file contents
59 file = request.files['file']
60 # generate a uuid to reference this package
61 service_uuid = str(uuid.uuid4())
62 hash = hashlib.sha1(str(file)).hexdigest()
63 # ensure that upload folder exists
64 ensure_dir(UPLOAD_FOLDER)
65 upload_path = os.path.join(UPLOAD_FOLDER, "%s.son" % service_uuid)
66 # store *.son file to disk
67 file.save(upload_path)
68 size = os.path.getsize(upload_path)
69 # store a reference to the uploaded package in our gatekeeper
70 GK.packages[service_uuid] = upload_path
71 # generate the JSON result
72 return {"service_uuid": service_uuid, "size": size, "sha1": hash, "error": None}
73 except Exception as ex:
74 logging.exception("Service package upload failed:")
75 return {"service_uuid": None, "size": 0, "sha1": None, "error": "upload failed"}
76
77 def get(self):
peusterm26455852016-03-08 14:23:53 +010078 """
79 Return a list of UUID's of uploaded service packages.
80 :return: dict/list
81 """
peusterme26487b2016-03-08 14:00:21 +010082 return {"service_uuid_list": list(GK.packages.iterkeys())}
83
84
85class Instantiations(fr.Resource):
86
87 def post(self):
peusterm26455852016-03-08 14:23:53 +010088 """
89 Instantiate a service specified by its UUID.
90 Will return a new UUID to identify the running service instance.
91 :return: UUID
92 """
93 # TODO implement method (start real service)
94 json_data = request.get_json(force=True)
95 service_uuid = json_data.get("service_uuid")
96 if service_uuid is not None:
97 service_instance_uuid = str(uuid.uuid4())
98 GK.instantiations[service_instance_uuid] = service_uuid
99 logging.info("Starting service %r" % service_uuid)
100 return {"service_instance_uuid": service_instance_uuid}
101 return None
peusterme26487b2016-03-08 14:00:21 +0100102
103 def get(self):
peusterm26455852016-03-08 14:23:53 +0100104 """
105 Returns a list of UUIDs containing all running services.
106 :return: dict / list
107 """
peusterme26487b2016-03-08 14:00:21 +0100108 # TODO implement method
peusterm26455852016-03-08 14:23:53 +0100109 return {"service_instance_uuid_list": list(GK.instantiations.iterkeys())}
peusterme26487b2016-03-08 14:00:21 +0100110
111# create a single, global GK object
112GK = Gatekeeper()
113# setup Flask
114app = Flask(__name__)
115app.config['MAX_CONTENT_LENGTH'] = 512 * 1024 * 1024 # 512 MB max upload
116api = fr.Api(app)
117# define endpoints
118api.add_resource(Packages, '/api/packages/uploads')
119api.add_resource(Instantiations, '/api/instantiations')
120
121
122def start_rest_api(host, port):
123 # start the Flask server (not the best performance but ok for our use case)
124 app.run(host=host,
125 port=port,
126 debug=True,
127 use_reloader=False # this is needed to run Flask in a non-main thread
128 )
129
130
131def ensure_dir(name):
132 if not os.path.exists(name):
133 os.makedirs(name)
134
135
136if __name__ == '__main__':
137 """
138 Lets allow to run the API in standalone mode.
139 """
140 logging.getLogger("werkzeug").setLevel(logging.INFO)
141 start_rest_api("0.0.0.0", 8000)
142