Access to DC list in dummy gk
[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 import yaml
14 from docker import Client as DockerClient
15 from flask import Flask, request
16 import flask_restful as fr
17
18 LOG = logging.getLogger("sonata-dummy-gatekeeper")
19 LOG.setLevel(logging.DEBUG)
20 logging.getLogger("werkzeug").setLevel(logging.WARNING)
21
22
23 UPLOAD_FOLDER = "/tmp/son-dummy-gk/uploads/"
24 CATALOG_FOLDER = "/tmp/son-dummy-gk/catalog/"
25
26
27 class Gatekeeper(object):
28
29 def __init__(self):
30 self.services = dict()
31 self.dcs = list()
32 LOG.info("Create SONATA dummy gatekeeper.")
33
34 def register_service_package(self, service_uuid, service):
35 """
36 register new service package
37 :param service_uuid
38 :param service object
39 """
40 self.services[service_uuid] = service
41 # lets perform all steps needed to onboard the service
42 service.onboard()
43
44
45 class Service(object):
46 """
47 This class represents a NS uploaded as a *.son package to the
48 dummy gatekeeper.
49 Can have multiple running instances of this service.
50 """
51
52 def __init__(self,
53 service_uuid,
54 package_file_hash,
55 package_file_path):
56 self.uuid = service_uuid
57 self.package_file_hash = package_file_hash
58 self.package_file_path = package_file_path
59 self.package_content_path = os.path.join(CATALOG_FOLDER, "services/%s" % self.uuid)
60 self.manifest = None
61 self.nsd = None
62 self.vnfds = dict()
63 self.local_docker_files = dict()
64 self.instances = dict()
65
66 def start_service(self):
67 # TODO implement method
68 instance_uuid = str(uuid.uuid4())
69 # 1. parse descriptors and get name of each docker container
70 for vnfd in self.vnfds.itervalues():
71 for u in vnfd.get("virtual_deployment_units"):
72 docker_name = u.get("vm_image")
73 # 2. do the corresponding dc.startCompute(name="foobar") calls
74 print "start %r" % docker_name
75 print "available dcs: %r " % GK.dcs
76 # 3. store references to the compute objects in self.instantiations
77 return instance_uuid
78
79 def onboard(self):
80 """
81 Do all steps to prepare this service to be instantiated
82 :return:
83 """
84 # 1. extract the contents of the package and store them in our catalog
85 self._unpack_service_package()
86 # 2. read in all descriptor files
87 self._load_package_descriptor()
88 self._load_nsd()
89 self._load_vnfd()
90 self._load_docker_files()
91 # 3. prepare container images (e.g. download or build Dockerfile)
92 self._build_images_from_dockerfiles()
93 self._download_predefined_dockerimages()
94
95 LOG.info("On-boarded service: %r" % self.manifest.get("package_name"))
96
97 def _unpack_service_package(self):
98 """
99 unzip *.son file and store contents in CATALOG_FOLDER/services/<service_uuid>/
100 """
101 with zipfile.ZipFile(self.package_file_path, "r") as z:
102 z.extractall(self.package_content_path)
103
104 def _load_package_descriptor(self):
105 """
106 Load the main package descriptor YAML and keep it as dict.
107 :return:
108 """
109 self.manifest = load_yaml(
110 os.path.join(
111 self.package_content_path, "META-INF/MANIFEST.MF"))
112
113 def _load_nsd(self):
114 """
115 Load the entry NSD YAML and keep it as dict.
116 :return:
117 """
118 if "entry_service_template" in self.manifest:
119 nsd_path = os.path.join(
120 self.package_content_path,
121 make_relative_path(self.manifest.get("entry_service_template")))
122 self.nsd = load_yaml(nsd_path)
123 LOG.debug("Loaded NSD: %r" % self.nsd.get("ns_name"))
124
125 def _load_vnfd(self):
126 """
127 Load all VNFD YAML files referenced in MANIFEST.MF and keep them in dict.
128 :return:
129 """
130 if "package_content" in self.manifest:
131 for pc in self.manifest.get("package_content"):
132 if pc.get("content-type") == "application/sonata.function_descriptor":
133 vnfd_path = os.path.join(
134 self.package_content_path,
135 make_relative_path(pc.get("name")))
136 vnfd = load_yaml(vnfd_path)
137 self.vnfds[vnfd.get("vnf_name")] = vnfd
138 LOG.debug("Loaded VNFD: %r" % vnfd.get("vnf_name"))
139
140 def _load_docker_files(self):
141 """
142 Get all paths to Dockerfiles from MANIFEST.MF and store them in dict.
143 :return:
144 """
145 if "package_content" in self.manifest:
146 for df in self.manifest.get("package_content"):
147 if df.get("content-type") == "application/sonata.docker_files":
148 docker_path = os.path.join(
149 self.package_content_path,
150 make_relative_path(df.get("name")))
151 # FIXME: Mapping to docker image names is hardcoded because of the missing mapping in the example package
152 self.local_docker_files[helper_map_docker_name(df.get("name"))] = docker_path
153 LOG.debug("Found Dockerfile: %r" % docker_path)
154
155 def _build_images_from_dockerfiles(self):
156 """
157 Build Docker images for each local Dockerfile found in the package: self.local_docker_files
158 """
159 dc = DockerClient()
160 LOG.info("Building %d Docker images (this may take several minutes) ..." % len(self.local_docker_files))
161 for k, v in self.local_docker_files.iteritems():
162 for line in dc.build(path=v.replace("Dockerfile", ""), tag=k, rm=False, nocache=False):
163 LOG.debug("DOCKER BUILD: %s" % line)
164 LOG.info("Docker image created: %s" % k)
165
166 def _download_predefined_dockerimages(self):
167 """
168 If the package contains URLs to pre-build Docker images, we download them with this method.
169 """
170 # TODO implement
171 pass
172
173
174 """
175 Resource definitions and API endpoints
176 """
177
178
179 class Packages(fr.Resource):
180
181 def post(self):
182 """
183 Upload a *.son service package to the dummy gatekeeper.
184
185 We expect request with a *.son file and store it in UPLOAD_FOLDER
186 :return: UUID
187 """
188 try:
189 # get file contents
190 son_file = request.files['file']
191 # generate a uuid to reference this package
192 service_uuid = str(uuid.uuid4())
193 file_hash = hashlib.sha1(str(son_file)).hexdigest()
194 # ensure that upload folder exists
195 ensure_dir(UPLOAD_FOLDER)
196 upload_path = os.path.join(UPLOAD_FOLDER, "%s.son" % service_uuid)
197 # store *.son file to disk
198 son_file.save(upload_path)
199 size = os.path.getsize(upload_path)
200 # create a service object and register it
201 s = Service(service_uuid, file_hash, upload_path)
202 GK.register_service_package(service_uuid, s)
203 # generate the JSON result
204 return {"service_uuid": service_uuid, "size": size, "sha1": file_hash, "error": None}
205 except Exception as ex:
206 LOG.exception("Service package upload failed:")
207 return {"service_uuid": None, "size": 0, "sha1": None, "error": "upload failed"}
208
209 def get(self):
210 """
211 Return a list of UUID's of uploaded service packages.
212 :return: dict/list
213 """
214 return {"service_uuid_list": list(GK.services.iterkeys())}
215
216
217 class Instantiations(fr.Resource):
218
219 def post(self):
220 """
221 Instantiate a service specified by its UUID.
222 Will return a new UUID to identify the running service instance.
223 :return: UUID
224 """
225 # TODO implement method (start real service)
226 json_data = request.get_json(force=True)
227 service_uuid = list(GK.services.iterkeys())[0] #json_data.get("service_uuid") # TODO only for quick testing
228 if service_uuid in GK.services:
229 LOG.info("Starting service %r" % service_uuid)
230 service_instance_uuid = GK.services.get(service_uuid).start_service()
231 LOG.info("Service started. Instance id: %r" % service_instance_uuid)
232 return {"service_instance_uuid": service_instance_uuid}
233 return "Service not found", 404
234
235 def get(self):
236 """
237 Returns a list of UUIDs containing all running services.
238 :return: dict / list
239 """
240 # TODO implement method
241 return {"service_instance_uuid_list": list()}
242
243
244 # create a single, global GK object
245 GK = Gatekeeper()
246 # setup Flask
247 app = Flask(__name__)
248 app.config['MAX_CONTENT_LENGTH'] = 512 * 1024 * 1024 # 512 MB max upload
249 api = fr.Api(app)
250 # define endpoints
251 api.add_resource(Packages, '/api/packages')
252 api.add_resource(Instantiations, '/api/instantiations')
253
254
255 def start_rest_api(host, port, datacenters=list()):
256 GK.dcs = datacenters
257 # start the Flask server (not the best performance but ok for our use case)
258 app.run(host=host,
259 port=port,
260 debug=True,
261 use_reloader=False # this is needed to run Flask in a non-main thread
262 )
263
264
265 def ensure_dir(name):
266 if not os.path.exists(name):
267 os.makedirs(name)
268
269
270 def load_yaml(path):
271 with open(path, "r") as f:
272 try:
273 r = yaml.load(f)
274 except yaml.YAMLError as exc:
275 LOG.exception("YAML parse error")
276 r = dict()
277 return r
278
279
280 def make_relative_path(path):
281 if path.startswith("/"):
282 return path.replace("/", "", 1)
283 return path
284
285
286 def helper_map_docker_name(name):
287 """
288 Quick hack to fix missing dependency in example package.
289 """
290 # TODO remove this when package description is fixed
291 mapping = {
292 "/docker_files/iperf/Dockerfile": "iperf_docker",
293 "/docker_files/firewall/Dockerfile": "fw_docker",
294 "/docker_files/tcpdump/Dockerfile": "tcpdump_docker"
295 }
296 return mapping.get(name)
297
298
299 if __name__ == '__main__':
300 """
301 Lets allow to run the API in standalone mode.
302 """
303 logging.getLogger("werkzeug").setLevel(logging.INFO)
304 start_rest_api("0.0.0.0", 8000)
305