Cleanup of GK API. Created Service class. Added unzipping functionality.
[osm/vim-emu.git] / src / emuvim / api / sonata / dummygatekeeper.py
1 """
2 This module implements a simple REST API that behaves like SONATA's gatekeeper.
3
4 It is only used to support the development of SONATA's SDK tools and to demonstrate
5 the year 1 version of the emulator until the integration with WP4's orchestrator is done.
6 """
7
8 import logging
9 import os
10 import uuid
11 import hashlib
12 import zipfile
13 from flask import Flask, request
14 import flask_restful as fr
15
16 LOG = logging.getLogger("sonata-dummy-gatekeeper")
17 LOG.setLevel(logging.DEBUG)
18 logging.getLogger("werkzeug").setLevel(logging.WARNING)
19
20
21 UPLOAD_FOLDER = "/tmp/son-dummy-gk/uploads/"
22 CATALOG_FOLDER = "/tmp/son-dummy-gk/catalog/"
23
24
25 class Gatekeeper(object):
26
27 def __init__(self):
28 self.services = dict()
29 LOG.info("Create SONATA dummy gatekeeper.")
30
31 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
42 class 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)
59
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
67 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
88
89 """
90 Resource definitions and API endpoints
91 """
92
93
94 class Packages(fr.Resource):
95
96 def post(self):
97 """
98 Upload a *.son service package to the dummy gatekeeper.
99
100 We expect request with a *.son file and store it in UPLOAD_FOLDER
101 :return: UUID
102 """
103 try:
104 # get file contents
105 son_file = request.files['file']
106 # generate a uuid to reference this package
107 service_uuid = str(uuid.uuid4())
108 file_hash = hashlib.sha1(str(son_file)).hexdigest()
109 # 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
113 son_file.save(upload_path)
114 size = os.path.getsize(upload_path)
115 # create a service object and register it
116 s = Service(service_uuid, file_hash, upload_path)
117 GK.register_service_package(service_uuid, s)
118 # generate the JSON result
119 return {"service_uuid": service_uuid, "size": size, "sha1": file_hash, "error": None}
120 except Exception as ex:
121 LOG.exception("Service package upload failed:")
122 return {"service_uuid": None, "size": 0, "sha1": None, "error": "upload failed"}
123
124 def get(self):
125 """
126 Return a list of UUID's of uploaded service packages.
127 :return: dict/list
128 """
129 return {"service_uuid_list": list(GK.services.iterkeys())}
130
131
132 class Instantiations(fr.Resource):
133
134 def post(self):
135 """
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())
145 LOG.info("Starting service %r" % service_uuid)
146 return {"service_instance_uuid": service_instance_uuid}
147 return None
148
149 def get(self):
150 """
151 Returns a list of UUIDs containing all running services.
152 :return: dict / list
153 """
154 # TODO implement method
155 return {"service_instance_uuid_list": list()}
156
157
158 # create a single, global GK object
159 GK = Gatekeeper()
160 # setup Flask
161 app = Flask(__name__)
162 app.config['MAX_CONTENT_LENGTH'] = 512 * 1024 * 1024 # 512 MB max upload
163 api = fr.Api(app)
164 # define endpoints
165 api.add_resource(Packages, '/api/packages')
166 api.add_resource(Instantiations, '/api/instantiations')
167
168
169 def 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
178 def ensure_dir(name):
179 if not os.path.exists(name):
180 os.makedirs(name)
181
182
183 if __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