blob: 0767b7bed96b0961596a0cb13f3680011c0a8b69 [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
peusterme26487b2016-03-08 14:00:21 +010033
34class Gatekeeper(object):
35
36 def __init__(self):
peusterm786cd542016-03-14 14:12:17 +010037 self.services = dict()
peusterm082378b2016-03-16 20:14:22 +010038 self.dcs = dict()
peusterm3444ae42016-03-16 20:46:41 +010039 self.vnf_counter = 0 # used to generate short names for VNFs (Mininet limitation)
peusterm786cd542016-03-14 14:12:17 +010040 LOG.info("Create SONATA dummy gatekeeper.")
peusterme26487b2016-03-08 14:00:21 +010041
peusterm786cd542016-03-14 14:12:17 +010042 def register_service_package(self, service_uuid, service):
43 """
44 register new service package
45 :param service_uuid
46 :param service object
47 """
48 self.services[service_uuid] = service
49 # lets perform all steps needed to onboard the service
50 service.onboard()
51
peusterm3444ae42016-03-16 20:46:41 +010052 def get_next_vnf_name(self):
53 self.vnf_counter += 1
peusterm398cd3b2016-03-21 15:04:54 +010054 return "vnf%d" % self.vnf_counter
peusterm3444ae42016-03-16 20:46:41 +010055
peusterm786cd542016-03-14 14:12:17 +010056
57class Service(object):
58 """
59 This class represents a NS uploaded as a *.son package to the
60 dummy gatekeeper.
61 Can have multiple running instances of this service.
62 """
63
64 def __init__(self,
65 service_uuid,
66 package_file_hash,
67 package_file_path):
68 self.uuid = service_uuid
69 self.package_file_hash = package_file_hash
70 self.package_file_path = package_file_path
71 self.package_content_path = os.path.join(CATALOG_FOLDER, "services/%s" % self.uuid)
peusterm7ec665d2016-03-14 15:20:44 +010072 self.manifest = None
73 self.nsd = None
74 self.vnfds = dict()
peustermbdfab7e2016-03-14 16:03:30 +010075 self.local_docker_files = dict()
peusterm82d406e2016-05-02 20:52:06 +020076 self.remote_docker_image_urls = dict()
peusterm786cd542016-03-14 14:12:17 +010077 self.instances = dict()
peusterme26487b2016-03-08 14:00:21 +010078
peusterm786cd542016-03-14 14:12:17 +010079 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
peusterm7ec665d2016-03-14 15:20:44 +010087 self._load_package_descriptor()
88 self._load_nsd()
89 self._load_vnfd()
peusterm786cd542016-03-14 14:12:17 +010090 # 3. prepare container images (e.g. download or build Dockerfile)
peusterm82d406e2016-05-02 20:52:06 +020091 if BUILD_DOCKERFILE:
92 self._load_docker_files()
93 self._build_images_from_dockerfiles()
94 else:
95 self._load_docker_urls()
96 self._pull_predefined_dockerimages()
peusterm7ec665d2016-03-14 15:20:44 +010097 LOG.info("On-boarded service: %r" % self.manifest.get("package_name"))
98
peusterm082378b2016-03-16 20:14:22 +010099 def start_service(self):
peusterm3444ae42016-03-16 20:46:41 +0100100 """
101 This methods creates and starts a new service instance.
102 It computes placements, iterates over all VNFDs, and starts
103 each VNFD as a Docker container in the data center selected
104 by the placement algorithm.
105 :return:
106 """
107 LOG.info("Starting service %r" % self.uuid)
108 # 1. each service instance gets a new uuid to identify it
peusterm082378b2016-03-16 20:14:22 +0100109 instance_uuid = str(uuid.uuid4())
peusterm3444ae42016-03-16 20:46:41 +0100110 # build a instances dict (a bit like a NSR :))
111 self.instances[instance_uuid] = dict()
112 self.instances[instance_uuid]["vnf_instances"] = list()
113 # 2. compute placement of this service instance (adds DC names to VNFDs)
peusterm398cd3b2016-03-21 15:04:54 +0100114 if not GK_STANDALONE_MODE:
115 self._calculate_placement(FirstDcPlacement)
peusterm3444ae42016-03-16 20:46:41 +0100116 # iterate over all vnfds that we have to start
peusterm082378b2016-03-16 20:14:22 +0100117 for vnfd in self.vnfds.itervalues():
peusterm398cd3b2016-03-21 15:04:54 +0100118 vnfi = None
119 if not GK_STANDALONE_MODE:
120 vnfi = self._start_vnfd(vnfd)
121 self.instances[instance_uuid]["vnf_instances"].append(vnfi)
peusterm3444ae42016-03-16 20:46:41 +0100122 LOG.info("Service started. Instance id: %r" % instance_uuid)
peusterm082378b2016-03-16 20:14:22 +0100123 return instance_uuid
124
peusterm398cd3b2016-03-21 15:04:54 +0100125 def _start_vnfd(self, vnfd):
126 """
127 Start a single VNFD of this service
128 :param vnfd: vnfd descriptor dict
129 :return:
130 """
131 # iterate over all deployment units within each VNFDs
132 for u in vnfd.get("virtual_deployment_units"):
133 # 1. get the name of the docker image to start and the assigned DC
peusterm757fe9a2016-04-04 14:11:58 +0200134 docker_name = vnfd.get("name")
peusterm398cd3b2016-03-21 15:04:54 +0100135 target_dc = vnfd.get("dc")
136 # 2. perform some checks to ensure we can start the container
137 assert(docker_name is not None)
138 assert(target_dc is not None)
139 if not self._check_docker_image_exists(docker_name):
140 raise Exception("Docker image %r not found. Abort." % docker_name)
141 # 3. do the dc.startCompute(name="foobar") call to run the container
142 # TODO consider flavors, and other annotations
143 vnfi = target_dc.startCompute(GK.get_next_vnf_name(), image=docker_name, flavor_name="small")
144 # 6. store references to the compute objects in self.instances
145 return vnfi
146
peusterm786cd542016-03-14 14:12:17 +0100147 def _unpack_service_package(self):
148 """
149 unzip *.son file and store contents in CATALOG_FOLDER/services/<service_uuid>/
150 """
peusterm82d406e2016-05-02 20:52:06 +0200151 LOG.info("Unzipping: %r" % self.package_file_path)
peusterm786cd542016-03-14 14:12:17 +0100152 with zipfile.ZipFile(self.package_file_path, "r") as z:
153 z.extractall(self.package_content_path)
154
peusterm82d406e2016-05-02 20:52:06 +0200155
peusterm7ec665d2016-03-14 15:20:44 +0100156 def _load_package_descriptor(self):
157 """
158 Load the main package descriptor YAML and keep it as dict.
159 :return:
160 """
161 self.manifest = load_yaml(
162 os.path.join(
163 self.package_content_path, "META-INF/MANIFEST.MF"))
164
165 def _load_nsd(self):
166 """
167 Load the entry NSD YAML and keep it as dict.
168 :return:
169 """
170 if "entry_service_template" in self.manifest:
171 nsd_path = os.path.join(
172 self.package_content_path,
173 make_relative_path(self.manifest.get("entry_service_template")))
174 self.nsd = load_yaml(nsd_path)
peusterm757fe9a2016-04-04 14:11:58 +0200175 LOG.debug("Loaded NSD: %r" % self.nsd.get("name"))
peusterm7ec665d2016-03-14 15:20:44 +0100176
177 def _load_vnfd(self):
178 """
179 Load all VNFD YAML files referenced in MANIFEST.MF and keep them in dict.
180 :return:
181 """
182 if "package_content" in self.manifest:
183 for pc in self.manifest.get("package_content"):
184 if pc.get("content-type") == "application/sonata.function_descriptor":
185 vnfd_path = os.path.join(
186 self.package_content_path,
187 make_relative_path(pc.get("name")))
188 vnfd = load_yaml(vnfd_path)
peusterm757fe9a2016-04-04 14:11:58 +0200189 self.vnfds[vnfd.get("name")] = vnfd
190 LOG.debug("Loaded VNFD: %r" % vnfd.get("name"))
peusterm7ec665d2016-03-14 15:20:44 +0100191
192 def _load_docker_files(self):
193 """
peusterm9d7d4b02016-03-23 19:56:44 +0100194 Get all paths to Dockerfiles from VNFDs and store them in dict.
peusterm7ec665d2016-03-14 15:20:44 +0100195 :return:
196 """
peusterm9d7d4b02016-03-23 19:56:44 +0100197 for k, v in self.vnfds.iteritems():
198 for vu in v.get("virtual_deployment_units"):
199 if vu.get("vm_image_format") == "docker":
200 vm_image = vu.get("vm_image")
peusterm7ec665d2016-03-14 15:20:44 +0100201 docker_path = os.path.join(
202 self.package_content_path,
peusterm9d7d4b02016-03-23 19:56:44 +0100203 make_relative_path(vm_image))
204 self.local_docker_files[k] = docker_path
peusterm7ec665d2016-03-14 15:20:44 +0100205 LOG.debug("Found Dockerfile: %r" % docker_path)
206
peusterm82d406e2016-05-02 20:52:06 +0200207 def _load_docker_urls(self):
208 """
209 Get all URLs to pre-build docker images in some repo.
210 :return:
211 """
212 for k, v in self.vnfds.iteritems():
213 for vu in v.get("virtual_deployment_units"):
214 if vu.get("vm_image_format") == "docker":
peusterm35ba4052016-05-02 21:21:14 +0200215 url = vu.get("vm_image")
216 if url is not None:
217 url = url.replace("http://", "")
218 self.remote_docker_image_urls[k] = url
219 LOG.debug("Found Docker image URL: %r" % self.remote_docker_image_urls[k])
peusterm82d406e2016-05-02 20:52:06 +0200220
peustermbdfab7e2016-03-14 16:03:30 +0100221 def _build_images_from_dockerfiles(self):
222 """
223 Build Docker images for each local Dockerfile found in the package: self.local_docker_files
224 """
peusterm398cd3b2016-03-21 15:04:54 +0100225 if GK_STANDALONE_MODE:
226 return # do not build anything in standalone mode
peustermbdfab7e2016-03-14 16:03:30 +0100227 dc = DockerClient()
228 LOG.info("Building %d Docker images (this may take several minutes) ..." % len(self.local_docker_files))
229 for k, v in self.local_docker_files.iteritems():
230 for line in dc.build(path=v.replace("Dockerfile", ""), tag=k, rm=False, nocache=False):
231 LOG.debug("DOCKER BUILD: %s" % line)
232 LOG.info("Docker image created: %s" % k)
233
peusterm82d406e2016-05-02 20:52:06 +0200234 def _pull_predefined_dockerimages(self):
peustermbdfab7e2016-03-14 16:03:30 +0100235 """
236 If the package contains URLs to pre-build Docker images, we download them with this method.
237 """
peusterm82d406e2016-05-02 20:52:06 +0200238 # TODO implement this
peusterm35ba4052016-05-02 21:21:14 +0200239 dc = DockerClient()
240 for url in self.remote_docker_image_urls.itervalues():
241 LOG.info("Pulling image: %r" % url)
242 dc.pull(url,
243 insecure_registry=True)
peusterm786cd542016-03-14 14:12:17 +0100244
peusterm3444ae42016-03-16 20:46:41 +0100245 def _check_docker_image_exists(self, image_name):
peusterm3f307142016-03-16 21:02:53 +0100246 """
247 Query the docker service and check if the given image exists
248 :param image_name: name of the docker image
249 :return:
250 """
251 return len(DockerClient().images(image_name)) > 0
peusterm3444ae42016-03-16 20:46:41 +0100252
peusterm082378b2016-03-16 20:14:22 +0100253 def _calculate_placement(self, algorithm):
254 """
255 Do placement by adding the a field "dc" to
256 each VNFD that points to one of our
257 data center objects known to the gatekeeper.
258 """
259 assert(len(self.vnfds) > 0)
260 assert(len(GK.dcs) > 0)
261 # instantiate algorithm an place
262 p = algorithm()
263 p.place(self.nsd, self.vnfds, GK.dcs)
264 LOG.info("Using placement algorithm: %r" % p.__class__.__name__)
265 # lets print the placement result
266 for name, vnfd in self.vnfds.iteritems():
267 LOG.info("Placed VNF %r on DC %r" % (name, str(vnfd.get("dc"))))
268
269
270"""
271Some (simple) placement algorithms
272"""
273
274
275class FirstDcPlacement(object):
276 """
277 Placement: Always use one and the same data center from the GK.dcs dict.
278 """
279 def place(self, nsd, vnfds, dcs):
280 for name, vnfd in vnfds.iteritems():
281 vnfd["dc"] = list(dcs.itervalues())[0]
282
peusterme26487b2016-03-08 14:00:21 +0100283
284"""
285Resource definitions and API endpoints
286"""
287
288
289class Packages(fr.Resource):
290
291 def post(self):
292 """
peusterm26455852016-03-08 14:23:53 +0100293 Upload a *.son service package to the dummy gatekeeper.
294
peusterme26487b2016-03-08 14:00:21 +0100295 We expect request with a *.son file and store it in UPLOAD_FOLDER
peusterm26455852016-03-08 14:23:53 +0100296 :return: UUID
peusterme26487b2016-03-08 14:00:21 +0100297 """
298 try:
299 # get file contents
wtavernib8d9ecb2016-03-25 15:18:31 +0100300 print(request.files)
peusterm593ca582016-03-30 19:55:01 +0200301 # lets search for the package in the request
302 if "package" in request.files:
303 son_file = request.files["package"]
304 # elif "file" in request.files:
305 # son_file = request.files["file"]
306 else:
307 return {"service_uuid": None, "size": 0, "sha1": None, "error": "upload failed. file not found."}, 500
peusterme26487b2016-03-08 14:00:21 +0100308 # generate a uuid to reference this package
309 service_uuid = str(uuid.uuid4())
peusterm786cd542016-03-14 14:12:17 +0100310 file_hash = hashlib.sha1(str(son_file)).hexdigest()
peusterme26487b2016-03-08 14:00:21 +0100311 # ensure that upload folder exists
312 ensure_dir(UPLOAD_FOLDER)
313 upload_path = os.path.join(UPLOAD_FOLDER, "%s.son" % service_uuid)
314 # store *.son file to disk
peusterm786cd542016-03-14 14:12:17 +0100315 son_file.save(upload_path)
peusterme26487b2016-03-08 14:00:21 +0100316 size = os.path.getsize(upload_path)
peusterm786cd542016-03-14 14:12:17 +0100317 # create a service object and register it
318 s = Service(service_uuid, file_hash, upload_path)
319 GK.register_service_package(service_uuid, s)
peusterme26487b2016-03-08 14:00:21 +0100320 # generate the JSON result
peusterm786cd542016-03-14 14:12:17 +0100321 return {"service_uuid": service_uuid, "size": size, "sha1": file_hash, "error": None}
peusterme26487b2016-03-08 14:00:21 +0100322 except Exception as ex:
peusterm786cd542016-03-14 14:12:17 +0100323 LOG.exception("Service package upload failed:")
peusterm593ca582016-03-30 19:55:01 +0200324 return {"service_uuid": None, "size": 0, "sha1": None, "error": "upload failed"}, 500
peusterme26487b2016-03-08 14:00:21 +0100325
326 def get(self):
peusterm26455852016-03-08 14:23:53 +0100327 """
328 Return a list of UUID's of uploaded service packages.
329 :return: dict/list
330 """
peusterm786cd542016-03-14 14:12:17 +0100331 return {"service_uuid_list": list(GK.services.iterkeys())}
peusterme26487b2016-03-08 14:00:21 +0100332
333
334class Instantiations(fr.Resource):
335
336 def post(self):
peusterm26455852016-03-08 14:23:53 +0100337 """
338 Instantiate a service specified by its UUID.
339 Will return a new UUID to identify the running service instance.
340 :return: UUID
341 """
peusterm64b45502016-03-16 21:15:14 +0100342 # try to extract the service uuid from the request
peusterm26455852016-03-08 14:23:53 +0100343 json_data = request.get_json(force=True)
peusterm64b45502016-03-16 21:15:14 +0100344 service_uuid = json_data.get("service_uuid")
345
346 # lets be a bit fuzzy here to make testing easier
347 if service_uuid is None and len(GK.services) > 0:
348 # if we don't get a service uuid, we simple start the first service in the list
349 service_uuid = list(GK.services.iterkeys())[0]
350
peustermbea87372016-03-16 19:37:35 +0100351 if service_uuid in GK.services:
peusterm64b45502016-03-16 21:15:14 +0100352 # ok, we have a service uuid, lets start the service
peustermbea87372016-03-16 19:37:35 +0100353 service_instance_uuid = GK.services.get(service_uuid).start_service()
peusterm26455852016-03-08 14:23:53 +0100354 return {"service_instance_uuid": service_instance_uuid}
peustermbea87372016-03-16 19:37:35 +0100355 return "Service not found", 404
peusterme26487b2016-03-08 14:00:21 +0100356
357 def get(self):
peusterm26455852016-03-08 14:23:53 +0100358 """
359 Returns a list of UUIDs containing all running services.
360 :return: dict / list
361 """
peusterm64b45502016-03-16 21:15:14 +0100362 return {"service_instance_list": [
363 list(s.instances.iterkeys()) for s in GK.services.itervalues()]}
peusterm786cd542016-03-14 14:12:17 +0100364
peusterme26487b2016-03-08 14:00:21 +0100365
366# create a single, global GK object
367GK = Gatekeeper()
368# setup Flask
369app = Flask(__name__)
370app.config['MAX_CONTENT_LENGTH'] = 512 * 1024 * 1024 # 512 MB max upload
371api = fr.Api(app)
372# define endpoints
peusterm593ca582016-03-30 19:55:01 +0200373api.add_resource(Packages, '/packages')
374api.add_resource(Instantiations, '/instantiations')
peusterme26487b2016-03-08 14:00:21 +0100375
376
peusterm082378b2016-03-16 20:14:22 +0100377def start_rest_api(host, port, datacenters=dict()):
peustermbea87372016-03-16 19:37:35 +0100378 GK.dcs = datacenters
peusterme26487b2016-03-08 14:00:21 +0100379 # start the Flask server (not the best performance but ok for our use case)
380 app.run(host=host,
381 port=port,
382 debug=True,
383 use_reloader=False # this is needed to run Flask in a non-main thread
384 )
385
386
387def ensure_dir(name):
388 if not os.path.exists(name):
peusterm7ec665d2016-03-14 15:20:44 +0100389 os.makedirs(name)
390
391
392def load_yaml(path):
393 with open(path, "r") as f:
394 try:
395 r = yaml.load(f)
396 except yaml.YAMLError as exc:
397 LOG.exception("YAML parse error")
398 r = dict()
399 return r
400
401
402def make_relative_path(path):
peusterm9d7d4b02016-03-23 19:56:44 +0100403 if path.startswith("file://"):
404 path = path.replace("file://", "", 1)
peusterm7ec665d2016-03-14 15:20:44 +0100405 if path.startswith("/"):
peusterm9d7d4b02016-03-23 19:56:44 +0100406 path = path.replace("/", "", 1)
peusterm7ec665d2016-03-14 15:20:44 +0100407 return path
408
409
peusterme26487b2016-03-08 14:00:21 +0100410if __name__ == '__main__':
411 """
412 Lets allow to run the API in standalone mode.
413 """
peusterm398cd3b2016-03-21 15:04:54 +0100414 GK_STANDALONE_MODE = True
peusterme26487b2016-03-08 14:00:21 +0100415 logging.getLogger("werkzeug").setLevel(logging.INFO)
416 start_rest_api("0.0.0.0", 8000)
417