Merge pull request #93 from mpeuster/master
[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 logging.basicConfig()
19 LOG = logging.getLogger("sonata-dummy-gatekeeper")
20 LOG.setLevel(logging.DEBUG)
21 logging.getLogger("werkzeug").setLevel(logging.WARNING)
22
23 GK_STORAGE = "/tmp/son-dummy-gk/"
24 UPLOAD_FOLDER = os.path.join(GK_STORAGE, "uploads/")
25 CATALOG_FOLDER = os.path.join(GK_STORAGE, "catalog/")
26
27 # Enable Dockerfile build functionality
28 BUILD_DOCKERFILE = False
29
30 # flag to indicate that we run without the emulator (only the bare API for integration testing)
31 GK_STANDALONE_MODE = False
32
33 # should a new version of an image be pulled even if its available
34 FORCE_PULL = True
35
36
37 class Gatekeeper(object):
38
39 def __init__(self):
40 self.services = dict()
41 self.dcs = dict()
42 self.vnf_counter = 0 # used to generate short names for VNFs (Mininet limitation)
43 LOG.info("Create SONATA dummy gatekeeper.")
44
45 def register_service_package(self, service_uuid, service):
46 """
47 register new service package
48 :param service_uuid
49 :param service object
50 """
51 self.services[service_uuid] = service
52 # lets perform all steps needed to onboard the service
53 service.onboard()
54
55 def get_next_vnf_name(self):
56 self.vnf_counter += 1
57 return "vnf%d" % self.vnf_counter
58
59
60 class Service(object):
61 """
62 This class represents a NS uploaded as a *.son package to the
63 dummy gatekeeper.
64 Can have multiple running instances of this service.
65 """
66
67 def __init__(self,
68 service_uuid,
69 package_file_hash,
70 package_file_path):
71 self.uuid = service_uuid
72 self.package_file_hash = package_file_hash
73 self.package_file_path = package_file_path
74 self.package_content_path = os.path.join(CATALOG_FOLDER, "services/%s" % self.uuid)
75 self.manifest = None
76 self.nsd = None
77 self.vnfds = dict()
78 self.local_docker_files = dict()
79 self.remote_docker_image_urls = dict()
80 self.instances = dict()
81
82 def onboard(self):
83 """
84 Do all steps to prepare this service to be instantiated
85 :return:
86 """
87 # 1. extract the contents of the package and store them in our catalog
88 self._unpack_service_package()
89 # 2. read in all descriptor files
90 self._load_package_descriptor()
91 self._load_nsd()
92 self._load_vnfd()
93 # 3. prepare container images (e.g. download or build Dockerfile)
94 if BUILD_DOCKERFILE:
95 self._load_docker_files()
96 self._build_images_from_dockerfiles()
97 else:
98 self._load_docker_urls()
99 self._pull_predefined_dockerimages()
100 LOG.info("On-boarded service: %r" % self.manifest.get("package_name"))
101
102 def start_service(self):
103 """
104 This methods creates and starts a new service instance.
105 It computes placements, iterates over all VNFDs, and starts
106 each VNFD as a Docker container in the data center selected
107 by the placement algorithm.
108 :return:
109 """
110 LOG.info("Starting service %r" % self.uuid)
111 # 1. each service instance gets a new uuid to identify it
112 instance_uuid = str(uuid.uuid4())
113 # build a instances dict (a bit like a NSR :))
114 self.instances[instance_uuid] = dict()
115 self.instances[instance_uuid]["vnf_instances"] = list()
116 # 2. compute placement of this service instance (adds DC names to VNFDs)
117 if not GK_STANDALONE_MODE:
118 self._calculate_placement(FirstDcPlacement)
119 # iterate over all vnfds that we have to start
120 for vnfd in self.vnfds.itervalues():
121 vnfi = None
122 if not GK_STANDALONE_MODE:
123 vnfi = self._start_vnfd(vnfd)
124 self.instances[instance_uuid]["vnf_instances"].append(vnfi)
125 LOG.info("Service started. Instance id: %r" % instance_uuid)
126 return instance_uuid
127
128 def _start_vnfd(self, vnfd):
129 """
130 Start a single VNFD of this service
131 :param vnfd: vnfd descriptor dict
132 :return:
133 """
134 # iterate over all deployment units within each VNFDs
135 for u in vnfd.get("virtual_deployment_units"):
136 # 1. get the name of the docker image to start and the assigned DC
137 vnf_name = vnfd.get("name")
138 if vnf_name not in self.remote_docker_image_urls:
139 raise Exception("No image name for %r found. Abort." % vnf_name)
140 docker_name = self.remote_docker_image_urls.get(vnf_name)
141 target_dc = vnfd.get("dc")
142 # 2. perform some checks to ensure we can start the container
143 assert(docker_name is not None)
144 assert(target_dc is not None)
145 if not self._check_docker_image_exists(docker_name):
146 raise Exception("Docker image %r not found. Abort." % docker_name)
147 # 3. do the dc.startCompute(name="foobar") call to run the container
148 # TODO consider flavors, and other annotations
149 vnfi = target_dc.startCompute(GK.get_next_vnf_name(), image=docker_name, flavor_name="small")
150 # 6. store references to the compute objects in self.instances
151 return vnfi
152
153 def _unpack_service_package(self):
154 """
155 unzip *.son file and store contents in CATALOG_FOLDER/services/<service_uuid>/
156 """
157 LOG.info("Unzipping: %r" % self.package_file_path)
158 with zipfile.ZipFile(self.package_file_path, "r") as z:
159 z.extractall(self.package_content_path)
160
161
162 def _load_package_descriptor(self):
163 """
164 Load the main package descriptor YAML and keep it as dict.
165 :return:
166 """
167 self.manifest = load_yaml(
168 os.path.join(
169 self.package_content_path, "META-INF/MANIFEST.MF"))
170
171 def _load_nsd(self):
172 """
173 Load the entry NSD YAML and keep it as dict.
174 :return:
175 """
176 if "entry_service_template" in self.manifest:
177 nsd_path = os.path.join(
178 self.package_content_path,
179 make_relative_path(self.manifest.get("entry_service_template")))
180 self.nsd = load_yaml(nsd_path)
181 LOG.debug("Loaded NSD: %r" % self.nsd.get("name"))
182
183 def _load_vnfd(self):
184 """
185 Load all VNFD YAML files referenced in MANIFEST.MF and keep them in dict.
186 :return:
187 """
188 if "package_content" in self.manifest:
189 for pc in self.manifest.get("package_content"):
190 if pc.get("content-type") == "application/sonata.function_descriptor":
191 vnfd_path = os.path.join(
192 self.package_content_path,
193 make_relative_path(pc.get("name")))
194 vnfd = load_yaml(vnfd_path)
195 self.vnfds[vnfd.get("name")] = vnfd
196 LOG.debug("Loaded VNFD: %r" % vnfd.get("name"))
197
198 def _load_docker_files(self):
199 """
200 Get all paths to Dockerfiles from VNFDs and store them in dict.
201 :return:
202 """
203 for k, v in self.vnfds.iteritems():
204 for vu in v.get("virtual_deployment_units"):
205 if vu.get("vm_image_format") == "docker":
206 vm_image = vu.get("vm_image")
207 docker_path = os.path.join(
208 self.package_content_path,
209 make_relative_path(vm_image))
210 self.local_docker_files[k] = docker_path
211 LOG.debug("Found Dockerfile (%r): %r" % (k, docker_path))
212
213 def _load_docker_urls(self):
214 """
215 Get all URLs to pre-build docker images in some repo.
216 :return:
217 """
218 for k, v in self.vnfds.iteritems():
219 for vu in v.get("virtual_deployment_units"):
220 if vu.get("vm_image_format") == "docker":
221 url = vu.get("vm_image")
222 if url is not None:
223 url = url.replace("http://", "")
224 self.remote_docker_image_urls[k] = url
225 LOG.debug("Found Docker image URL (%r): %r" % (k, self.remote_docker_image_urls[k]))
226
227 def _build_images_from_dockerfiles(self):
228 """
229 Build Docker images for each local Dockerfile found in the package: self.local_docker_files
230 """
231 if GK_STANDALONE_MODE:
232 return # do not build anything in standalone mode
233 dc = DockerClient()
234 LOG.info("Building %d Docker images (this may take several minutes) ..." % len(self.local_docker_files))
235 for k, v in self.local_docker_files.iteritems():
236 for line in dc.build(path=v.replace("Dockerfile", ""), tag=k, rm=False, nocache=False):
237 LOG.debug("DOCKER BUILD: %s" % line)
238 LOG.info("Docker image created: %s" % k)
239
240 def _pull_predefined_dockerimages(self):
241 """
242 If the package contains URLs to pre-build Docker images, we download them with this method.
243 """
244 dc = DockerClient()
245 for url in self.remote_docker_image_urls.itervalues():
246 if not FORCE_PULL: # only pull if not present (speedup for development)
247 if len(dc.images(name=url)) > 0:
248 LOG.debug("Image %r present. Skipping pull." % url)
249 continue
250 LOG.info("Pulling image: %r" % url)
251 dc.pull(url,
252 insecure_registry=True)
253
254 def _check_docker_image_exists(self, image_name):
255 """
256 Query the docker service and check if the given image exists
257 :param image_name: name of the docker image
258 :return:
259 """
260 return len(DockerClient().images(image_name)) > 0
261
262 def _calculate_placement(self, algorithm):
263 """
264 Do placement by adding the a field "dc" to
265 each VNFD that points to one of our
266 data center objects known to the gatekeeper.
267 """
268 assert(len(self.vnfds) > 0)
269 assert(len(GK.dcs) > 0)
270 # instantiate algorithm an place
271 p = algorithm()
272 p.place(self.nsd, self.vnfds, GK.dcs)
273 LOG.info("Using placement algorithm: %r" % p.__class__.__name__)
274 # lets print the placement result
275 for name, vnfd in self.vnfds.iteritems():
276 LOG.info("Placed VNF %r on DC %r" % (name, str(vnfd.get("dc"))))
277
278
279 """
280 Some (simple) placement algorithms
281 """
282
283
284 class FirstDcPlacement(object):
285 """
286 Placement: Always use one and the same data center from the GK.dcs dict.
287 """
288 def place(self, nsd, vnfds, dcs):
289 for name, vnfd in vnfds.iteritems():
290 vnfd["dc"] = list(dcs.itervalues())[0]
291
292
293 """
294 Resource definitions and API endpoints
295 """
296
297
298 class Packages(fr.Resource):
299
300 def post(self):
301 """
302 Upload a *.son service package to the dummy gatekeeper.
303
304 We expect request with a *.son file and store it in UPLOAD_FOLDER
305 :return: UUID
306 """
307 try:
308 # get file contents
309 print(request.files)
310 # lets search for the package in the request
311 if "package" in request.files:
312 son_file = request.files["package"]
313 # elif "file" in request.files:
314 # son_file = request.files["file"]
315 else:
316 return {"service_uuid": None, "size": 0, "sha1": None, "error": "upload failed. file not found."}, 500
317 # generate a uuid to reference this package
318 service_uuid = str(uuid.uuid4())
319 file_hash = hashlib.sha1(str(son_file)).hexdigest()
320 # ensure that upload folder exists
321 ensure_dir(UPLOAD_FOLDER)
322 upload_path = os.path.join(UPLOAD_FOLDER, "%s.son" % service_uuid)
323 # store *.son file to disk
324 son_file.save(upload_path)
325 size = os.path.getsize(upload_path)
326 # create a service object and register it
327 s = Service(service_uuid, file_hash, upload_path)
328 GK.register_service_package(service_uuid, s)
329 # generate the JSON result
330 return {"service_uuid": service_uuid, "size": size, "sha1": file_hash, "error": None}
331 except Exception as ex:
332 LOG.exception("Service package upload failed:")
333 return {"service_uuid": None, "size": 0, "sha1": None, "error": "upload failed"}, 500
334
335 def get(self):
336 """
337 Return a list of UUID's of uploaded service packages.
338 :return: dict/list
339 """
340 return {"service_uuid_list": list(GK.services.iterkeys())}
341
342
343 class Instantiations(fr.Resource):
344
345 def post(self):
346 """
347 Instantiate a service specified by its UUID.
348 Will return a new UUID to identify the running service instance.
349 :return: UUID
350 """
351 # try to extract the service uuid from the request
352 json_data = request.get_json(force=True)
353 service_uuid = json_data.get("service_uuid")
354
355 # lets be a bit fuzzy here to make testing easier
356 if service_uuid is None and len(GK.services) > 0:
357 # if we don't get a service uuid, we simple start the first service in the list
358 service_uuid = list(GK.services.iterkeys())[0]
359
360 if service_uuid in GK.services:
361 # ok, we have a service uuid, lets start the service
362 service_instance_uuid = GK.services.get(service_uuid).start_service()
363 return {"service_instance_uuid": service_instance_uuid}
364 return "Service not found", 404
365
366 def get(self):
367 """
368 Returns a list of UUIDs containing all running services.
369 :return: dict / list
370 """
371 return {"service_instance_list": [
372 list(s.instances.iterkeys()) for s in GK.services.itervalues()]}
373
374
375 # create a single, global GK object
376 GK = Gatekeeper()
377 # setup Flask
378 app = Flask(__name__)
379 app.config['MAX_CONTENT_LENGTH'] = 512 * 1024 * 1024 # 512 MB max upload
380 api = fr.Api(app)
381 # define endpoints
382 api.add_resource(Packages, '/packages')
383 api.add_resource(Instantiations, '/instantiations')
384
385
386 def start_rest_api(host, port, datacenters=dict()):
387 GK.dcs = datacenters
388 # start the Flask server (not the best performance but ok for our use case)
389 app.run(host=host,
390 port=port,
391 debug=True,
392 use_reloader=False # this is needed to run Flask in a non-main thread
393 )
394
395
396 def ensure_dir(name):
397 if not os.path.exists(name):
398 os.makedirs(name)
399
400
401 def load_yaml(path):
402 with open(path, "r") as f:
403 try:
404 r = yaml.load(f)
405 except yaml.YAMLError as exc:
406 LOG.exception("YAML parse error")
407 r = dict()
408 return r
409
410
411 def make_relative_path(path):
412 if path.startswith("file://"):
413 path = path.replace("file://", "", 1)
414 if path.startswith("/"):
415 path = path.replace("/", "", 1)
416 return path
417
418
419 if __name__ == '__main__':
420 """
421 Lets allow to run the API in standalone mode.
422 """
423 GK_STANDALONE_MODE = True
424 logging.getLogger("werkzeug").setLevel(logging.INFO)
425 start_rest_api("0.0.0.0", 8000)
426