blob: 29ebc0bd7118bbd1aa5019c6c600407c440fd391 [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
peusterm786cd542016-03-14 14:12:17 +010018LOG = logging.getLogger("sonata-dummy-gatekeeper")
19LOG.setLevel(logging.DEBUG)
peusterme26487b2016-03-08 14:00:21 +010020logging.getLogger("werkzeug").setLevel(logging.WARNING)
21
22
23UPLOAD_FOLDER = "/tmp/son-dummy-gk/uploads/"
24CATALOG_FOLDER = "/tmp/son-dummy-gk/catalog/"
25
26
27class Gatekeeper(object):
28
29 def __init__(self):
peusterm786cd542016-03-14 14:12:17 +010030 self.services = dict()
peusterm082378b2016-03-16 20:14:22 +010031 self.dcs = dict()
peusterm3444ae42016-03-16 20:46:41 +010032 self.vnf_counter = 0 # used to generate short names for VNFs (Mininet limitation)
peusterm786cd542016-03-14 14:12:17 +010033 LOG.info("Create SONATA dummy gatekeeper.")
peusterme26487b2016-03-08 14:00:21 +010034
peusterm786cd542016-03-14 14:12:17 +010035 def register_service_package(self, service_uuid, service):
36 """
37 register new service package
38 :param service_uuid
39 :param service object
40 """
41 self.services[service_uuid] = service
42 # lets perform all steps needed to onboard the service
43 service.onboard()
44
peusterm3444ae42016-03-16 20:46:41 +010045 def get_next_vnf_name(self):
46 self.vnf_counter += 1
47 return "sonvnf%d" % self.vnf_counter
48
peusterm786cd542016-03-14 14:12:17 +010049
50class Service(object):
51 """
52 This class represents a NS uploaded as a *.son package to the
53 dummy gatekeeper.
54 Can have multiple running instances of this service.
55 """
56
57 def __init__(self,
58 service_uuid,
59 package_file_hash,
60 package_file_path):
61 self.uuid = service_uuid
62 self.package_file_hash = package_file_hash
63 self.package_file_path = package_file_path
64 self.package_content_path = os.path.join(CATALOG_FOLDER, "services/%s" % self.uuid)
peusterm7ec665d2016-03-14 15:20:44 +010065 self.manifest = None
66 self.nsd = None
67 self.vnfds = dict()
peustermbdfab7e2016-03-14 16:03:30 +010068 self.local_docker_files = dict()
peusterm786cd542016-03-14 14:12:17 +010069 self.instances = dict()
peusterme26487b2016-03-08 14:00:21 +010070
peusterm786cd542016-03-14 14:12:17 +010071 def onboard(self):
72 """
73 Do all steps to prepare this service to be instantiated
74 :return:
75 """
76 # 1. extract the contents of the package and store them in our catalog
77 self._unpack_service_package()
78 # 2. read in all descriptor files
peusterm7ec665d2016-03-14 15:20:44 +010079 self._load_package_descriptor()
80 self._load_nsd()
81 self._load_vnfd()
82 self._load_docker_files()
peusterm786cd542016-03-14 14:12:17 +010083 # 3. prepare container images (e.g. download or build Dockerfile)
peustermbdfab7e2016-03-14 16:03:30 +010084 self._build_images_from_dockerfiles()
85 self._download_predefined_dockerimages()
peusterm786cd542016-03-14 14:12:17 +010086
peusterm7ec665d2016-03-14 15:20:44 +010087 LOG.info("On-boarded service: %r" % self.manifest.get("package_name"))
88
peusterm082378b2016-03-16 20:14:22 +010089 def start_service(self):
peusterm3444ae42016-03-16 20:46:41 +010090 """
91 This methods creates and starts a new service instance.
92 It computes placements, iterates over all VNFDs, and starts
93 each VNFD as a Docker container in the data center selected
94 by the placement algorithm.
95 :return:
96 """
97 LOG.info("Starting service %r" % self.uuid)
98 # 1. each service instance gets a new uuid to identify it
peusterm082378b2016-03-16 20:14:22 +010099 instance_uuid = str(uuid.uuid4())
peusterm3444ae42016-03-16 20:46:41 +0100100 # build a instances dict (a bit like a NSR :))
101 self.instances[instance_uuid] = dict()
102 self.instances[instance_uuid]["vnf_instances"] = list()
103 # 2. compute placement of this service instance (adds DC names to VNFDs)
peusterm082378b2016-03-16 20:14:22 +0100104 self._calculate_placement(FirstDcPlacement)
peusterm3444ae42016-03-16 20:46:41 +0100105 # iterate over all vnfds that we have to start
peusterm082378b2016-03-16 20:14:22 +0100106 for vnfd in self.vnfds.itervalues():
peusterm3444ae42016-03-16 20:46:41 +0100107 # iterate over all deployment units within each VNFDs
peusterm082378b2016-03-16 20:14:22 +0100108 for u in vnfd.get("virtual_deployment_units"):
peusterm3444ae42016-03-16 20:46:41 +0100109 # 3. get the name of the docker image to start and the assigned DC
peusterm082378b2016-03-16 20:14:22 +0100110 docker_name = u.get("vm_image")
peusterm3444ae42016-03-16 20:46:41 +0100111 target_dc = vnfd.get("dc")
112 # 4. perform some checks to ensure we can start the container
113 assert(docker_name is not None)
114 assert(target_dc is not None)
115 if not self._check_docker_image_exists(docker_name):
116 raise Exception("Docker image %r not found. Abort." % docker_name)
117 # 5. do the dc.startCompute(name="foobar") call to run the container
118 # TODO consider flavors, and other annotations
119 vnfi = target_dc.startCompute(GK.get_next_vnf_name(), image=docker_name, flavor_name="small")
120 # 6. store references to the compute objects in self.instances
121 self.instances[instance_uuid]["vnf_instances"].append(vnfi)
122 LOG.info("Service started. Instance id: %r" % instance_uuid)
peusterm082378b2016-03-16 20:14:22 +0100123 return instance_uuid
124
peusterm786cd542016-03-14 14:12:17 +0100125 def _unpack_service_package(self):
126 """
127 unzip *.son file and store contents in CATALOG_FOLDER/services/<service_uuid>/
128 """
129 with zipfile.ZipFile(self.package_file_path, "r") as z:
130 z.extractall(self.package_content_path)
131
peusterm7ec665d2016-03-14 15:20:44 +0100132 def _load_package_descriptor(self):
133 """
134 Load the main package descriptor YAML and keep it as dict.
135 :return:
136 """
137 self.manifest = load_yaml(
138 os.path.join(
139 self.package_content_path, "META-INF/MANIFEST.MF"))
140
141 def _load_nsd(self):
142 """
143 Load the entry NSD YAML and keep it as dict.
144 :return:
145 """
146 if "entry_service_template" in self.manifest:
147 nsd_path = os.path.join(
148 self.package_content_path,
149 make_relative_path(self.manifest.get("entry_service_template")))
150 self.nsd = load_yaml(nsd_path)
151 LOG.debug("Loaded NSD: %r" % self.nsd.get("ns_name"))
152
153 def _load_vnfd(self):
154 """
155 Load all VNFD YAML files referenced in MANIFEST.MF and keep them in dict.
156 :return:
157 """
158 if "package_content" in self.manifest:
159 for pc in self.manifest.get("package_content"):
160 if pc.get("content-type") == "application/sonata.function_descriptor":
161 vnfd_path = os.path.join(
162 self.package_content_path,
163 make_relative_path(pc.get("name")))
164 vnfd = load_yaml(vnfd_path)
165 self.vnfds[vnfd.get("vnf_name")] = vnfd
166 LOG.debug("Loaded VNFD: %r" % vnfd.get("vnf_name"))
167
168 def _load_docker_files(self):
169 """
170 Get all paths to Dockerfiles from MANIFEST.MF and store them in dict.
171 :return:
172 """
173 if "package_content" in self.manifest:
174 for df in self.manifest.get("package_content"):
175 if df.get("content-type") == "application/sonata.docker_files":
176 docker_path = os.path.join(
177 self.package_content_path,
178 make_relative_path(df.get("name")))
179 # FIXME: Mapping to docker image names is hardcoded because of the missing mapping in the example package
peustermbdfab7e2016-03-14 16:03:30 +0100180 self.local_docker_files[helper_map_docker_name(df.get("name"))] = docker_path
peusterm7ec665d2016-03-14 15:20:44 +0100181 LOG.debug("Found Dockerfile: %r" % docker_path)
182
peustermbdfab7e2016-03-14 16:03:30 +0100183 def _build_images_from_dockerfiles(self):
184 """
185 Build Docker images for each local Dockerfile found in the package: self.local_docker_files
186 """
187 dc = DockerClient()
188 LOG.info("Building %d Docker images (this may take several minutes) ..." % len(self.local_docker_files))
189 for k, v in self.local_docker_files.iteritems():
190 for line in dc.build(path=v.replace("Dockerfile", ""), tag=k, rm=False, nocache=False):
191 LOG.debug("DOCKER BUILD: %s" % line)
192 LOG.info("Docker image created: %s" % k)
193
194 def _download_predefined_dockerimages(self):
195 """
196 If the package contains URLs to pre-build Docker images, we download them with this method.
197 """
peusterm3f307142016-03-16 21:02:53 +0100198 # TODO implement this if we want to be able to download docker images instead of building them
peustermbdfab7e2016-03-14 16:03:30 +0100199 pass
peusterm786cd542016-03-14 14:12:17 +0100200
peusterm3444ae42016-03-16 20:46:41 +0100201 def _check_docker_image_exists(self, image_name):
peusterm3f307142016-03-16 21:02:53 +0100202 """
203 Query the docker service and check if the given image exists
204 :param image_name: name of the docker image
205 :return:
206 """
207 return len(DockerClient().images(image_name)) > 0
peusterm3444ae42016-03-16 20:46:41 +0100208
peusterm082378b2016-03-16 20:14:22 +0100209 def _calculate_placement(self, algorithm):
210 """
211 Do placement by adding the a field "dc" to
212 each VNFD that points to one of our
213 data center objects known to the gatekeeper.
214 """
215 assert(len(self.vnfds) > 0)
216 assert(len(GK.dcs) > 0)
217 # instantiate algorithm an place
218 p = algorithm()
219 p.place(self.nsd, self.vnfds, GK.dcs)
220 LOG.info("Using placement algorithm: %r" % p.__class__.__name__)
221 # lets print the placement result
222 for name, vnfd in self.vnfds.iteritems():
223 LOG.info("Placed VNF %r on DC %r" % (name, str(vnfd.get("dc"))))
224
225
226"""
227Some (simple) placement algorithms
228"""
229
230
231class FirstDcPlacement(object):
232 """
233 Placement: Always use one and the same data center from the GK.dcs dict.
234 """
235 def place(self, nsd, vnfds, dcs):
236 for name, vnfd in vnfds.iteritems():
237 vnfd["dc"] = list(dcs.itervalues())[0]
238
peusterme26487b2016-03-08 14:00:21 +0100239
240"""
241Resource definitions and API endpoints
242"""
243
244
245class Packages(fr.Resource):
246
247 def post(self):
248 """
peusterm26455852016-03-08 14:23:53 +0100249 Upload a *.son service package to the dummy gatekeeper.
250
peusterme26487b2016-03-08 14:00:21 +0100251 We expect request with a *.son file and store it in UPLOAD_FOLDER
peusterm26455852016-03-08 14:23:53 +0100252 :return: UUID
peusterme26487b2016-03-08 14:00:21 +0100253 """
254 try:
255 # get file contents
peusterm786cd542016-03-14 14:12:17 +0100256 son_file = request.files['file']
peusterme26487b2016-03-08 14:00:21 +0100257 # generate a uuid to reference this package
258 service_uuid = str(uuid.uuid4())
peusterm786cd542016-03-14 14:12:17 +0100259 file_hash = hashlib.sha1(str(son_file)).hexdigest()
peusterme26487b2016-03-08 14:00:21 +0100260 # ensure that upload folder exists
261 ensure_dir(UPLOAD_FOLDER)
262 upload_path = os.path.join(UPLOAD_FOLDER, "%s.son" % service_uuid)
263 # store *.son file to disk
peusterm786cd542016-03-14 14:12:17 +0100264 son_file.save(upload_path)
peusterme26487b2016-03-08 14:00:21 +0100265 size = os.path.getsize(upload_path)
peusterm786cd542016-03-14 14:12:17 +0100266 # create a service object and register it
267 s = Service(service_uuid, file_hash, upload_path)
268 GK.register_service_package(service_uuid, s)
peusterme26487b2016-03-08 14:00:21 +0100269 # generate the JSON result
peusterm786cd542016-03-14 14:12:17 +0100270 return {"service_uuid": service_uuid, "size": size, "sha1": file_hash, "error": None}
peusterme26487b2016-03-08 14:00:21 +0100271 except Exception as ex:
peusterm786cd542016-03-14 14:12:17 +0100272 LOG.exception("Service package upload failed:")
peusterme26487b2016-03-08 14:00:21 +0100273 return {"service_uuid": None, "size": 0, "sha1": None, "error": "upload failed"}
274
275 def get(self):
peusterm26455852016-03-08 14:23:53 +0100276 """
277 Return a list of UUID's of uploaded service packages.
278 :return: dict/list
279 """
peusterm786cd542016-03-14 14:12:17 +0100280 return {"service_uuid_list": list(GK.services.iterkeys())}
peusterme26487b2016-03-08 14:00:21 +0100281
282
283class Instantiations(fr.Resource):
284
285 def post(self):
peusterm26455852016-03-08 14:23:53 +0100286 """
287 Instantiate a service specified by its UUID.
288 Will return a new UUID to identify the running service instance.
289 :return: UUID
290 """
peusterm64b45502016-03-16 21:15:14 +0100291 # try to extract the service uuid from the request
peusterm26455852016-03-08 14:23:53 +0100292 json_data = request.get_json(force=True)
peusterm64b45502016-03-16 21:15:14 +0100293 service_uuid = json_data.get("service_uuid")
294
295 # lets be a bit fuzzy here to make testing easier
296 if service_uuid is None and len(GK.services) > 0:
297 # if we don't get a service uuid, we simple start the first service in the list
298 service_uuid = list(GK.services.iterkeys())[0]
299
peustermbea87372016-03-16 19:37:35 +0100300 if service_uuid in GK.services:
peusterm64b45502016-03-16 21:15:14 +0100301 # ok, we have a service uuid, lets start the service
peustermbea87372016-03-16 19:37:35 +0100302 service_instance_uuid = GK.services.get(service_uuid).start_service()
peusterm26455852016-03-08 14:23:53 +0100303 return {"service_instance_uuid": service_instance_uuid}
peustermbea87372016-03-16 19:37:35 +0100304 return "Service not found", 404
peusterme26487b2016-03-08 14:00:21 +0100305
306 def get(self):
peusterm26455852016-03-08 14:23:53 +0100307 """
308 Returns a list of UUIDs containing all running services.
309 :return: dict / list
310 """
peusterm64b45502016-03-16 21:15:14 +0100311 return {"service_instance_list": [
312 list(s.instances.iterkeys()) for s in GK.services.itervalues()]}
peusterm786cd542016-03-14 14:12:17 +0100313
peusterme26487b2016-03-08 14:00:21 +0100314
315# create a single, global GK object
316GK = Gatekeeper()
317# setup Flask
318app = Flask(__name__)
319app.config['MAX_CONTENT_LENGTH'] = 512 * 1024 * 1024 # 512 MB max upload
320api = fr.Api(app)
321# define endpoints
peusterm786cd542016-03-14 14:12:17 +0100322api.add_resource(Packages, '/api/packages')
peusterme26487b2016-03-08 14:00:21 +0100323api.add_resource(Instantiations, '/api/instantiations')
324
325
peusterm082378b2016-03-16 20:14:22 +0100326def start_rest_api(host, port, datacenters=dict()):
peustermbea87372016-03-16 19:37:35 +0100327 GK.dcs = datacenters
peusterme26487b2016-03-08 14:00:21 +0100328 # start the Flask server (not the best performance but ok for our use case)
329 app.run(host=host,
330 port=port,
331 debug=True,
332 use_reloader=False # this is needed to run Flask in a non-main thread
333 )
334
335
336def ensure_dir(name):
337 if not os.path.exists(name):
peusterm7ec665d2016-03-14 15:20:44 +0100338 os.makedirs(name)
339
340
341def load_yaml(path):
342 with open(path, "r") as f:
343 try:
344 r = yaml.load(f)
345 except yaml.YAMLError as exc:
346 LOG.exception("YAML parse error")
347 r = dict()
348 return r
349
350
351def make_relative_path(path):
352 if path.startswith("/"):
353 return path.replace("/", "", 1)
354 return path
355
356
357def helper_map_docker_name(name):
358 """
359 Quick hack to fix missing dependency in example package.
360 """
peusterm3f307142016-03-16 21:02:53 +0100361 # FIXME remove this when package description is fixed
peusterm7ec665d2016-03-14 15:20:44 +0100362 mapping = {
363 "/docker_files/iperf/Dockerfile": "iperf_docker",
364 "/docker_files/firewall/Dockerfile": "fw_docker",
365 "/docker_files/tcpdump/Dockerfile": "tcpdump_docker"
366 }
367 return mapping.get(name)
peusterme26487b2016-03-08 14:00:21 +0100368
369
370if __name__ == '__main__':
371 """
372 Lets allow to run the API in standalone mode.
373 """
374 logging.getLogger("werkzeug").setLevel(logging.INFO)
375 start_rest_api("0.0.0.0", 8000)
376