blob: 8423a31622f6f2e7173be243ecab9021fbd0901c [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
peusterm7ec665d2016-03-14 15:20:44 +010013import yaml
peustermbdfab7e2016-03-14 16:03:30 +010014from docker import Client as DockerClient
peusterme26487b2016-03-08 14:00:21 +010015from flask import Flask, request
16import flask_restful as fr
17
peusterm398cd3b2016-03-21 15:04:54 +010018logging.basicConfig()
peusterm786cd542016-03-14 14:12:17 +010019LOG = logging.getLogger("sonata-dummy-gatekeeper")
20LOG.setLevel(logging.DEBUG)
peusterme26487b2016-03-08 14:00:21 +010021logging.getLogger("werkzeug").setLevel(logging.WARNING)
22
peusterm92237dc2016-03-21 15:45:58 +010023GK_STORAGE = "/tmp/son-dummy-gk/"
24UPLOAD_FOLDER = os.path.join(GK_STORAGE, "uploads/")
25CATALOG_FOLDER = os.path.join(GK_STORAGE, "catalog/")
peusterme26487b2016-03-08 14:00:21 +010026
peusterm82d406e2016-05-02 20:52:06 +020027# Enable Dockerfile build functionality
28BUILD_DOCKERFILE = False
29
peusterm398cd3b2016-03-21 15:04:54 +010030# flag to indicate that we run without the emulator (only the bare API for integration testing)
31GK_STANDALONE_MODE = False
32
peusterm56356cb2016-05-03 10:43:43 +020033# should a new version of an image be pulled even if its available
34FORCE_PULL = True
35
peusterme26487b2016-03-08 14:00:21 +010036
37class Gatekeeper(object):
38
39 def __init__(self):
peusterm786cd542016-03-14 14:12:17 +010040 self.services = dict()
peusterm082378b2016-03-16 20:14:22 +010041 self.dcs = dict()
peusterm3444ae42016-03-16 20:46:41 +010042 self.vnf_counter = 0 # used to generate short names for VNFs (Mininet limitation)
peusterm786cd542016-03-14 14:12:17 +010043 LOG.info("Create SONATA dummy gatekeeper.")
peusterme26487b2016-03-08 14:00:21 +010044
peusterm786cd542016-03-14 14:12:17 +010045 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
peusterm3444ae42016-03-16 20:46:41 +010055 def get_next_vnf_name(self):
56 self.vnf_counter += 1
peusterm398cd3b2016-03-21 15:04:54 +010057 return "vnf%d" % self.vnf_counter
peusterm3444ae42016-03-16 20:46:41 +010058
peusterm786cd542016-03-14 14:12:17 +010059
60class 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)
peusterm7ec665d2016-03-14 15:20:44 +010075 self.manifest = None
76 self.nsd = None
77 self.vnfds = dict()
peustermbdfab7e2016-03-14 16:03:30 +010078 self.local_docker_files = dict()
peusterm82d406e2016-05-02 20:52:06 +020079 self.remote_docker_image_urls = dict()
peusterm786cd542016-03-14 14:12:17 +010080 self.instances = dict()
peusterme26487b2016-03-08 14:00:21 +010081
peusterm786cd542016-03-14 14:12:17 +010082 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
peusterm7ec665d2016-03-14 15:20:44 +010090 self._load_package_descriptor()
91 self._load_nsd()
92 self._load_vnfd()
peusterm786cd542016-03-14 14:12:17 +010093 # 3. prepare container images (e.g. download or build Dockerfile)
peusterm82d406e2016-05-02 20:52:06 +020094 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()
peusterm7ec665d2016-03-14 15:20:44 +0100100 LOG.info("On-boarded service: %r" % self.manifest.get("package_name"))
101
peusterm082378b2016-03-16 20:14:22 +0100102 def start_service(self):
peusterm3444ae42016-03-16 20:46:41 +0100103 """
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)
stevenvanrossemd87fe472016-05-11 11:34:34 +0200111
peusterm3444ae42016-03-16 20:46:41 +0100112 # 1. each service instance gets a new uuid to identify it
peusterm082378b2016-03-16 20:14:22 +0100113 instance_uuid = str(uuid.uuid4())
peusterm3444ae42016-03-16 20:46:41 +0100114 # build a instances dict (a bit like a NSR :))
115 self.instances[instance_uuid] = dict()
116 self.instances[instance_uuid]["vnf_instances"] = list()
stevenvanrossemd87fe472016-05-11 11:34:34 +0200117
peusterm3444ae42016-03-16 20:46:41 +0100118 # 2. compute placement of this service instance (adds DC names to VNFDs)
peusterm398cd3b2016-03-21 15:04:54 +0100119 if not GK_STANDALONE_MODE:
120 self._calculate_placement(FirstDcPlacement)
peusterm3444ae42016-03-16 20:46:41 +0100121 # iterate over all vnfds that we have to start
peusterm082378b2016-03-16 20:14:22 +0100122 for vnfd in self.vnfds.itervalues():
peusterm398cd3b2016-03-21 15:04:54 +0100123 vnfi = None
124 if not GK_STANDALONE_MODE:
125 vnfi = self._start_vnfd(vnfd)
126 self.instances[instance_uuid]["vnf_instances"].append(vnfi)
stevenvanrossemd87fe472016-05-11 11:34:34 +0200127
128 # 3. Configure the chaining of the network functions (currently only E-Line links supported)
129 vlinks = self.nsd["virtual_links"]
130 fwd_links = self.nsd["forwarding_graphs"][0]["constituent_virtual_links"]
131 eline_fwd_links = [l for l in vlinks if (l["id"] in fwd_links) and (l["connectivity_type"] == "E-Line")]
132
133 for link in eline_fwd_links:
134 src_node, src_port = link["connection_points_reference"][0].split(":")
135 dst_node, dst_port = link["connection_points_reference"][1].split(":")
136
peusterm3b216492016-05-11 16:25:50 +0200137 if src_node in self.vnfds:
138 network = self.vnfds[src_node].get("dc").net # there should be a cleaner way to find the DCNetwork
139 network.setChain(src_node, dst_node, vnf_src_interface=src_port, vnf_dst_interface=dst_port)
stevenvanrossemd87fe472016-05-11 11:34:34 +0200140
peusterm3444ae42016-03-16 20:46:41 +0100141 LOG.info("Service started. Instance id: %r" % instance_uuid)
peusterm082378b2016-03-16 20:14:22 +0100142 return instance_uuid
143
peusterm398cd3b2016-03-21 15:04:54 +0100144 def _start_vnfd(self, vnfd):
145 """
146 Start a single VNFD of this service
147 :param vnfd: vnfd descriptor dict
148 :return:
149 """
150 # iterate over all deployment units within each VNFDs
151 for u in vnfd.get("virtual_deployment_units"):
152 # 1. get the name of the docker image to start and the assigned DC
peusterm56356cb2016-05-03 10:43:43 +0200153 vnf_name = vnfd.get("name")
154 if vnf_name not in self.remote_docker_image_urls:
155 raise Exception("No image name for %r found. Abort." % vnf_name)
156 docker_name = self.remote_docker_image_urls.get(vnf_name)
peusterm398cd3b2016-03-21 15:04:54 +0100157 target_dc = vnfd.get("dc")
158 # 2. perform some checks to ensure we can start the container
159 assert(docker_name is not None)
160 assert(target_dc is not None)
161 if not self._check_docker_image_exists(docker_name):
162 raise Exception("Docker image %r not found. Abort." % docker_name)
163 # 3. do the dc.startCompute(name="foobar") call to run the container
164 # TODO consider flavors, and other annotations
stevenvanrossemd87fe472016-05-11 11:34:34 +0200165 intfs = vnfd.get("connection_points")
166 vnfi = target_dc.startCompute(GK.get_next_vnf_name(), network=intfs, image=docker_name, flavor_name="small")
peusterm398cd3b2016-03-21 15:04:54 +0100167 # 6. store references to the compute objects in self.instances
168 return vnfi
169
peusterm786cd542016-03-14 14:12:17 +0100170 def _unpack_service_package(self):
171 """
172 unzip *.son file and store contents in CATALOG_FOLDER/services/<service_uuid>/
173 """
peusterm82d406e2016-05-02 20:52:06 +0200174 LOG.info("Unzipping: %r" % self.package_file_path)
peusterm786cd542016-03-14 14:12:17 +0100175 with zipfile.ZipFile(self.package_file_path, "r") as z:
176 z.extractall(self.package_content_path)
177
peusterm82d406e2016-05-02 20:52:06 +0200178
peusterm7ec665d2016-03-14 15:20:44 +0100179 def _load_package_descriptor(self):
180 """
181 Load the main package descriptor YAML and keep it as dict.
182 :return:
183 """
184 self.manifest = load_yaml(
185 os.path.join(
186 self.package_content_path, "META-INF/MANIFEST.MF"))
187
188 def _load_nsd(self):
189 """
190 Load the entry NSD YAML and keep it as dict.
191 :return:
192 """
193 if "entry_service_template" in self.manifest:
194 nsd_path = os.path.join(
195 self.package_content_path,
196 make_relative_path(self.manifest.get("entry_service_template")))
197 self.nsd = load_yaml(nsd_path)
peusterm757fe9a2016-04-04 14:11:58 +0200198 LOG.debug("Loaded NSD: %r" % self.nsd.get("name"))
peusterm7ec665d2016-03-14 15:20:44 +0100199
200 def _load_vnfd(self):
201 """
202 Load all VNFD YAML files referenced in MANIFEST.MF and keep them in dict.
203 :return:
204 """
205 if "package_content" in self.manifest:
206 for pc in self.manifest.get("package_content"):
207 if pc.get("content-type") == "application/sonata.function_descriptor":
208 vnfd_path = os.path.join(
209 self.package_content_path,
210 make_relative_path(pc.get("name")))
211 vnfd = load_yaml(vnfd_path)
peusterm757fe9a2016-04-04 14:11:58 +0200212 self.vnfds[vnfd.get("name")] = vnfd
213 LOG.debug("Loaded VNFD: %r" % vnfd.get("name"))
peusterm7ec665d2016-03-14 15:20:44 +0100214
215 def _load_docker_files(self):
216 """
peusterm9d7d4b02016-03-23 19:56:44 +0100217 Get all paths to Dockerfiles from VNFDs and store them in dict.
peusterm7ec665d2016-03-14 15:20:44 +0100218 :return:
219 """
peusterm9d7d4b02016-03-23 19:56:44 +0100220 for k, v in self.vnfds.iteritems():
221 for vu in v.get("virtual_deployment_units"):
222 if vu.get("vm_image_format") == "docker":
223 vm_image = vu.get("vm_image")
peusterm7ec665d2016-03-14 15:20:44 +0100224 docker_path = os.path.join(
225 self.package_content_path,
peusterm9d7d4b02016-03-23 19:56:44 +0100226 make_relative_path(vm_image))
227 self.local_docker_files[k] = docker_path
peusterm56356cb2016-05-03 10:43:43 +0200228 LOG.debug("Found Dockerfile (%r): %r" % (k, docker_path))
peusterm7ec665d2016-03-14 15:20:44 +0100229
peusterm82d406e2016-05-02 20:52:06 +0200230 def _load_docker_urls(self):
231 """
232 Get all URLs to pre-build docker images in some repo.
233 :return:
234 """
235 for k, v in self.vnfds.iteritems():
236 for vu in v.get("virtual_deployment_units"):
237 if vu.get("vm_image_format") == "docker":
peusterm35ba4052016-05-02 21:21:14 +0200238 url = vu.get("vm_image")
239 if url is not None:
240 url = url.replace("http://", "")
241 self.remote_docker_image_urls[k] = url
peusterm56356cb2016-05-03 10:43:43 +0200242 LOG.debug("Found Docker image URL (%r): %r" % (k, self.remote_docker_image_urls[k]))
peusterm82d406e2016-05-02 20:52:06 +0200243
peustermbdfab7e2016-03-14 16:03:30 +0100244 def _build_images_from_dockerfiles(self):
245 """
246 Build Docker images for each local Dockerfile found in the package: self.local_docker_files
247 """
peusterm398cd3b2016-03-21 15:04:54 +0100248 if GK_STANDALONE_MODE:
249 return # do not build anything in standalone mode
peustermbdfab7e2016-03-14 16:03:30 +0100250 dc = DockerClient()
251 LOG.info("Building %d Docker images (this may take several minutes) ..." % len(self.local_docker_files))
252 for k, v in self.local_docker_files.iteritems():
253 for line in dc.build(path=v.replace("Dockerfile", ""), tag=k, rm=False, nocache=False):
254 LOG.debug("DOCKER BUILD: %s" % line)
255 LOG.info("Docker image created: %s" % k)
256
peusterm82d406e2016-05-02 20:52:06 +0200257 def _pull_predefined_dockerimages(self):
peustermbdfab7e2016-03-14 16:03:30 +0100258 """
259 If the package contains URLs to pre-build Docker images, we download them with this method.
260 """
peusterm35ba4052016-05-02 21:21:14 +0200261 dc = DockerClient()
262 for url in self.remote_docker_image_urls.itervalues():
peusterm56356cb2016-05-03 10:43:43 +0200263 if not FORCE_PULL: # only pull if not present (speedup for development)
264 if len(dc.images(name=url)) > 0:
265 LOG.debug("Image %r present. Skipping pull." % url)
266 continue
peusterm35ba4052016-05-02 21:21:14 +0200267 LOG.info("Pulling image: %r" % url)
268 dc.pull(url,
269 insecure_registry=True)
peusterm786cd542016-03-14 14:12:17 +0100270
peusterm3444ae42016-03-16 20:46:41 +0100271 def _check_docker_image_exists(self, image_name):
peusterm3f307142016-03-16 21:02:53 +0100272 """
273 Query the docker service and check if the given image exists
274 :param image_name: name of the docker image
275 :return:
276 """
277 return len(DockerClient().images(image_name)) > 0
peusterm3444ae42016-03-16 20:46:41 +0100278
peusterm082378b2016-03-16 20:14:22 +0100279 def _calculate_placement(self, algorithm):
280 """
281 Do placement by adding the a field "dc" to
282 each VNFD that points to one of our
283 data center objects known to the gatekeeper.
284 """
285 assert(len(self.vnfds) > 0)
286 assert(len(GK.dcs) > 0)
287 # instantiate algorithm an place
288 p = algorithm()
289 p.place(self.nsd, self.vnfds, GK.dcs)
290 LOG.info("Using placement algorithm: %r" % p.__class__.__name__)
291 # lets print the placement result
292 for name, vnfd in self.vnfds.iteritems():
293 LOG.info("Placed VNF %r on DC %r" % (name, str(vnfd.get("dc"))))
294
295
296"""
297Some (simple) placement algorithms
298"""
299
300
301class FirstDcPlacement(object):
302 """
303 Placement: Always use one and the same data center from the GK.dcs dict.
304 """
305 def place(self, nsd, vnfds, dcs):
306 for name, vnfd in vnfds.iteritems():
307 vnfd["dc"] = list(dcs.itervalues())[0]
308
peusterme26487b2016-03-08 14:00:21 +0100309
310"""
311Resource definitions and API endpoints
312"""
313
314
315class Packages(fr.Resource):
316
317 def post(self):
318 """
peusterm26455852016-03-08 14:23:53 +0100319 Upload a *.son service package to the dummy gatekeeper.
320
peusterme26487b2016-03-08 14:00:21 +0100321 We expect request with a *.son file and store it in UPLOAD_FOLDER
peusterm26455852016-03-08 14:23:53 +0100322 :return: UUID
peusterme26487b2016-03-08 14:00:21 +0100323 """
324 try:
325 # get file contents
wtavernib8d9ecb2016-03-25 15:18:31 +0100326 print(request.files)
peusterm593ca582016-03-30 19:55:01 +0200327 # lets search for the package in the request
328 if "package" in request.files:
329 son_file = request.files["package"]
330 # elif "file" in request.files:
331 # son_file = request.files["file"]
332 else:
333 return {"service_uuid": None, "size": 0, "sha1": None, "error": "upload failed. file not found."}, 500
peusterme26487b2016-03-08 14:00:21 +0100334 # generate a uuid to reference this package
335 service_uuid = str(uuid.uuid4())
peusterm786cd542016-03-14 14:12:17 +0100336 file_hash = hashlib.sha1(str(son_file)).hexdigest()
peusterme26487b2016-03-08 14:00:21 +0100337 # ensure that upload folder exists
338 ensure_dir(UPLOAD_FOLDER)
339 upload_path = os.path.join(UPLOAD_FOLDER, "%s.son" % service_uuid)
340 # store *.son file to disk
peusterm786cd542016-03-14 14:12:17 +0100341 son_file.save(upload_path)
peusterme26487b2016-03-08 14:00:21 +0100342 size = os.path.getsize(upload_path)
peusterm786cd542016-03-14 14:12:17 +0100343 # create a service object and register it
344 s = Service(service_uuid, file_hash, upload_path)
345 GK.register_service_package(service_uuid, s)
peusterme26487b2016-03-08 14:00:21 +0100346 # generate the JSON result
peusterm786cd542016-03-14 14:12:17 +0100347 return {"service_uuid": service_uuid, "size": size, "sha1": file_hash, "error": None}
peusterme26487b2016-03-08 14:00:21 +0100348 except Exception as ex:
peusterm786cd542016-03-14 14:12:17 +0100349 LOG.exception("Service package upload failed:")
peusterm593ca582016-03-30 19:55:01 +0200350 return {"service_uuid": None, "size": 0, "sha1": None, "error": "upload failed"}, 500
peusterme26487b2016-03-08 14:00:21 +0100351
352 def get(self):
peusterm26455852016-03-08 14:23:53 +0100353 """
354 Return a list of UUID's of uploaded service packages.
355 :return: dict/list
356 """
peusterm786cd542016-03-14 14:12:17 +0100357 return {"service_uuid_list": list(GK.services.iterkeys())}
peusterme26487b2016-03-08 14:00:21 +0100358
359
360class Instantiations(fr.Resource):
361
362 def post(self):
peusterm26455852016-03-08 14:23:53 +0100363 """
364 Instantiate a service specified by its UUID.
365 Will return a new UUID to identify the running service instance.
366 :return: UUID
367 """
peusterm64b45502016-03-16 21:15:14 +0100368 # try to extract the service uuid from the request
peusterm26455852016-03-08 14:23:53 +0100369 json_data = request.get_json(force=True)
peusterm64b45502016-03-16 21:15:14 +0100370 service_uuid = json_data.get("service_uuid")
371
372 # lets be a bit fuzzy here to make testing easier
373 if service_uuid is None and len(GK.services) > 0:
374 # if we don't get a service uuid, we simple start the first service in the list
375 service_uuid = list(GK.services.iterkeys())[0]
376
peustermbea87372016-03-16 19:37:35 +0100377 if service_uuid in GK.services:
peusterm64b45502016-03-16 21:15:14 +0100378 # ok, we have a service uuid, lets start the service
peustermbea87372016-03-16 19:37:35 +0100379 service_instance_uuid = GK.services.get(service_uuid).start_service()
peusterm26455852016-03-08 14:23:53 +0100380 return {"service_instance_uuid": service_instance_uuid}
peustermbea87372016-03-16 19:37:35 +0100381 return "Service not found", 404
peusterme26487b2016-03-08 14:00:21 +0100382
383 def get(self):
peusterm26455852016-03-08 14:23:53 +0100384 """
385 Returns a list of UUIDs containing all running services.
386 :return: dict / list
387 """
peusterm64b45502016-03-16 21:15:14 +0100388 return {"service_instance_list": [
389 list(s.instances.iterkeys()) for s in GK.services.itervalues()]}
peusterm786cd542016-03-14 14:12:17 +0100390
peusterme26487b2016-03-08 14:00:21 +0100391
392# create a single, global GK object
393GK = Gatekeeper()
394# setup Flask
395app = Flask(__name__)
396app.config['MAX_CONTENT_LENGTH'] = 512 * 1024 * 1024 # 512 MB max upload
397api = fr.Api(app)
398# define endpoints
peusterm593ca582016-03-30 19:55:01 +0200399api.add_resource(Packages, '/packages')
400api.add_resource(Instantiations, '/instantiations')
peusterme26487b2016-03-08 14:00:21 +0100401
402
peusterm082378b2016-03-16 20:14:22 +0100403def start_rest_api(host, port, datacenters=dict()):
peustermbea87372016-03-16 19:37:35 +0100404 GK.dcs = datacenters
peusterme26487b2016-03-08 14:00:21 +0100405 # start the Flask server (not the best performance but ok for our use case)
406 app.run(host=host,
407 port=port,
408 debug=True,
409 use_reloader=False # this is needed to run Flask in a non-main thread
410 )
411
412
413def ensure_dir(name):
414 if not os.path.exists(name):
peusterm7ec665d2016-03-14 15:20:44 +0100415 os.makedirs(name)
416
417
418def load_yaml(path):
419 with open(path, "r") as f:
420 try:
421 r = yaml.load(f)
422 except yaml.YAMLError as exc:
423 LOG.exception("YAML parse error")
424 r = dict()
425 return r
426
427
428def make_relative_path(path):
peusterm9d7d4b02016-03-23 19:56:44 +0100429 if path.startswith("file://"):
430 path = path.replace("file://", "", 1)
peusterm7ec665d2016-03-14 15:20:44 +0100431 if path.startswith("/"):
peusterm9d7d4b02016-03-23 19:56:44 +0100432 path = path.replace("/", "", 1)
peusterm7ec665d2016-03-14 15:20:44 +0100433 return path
434
435
peusterme26487b2016-03-08 14:00:21 +0100436if __name__ == '__main__':
437 """
438 Lets allow to run the API in standalone mode.
439 """
peusterm398cd3b2016-03-21 15:04:54 +0100440 GK_STANDALONE_MODE = True
peusterme26487b2016-03-08 14:00:21 +0100441 logging.getLogger("werkzeug").setLevel(logging.INFO)
442 start_rest_api("0.0.0.0", 8000)
443