blob: 68031e494fa71fa4e0ce636a26423ce48ea6d6fb [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 """
peusterm786cd542016-03-14 14:12:17 +0100198 # TODO implement
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):
202 # TODO implement
203 return True
204
peusterm082378b2016-03-16 20:14:22 +0100205 def _calculate_placement(self, algorithm):
206 """
207 Do placement by adding the a field "dc" to
208 each VNFD that points to one of our
209 data center objects known to the gatekeeper.
210 """
211 assert(len(self.vnfds) > 0)
212 assert(len(GK.dcs) > 0)
213 # instantiate algorithm an place
214 p = algorithm()
215 p.place(self.nsd, self.vnfds, GK.dcs)
216 LOG.info("Using placement algorithm: %r" % p.__class__.__name__)
217 # lets print the placement result
218 for name, vnfd in self.vnfds.iteritems():
219 LOG.info("Placed VNF %r on DC %r" % (name, str(vnfd.get("dc"))))
220
221
222"""
223Some (simple) placement algorithms
224"""
225
226
227class FirstDcPlacement(object):
228 """
229 Placement: Always use one and the same data center from the GK.dcs dict.
230 """
231 def place(self, nsd, vnfds, dcs):
232 for name, vnfd in vnfds.iteritems():
233 vnfd["dc"] = list(dcs.itervalues())[0]
234
peusterme26487b2016-03-08 14:00:21 +0100235
236"""
237Resource definitions and API endpoints
238"""
239
240
241class Packages(fr.Resource):
242
243 def post(self):
244 """
peusterm26455852016-03-08 14:23:53 +0100245 Upload a *.son service package to the dummy gatekeeper.
246
peusterme26487b2016-03-08 14:00:21 +0100247 We expect request with a *.son file and store it in UPLOAD_FOLDER
peusterm26455852016-03-08 14:23:53 +0100248 :return: UUID
peusterme26487b2016-03-08 14:00:21 +0100249 """
250 try:
251 # get file contents
peusterm786cd542016-03-14 14:12:17 +0100252 son_file = request.files['file']
peusterme26487b2016-03-08 14:00:21 +0100253 # generate a uuid to reference this package
254 service_uuid = str(uuid.uuid4())
peusterm786cd542016-03-14 14:12:17 +0100255 file_hash = hashlib.sha1(str(son_file)).hexdigest()
peusterme26487b2016-03-08 14:00:21 +0100256 # ensure that upload folder exists
257 ensure_dir(UPLOAD_FOLDER)
258 upload_path = os.path.join(UPLOAD_FOLDER, "%s.son" % service_uuid)
259 # store *.son file to disk
peusterm786cd542016-03-14 14:12:17 +0100260 son_file.save(upload_path)
peusterme26487b2016-03-08 14:00:21 +0100261 size = os.path.getsize(upload_path)
peusterm786cd542016-03-14 14:12:17 +0100262 # create a service object and register it
263 s = Service(service_uuid, file_hash, upload_path)
264 GK.register_service_package(service_uuid, s)
peusterme26487b2016-03-08 14:00:21 +0100265 # generate the JSON result
peusterm786cd542016-03-14 14:12:17 +0100266 return {"service_uuid": service_uuid, "size": size, "sha1": file_hash, "error": None}
peusterme26487b2016-03-08 14:00:21 +0100267 except Exception as ex:
peusterm786cd542016-03-14 14:12:17 +0100268 LOG.exception("Service package upload failed:")
peusterme26487b2016-03-08 14:00:21 +0100269 return {"service_uuid": None, "size": 0, "sha1": None, "error": "upload failed"}
270
271 def get(self):
peusterm26455852016-03-08 14:23:53 +0100272 """
273 Return a list of UUID's of uploaded service packages.
274 :return: dict/list
275 """
peusterm786cd542016-03-14 14:12:17 +0100276 return {"service_uuid_list": list(GK.services.iterkeys())}
peusterme26487b2016-03-08 14:00:21 +0100277
278
279class Instantiations(fr.Resource):
280
281 def post(self):
peusterm26455852016-03-08 14:23:53 +0100282 """
283 Instantiate a service specified by its UUID.
284 Will return a new UUID to identify the running service instance.
285 :return: UUID
286 """
287 # TODO implement method (start real service)
288 json_data = request.get_json(force=True)
peustermbea87372016-03-16 19:37:35 +0100289 service_uuid = list(GK.services.iterkeys())[0] #json_data.get("service_uuid") # TODO only for quick testing
290 if service_uuid in GK.services:
peustermbea87372016-03-16 19:37:35 +0100291 service_instance_uuid = GK.services.get(service_uuid).start_service()
peusterm26455852016-03-08 14:23:53 +0100292 return {"service_instance_uuid": service_instance_uuid}
peustermbea87372016-03-16 19:37:35 +0100293 return "Service not found", 404
peusterme26487b2016-03-08 14:00:21 +0100294
295 def get(self):
peusterm26455852016-03-08 14:23:53 +0100296 """
297 Returns a list of UUIDs containing all running services.
298 :return: dict / list
299 """
peusterme26487b2016-03-08 14:00:21 +0100300 # TODO implement method
peusterm786cd542016-03-14 14:12:17 +0100301 return {"service_instance_uuid_list": list()}
302
peusterme26487b2016-03-08 14:00:21 +0100303
304# create a single, global GK object
305GK = Gatekeeper()
306# setup Flask
307app = Flask(__name__)
308app.config['MAX_CONTENT_LENGTH'] = 512 * 1024 * 1024 # 512 MB max upload
309api = fr.Api(app)
310# define endpoints
peusterm786cd542016-03-14 14:12:17 +0100311api.add_resource(Packages, '/api/packages')
peusterme26487b2016-03-08 14:00:21 +0100312api.add_resource(Instantiations, '/api/instantiations')
313
314
peusterm082378b2016-03-16 20:14:22 +0100315def start_rest_api(host, port, datacenters=dict()):
peustermbea87372016-03-16 19:37:35 +0100316 GK.dcs = datacenters
peusterme26487b2016-03-08 14:00:21 +0100317 # start the Flask server (not the best performance but ok for our use case)
318 app.run(host=host,
319 port=port,
320 debug=True,
321 use_reloader=False # this is needed to run Flask in a non-main thread
322 )
323
324
325def ensure_dir(name):
326 if not os.path.exists(name):
peusterm7ec665d2016-03-14 15:20:44 +0100327 os.makedirs(name)
328
329
330def load_yaml(path):
331 with open(path, "r") as f:
332 try:
333 r = yaml.load(f)
334 except yaml.YAMLError as exc:
335 LOG.exception("YAML parse error")
336 r = dict()
337 return r
338
339
340def make_relative_path(path):
341 if path.startswith("/"):
342 return path.replace("/", "", 1)
343 return path
344
345
346def helper_map_docker_name(name):
347 """
348 Quick hack to fix missing dependency in example package.
349 """
350 # TODO remove this when package description is fixed
351 mapping = {
352 "/docker_files/iperf/Dockerfile": "iperf_docker",
353 "/docker_files/firewall/Dockerfile": "fw_docker",
354 "/docker_files/tcpdump/Dockerfile": "tcpdump_docker"
355 }
356 return mapping.get(name)
peusterme26487b2016-03-08 14:00:21 +0100357
358
359if __name__ == '__main__':
360 """
361 Lets allow to run the API in standalone mode.
362 """
363 logging.getLogger("werkzeug").setLevel(logging.INFO)
364 start_rest_api("0.0.0.0", 8000)
365