blob: 71fd94c6b30abb2c464685698083bfe80edfc3cd [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
peusterm786cd542016-03-14 14:12:17 +010012import zipfile
peusterme26487b2016-03-08 14:00:21 +010013from flask import Flask, request
14import flask_restful as fr
15
peusterm786cd542016-03-14 14:12:17 +010016LOG = logging.getLogger("sonata-dummy-gatekeeper")
17LOG.setLevel(logging.DEBUG)
peusterme26487b2016-03-08 14:00:21 +010018logging.getLogger("werkzeug").setLevel(logging.WARNING)
19
20
21UPLOAD_FOLDER = "/tmp/son-dummy-gk/uploads/"
22CATALOG_FOLDER = "/tmp/son-dummy-gk/catalog/"
23
24
25class Gatekeeper(object):
26
27 def __init__(self):
peusterm786cd542016-03-14 14:12:17 +010028 self.services = dict()
29 LOG.info("Create SONATA dummy gatekeeper.")
peusterme26487b2016-03-08 14:00:21 +010030
peusterm786cd542016-03-14 14:12:17 +010031 def register_service_package(self, service_uuid, service):
32 """
33 register new service package
34 :param service_uuid
35 :param service object
36 """
37 self.services[service_uuid] = service
38 # lets perform all steps needed to onboard the service
39 service.onboard()
40
41
42class Service(object):
43 """
44 This class represents a NS uploaded as a *.son package to the
45 dummy gatekeeper.
46 Can have multiple running instances of this service.
47 """
48
49 def __init__(self,
50 service_uuid,
51 package_file_hash,
52 package_file_path):
53 self.uuid = service_uuid
54 self.package_file_hash = package_file_hash
55 self.package_file_path = package_file_path
56 self.package_content_path = os.path.join(CATALOG_FOLDER, "services/%s" % self.uuid)
57 self.instances = dict()
58 LOG.info("Created service: %r" % self.uuid)
peusterme26487b2016-03-08 14:00:21 +010059
60 def start_service(self, service_uuid):
61 # TODO implement method
62 # 1. parse descriptors
63 # 2. do the corresponding dc.startCompute(name="foobar") calls
64 # 3. store references to the compute objects in self.instantiations
65 pass
66
peusterm786cd542016-03-14 14:12:17 +010067 def onboard(self):
68 """
69 Do all steps to prepare this service to be instantiated
70 :return:
71 """
72 # 1. extract the contents of the package and store them in our catalog
73 self._unpack_service_package()
74 # 2. read in all descriptor files
75 # 3. prepare container images (e.g. download or build Dockerfile)
76
77 def _unpack_service_package(self):
78 """
79 unzip *.son file and store contents in CATALOG_FOLDER/services/<service_uuid>/
80 """
81 with zipfile.ZipFile(self.package_file_path, "r") as z:
82 z.extractall(self.package_content_path)
83
84 def _build_images_from_dockerfile(self):
85 pass
86 # TODO implement
87
peusterme26487b2016-03-08 14:00:21 +010088
89"""
90Resource definitions and API endpoints
91"""
92
93
94class Packages(fr.Resource):
95
96 def post(self):
97 """
peusterm26455852016-03-08 14:23:53 +010098 Upload a *.son service package to the dummy gatekeeper.
99
peusterme26487b2016-03-08 14:00:21 +0100100 We expect request with a *.son file and store it in UPLOAD_FOLDER
peusterm26455852016-03-08 14:23:53 +0100101 :return: UUID
peusterme26487b2016-03-08 14:00:21 +0100102 """
103 try:
104 # get file contents
peusterm786cd542016-03-14 14:12:17 +0100105 son_file = request.files['file']
peusterme26487b2016-03-08 14:00:21 +0100106 # generate a uuid to reference this package
107 service_uuid = str(uuid.uuid4())
peusterm786cd542016-03-14 14:12:17 +0100108 file_hash = hashlib.sha1(str(son_file)).hexdigest()
peusterme26487b2016-03-08 14:00:21 +0100109 # ensure that upload folder exists
110 ensure_dir(UPLOAD_FOLDER)
111 upload_path = os.path.join(UPLOAD_FOLDER, "%s.son" % service_uuid)
112 # store *.son file to disk
peusterm786cd542016-03-14 14:12:17 +0100113 son_file.save(upload_path)
peusterme26487b2016-03-08 14:00:21 +0100114 size = os.path.getsize(upload_path)
peusterm786cd542016-03-14 14:12:17 +0100115 # create a service object and register it
116 s = Service(service_uuid, file_hash, upload_path)
117 GK.register_service_package(service_uuid, s)
peusterme26487b2016-03-08 14:00:21 +0100118 # generate the JSON result
peusterm786cd542016-03-14 14:12:17 +0100119 return {"service_uuid": service_uuid, "size": size, "sha1": file_hash, "error": None}
peusterme26487b2016-03-08 14:00:21 +0100120 except Exception as ex:
peusterm786cd542016-03-14 14:12:17 +0100121 LOG.exception("Service package upload failed:")
peusterme26487b2016-03-08 14:00:21 +0100122 return {"service_uuid": None, "size": 0, "sha1": None, "error": "upload failed"}
123
124 def get(self):
peusterm26455852016-03-08 14:23:53 +0100125 """
126 Return a list of UUID's of uploaded service packages.
127 :return: dict/list
128 """
peusterm786cd542016-03-14 14:12:17 +0100129 return {"service_uuid_list": list(GK.services.iterkeys())}
peusterme26487b2016-03-08 14:00:21 +0100130
131
132class Instantiations(fr.Resource):
133
134 def post(self):
peusterm26455852016-03-08 14:23:53 +0100135 """
136 Instantiate a service specified by its UUID.
137 Will return a new UUID to identify the running service instance.
138 :return: UUID
139 """
140 # TODO implement method (start real service)
141 json_data = request.get_json(force=True)
142 service_uuid = json_data.get("service_uuid")
143 if service_uuid is not None:
144 service_instance_uuid = str(uuid.uuid4())
peusterm786cd542016-03-14 14:12:17 +0100145 LOG.info("Starting service %r" % service_uuid)
peusterm26455852016-03-08 14:23:53 +0100146 return {"service_instance_uuid": service_instance_uuid}
147 return None
peusterme26487b2016-03-08 14:00:21 +0100148
149 def get(self):
peusterm26455852016-03-08 14:23:53 +0100150 """
151 Returns a list of UUIDs containing all running services.
152 :return: dict / list
153 """
peusterme26487b2016-03-08 14:00:21 +0100154 # TODO implement method
peusterm786cd542016-03-14 14:12:17 +0100155 return {"service_instance_uuid_list": list()}
156
peusterme26487b2016-03-08 14:00:21 +0100157
158# create a single, global GK object
159GK = Gatekeeper()
160# setup Flask
161app = Flask(__name__)
162app.config['MAX_CONTENT_LENGTH'] = 512 * 1024 * 1024 # 512 MB max upload
163api = fr.Api(app)
164# define endpoints
peusterm786cd542016-03-14 14:12:17 +0100165api.add_resource(Packages, '/api/packages')
peusterme26487b2016-03-08 14:00:21 +0100166api.add_resource(Instantiations, '/api/instantiations')
167
168
169def start_rest_api(host, port):
170 # start the Flask server (not the best performance but ok for our use case)
171 app.run(host=host,
172 port=port,
173 debug=True,
174 use_reloader=False # this is needed to run Flask in a non-main thread
175 )
176
177
178def ensure_dir(name):
179 if not os.path.exists(name):
180 os.makedirs(name)
181
182
183if __name__ == '__main__':
184 """
185 Lets allow to run the API in standalone mode.
186 """
187 logging.getLogger("werkzeug").setLevel(logging.INFO)
188 start_rest_api("0.0.0.0", 8000)
189