update dummygatekeeper with chaining commands
[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
112 # 1. each service instance gets a new uuid to identify it
113 instance_uuid = str(uuid.uuid4())
114 # build a instances dict (a bit like a NSR :))
115 self.instances[instance_uuid] = dict()
116 self.instances[instance_uuid]["vnf_instances"] = list()
117
118 # 2. compute placement of this service instance (adds DC names to VNFDs)
119 if not GK_STANDALONE_MODE:
120 self._calculate_placement(FirstDcPlacement)
121 # iterate over all vnfds that we have to start
122 for vnfd in self.vnfds.itervalues():
123 vnfi = None
124 if not GK_STANDALONE_MODE:
125 vnfi = self._start_vnfd(vnfd)
126 self.instances[instance_uuid]["vnf_instances"].append(vnfi)
127
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
137 network = self.vnfds[src_node].get("dc").net # there should be a cleaner way to find the DCNetwork
138 network.setChain(src_node, dst_node, vnf_src_interface=src_port, vnf_dst_interface=dst_port)
139
140 LOG.info("Service started. Instance id: %r" % instance_uuid)
141 return instance_uuid
142
143 def _start_vnfd(self, vnfd):
144 """
145 Start a single VNFD of this service
146 :param vnfd: vnfd descriptor dict
147 :return:
148 """
149 # iterate over all deployment units within each VNFDs
150 for u in vnfd.get("virtual_deployment_units"):
151 # 1. get the name of the docker image to start and the assigned DC
152 vnf_name = vnfd.get("name")
153 if vnf_name not in self.remote_docker_image_urls:
154 raise Exception("No image name for %r found. Abort." % vnf_name)
155 docker_name = self.remote_docker_image_urls.get(vnf_name)
156 target_dc = vnfd.get("dc")
157 # 2. perform some checks to ensure we can start the container
158 assert(docker_name is not None)
159 assert(target_dc is not None)
160 if not self._check_docker_image_exists(docker_name):
161 raise Exception("Docker image %r not found. Abort." % docker_name)
162 # 3. do the dc.startCompute(name="foobar") call to run the container
163 # TODO consider flavors, and other annotations
164 intfs = vnfd.get("connection_points")
165 vnfi = target_dc.startCompute(GK.get_next_vnf_name(), network=intfs, image=docker_name, flavor_name="small")
166 # 6. store references to the compute objects in self.instances
167 return vnfi
168
169 def _unpack_service_package(self):
170 """
171 unzip *.son file and store contents in CATALOG_FOLDER/services/<service_uuid>/
172 """
173 LOG.info("Unzipping: %r" % self.package_file_path)
174 with zipfile.ZipFile(self.package_file_path, "r") as z:
175 z.extractall(self.package_content_path)
176
177
178 def _load_package_descriptor(self):
179 """
180 Load the main package descriptor YAML and keep it as dict.
181 :return:
182 """
183 self.manifest = load_yaml(
184 os.path.join(
185 self.package_content_path, "META-INF/MANIFEST.MF"))
186
187 def _load_nsd(self):
188 """
189 Load the entry NSD YAML and keep it as dict.
190 :return:
191 """
192 if "entry_service_template" in self.manifest:
193 nsd_path = os.path.join(
194 self.package_content_path,
195 make_relative_path(self.manifest.get("entry_service_template")))
196 self.nsd = load_yaml(nsd_path)
197 LOG.debug("Loaded NSD: %r" % self.nsd.get("name"))
198
199 def _load_vnfd(self):
200 """
201 Load all VNFD YAML files referenced in MANIFEST.MF and keep them in dict.
202 :return:
203 """
204 if "package_content" in self.manifest:
205 for pc in self.manifest.get("package_content"):
206 if pc.get("content-type") == "application/sonata.function_descriptor":
207 vnfd_path = os.path.join(
208 self.package_content_path,
209 make_relative_path(pc.get("name")))
210 vnfd = load_yaml(vnfd_path)
211 self.vnfds[vnfd.get("name")] = vnfd
212 LOG.debug("Loaded VNFD: %r" % vnfd.get("name"))
213
214 def _load_docker_files(self):
215 """
216 Get all paths to Dockerfiles from VNFDs and store them in dict.
217 :return:
218 """
219 for k, v in self.vnfds.iteritems():
220 for vu in v.get("virtual_deployment_units"):
221 if vu.get("vm_image_format") == "docker":
222 vm_image = vu.get("vm_image")
223 docker_path = os.path.join(
224 self.package_content_path,
225 make_relative_path(vm_image))
226 self.local_docker_files[k] = docker_path
227 LOG.debug("Found Dockerfile (%r): %r" % (k, docker_path))
228
229 def _load_docker_urls(self):
230 """
231 Get all URLs to pre-build docker images in some repo.
232 :return:
233 """
234 for k, v in self.vnfds.iteritems():
235 for vu in v.get("virtual_deployment_units"):
236 if vu.get("vm_image_format") == "docker":
237 url = vu.get("vm_image")
238 if url is not None:
239 url = url.replace("http://", "")
240 self.remote_docker_image_urls[k] = url
241 LOG.debug("Found Docker image URL (%r): %r" % (k, self.remote_docker_image_urls[k]))
242
243 def _build_images_from_dockerfiles(self):
244 """
245 Build Docker images for each local Dockerfile found in the package: self.local_docker_files
246 """
247 if GK_STANDALONE_MODE:
248 return # do not build anything in standalone mode
249 dc = DockerClient()
250 LOG.info("Building %d Docker images (this may take several minutes) ..." % len(self.local_docker_files))
251 for k, v in self.local_docker_files.iteritems():
252 for line in dc.build(path=v.replace("Dockerfile", ""), tag=k, rm=False, nocache=False):
253 LOG.debug("DOCKER BUILD: %s" % line)
254 LOG.info("Docker image created: %s" % k)
255
256 def _pull_predefined_dockerimages(self):
257 """
258 If the package contains URLs to pre-build Docker images, we download them with this method.
259 """
260 dc = DockerClient()
261 for url in self.remote_docker_image_urls.itervalues():
262 if not FORCE_PULL: # only pull if not present (speedup for development)
263 if len(dc.images(name=url)) > 0:
264 LOG.debug("Image %r present. Skipping pull." % url)
265 continue
266 LOG.info("Pulling image: %r" % url)
267 dc.pull(url,
268 insecure_registry=True)
269
270 def _check_docker_image_exists(self, image_name):
271 """
272 Query the docker service and check if the given image exists
273 :param image_name: name of the docker image
274 :return:
275 """
276 return len(DockerClient().images(image_name)) > 0
277
278 def _calculate_placement(self, algorithm):
279 """
280 Do placement by adding the a field "dc" to
281 each VNFD that points to one of our
282 data center objects known to the gatekeeper.
283 """
284 assert(len(self.vnfds) > 0)
285 assert(len(GK.dcs) > 0)
286 # instantiate algorithm an place
287 p = algorithm()
288 p.place(self.nsd, self.vnfds, GK.dcs)
289 LOG.info("Using placement algorithm: %r" % p.__class__.__name__)
290 # lets print the placement result
291 for name, vnfd in self.vnfds.iteritems():
292 LOG.info("Placed VNF %r on DC %r" % (name, str(vnfd.get("dc"))))
293
294
295 """
296 Some (simple) placement algorithms
297 """
298
299
300 class FirstDcPlacement(object):
301 """
302 Placement: Always use one and the same data center from the GK.dcs dict.
303 """
304 def place(self, nsd, vnfds, dcs):
305 for name, vnfd in vnfds.iteritems():
306 vnfd["dc"] = list(dcs.itervalues())[0]
307
308
309 """
310 Resource definitions and API endpoints
311 """
312
313
314 class Packages(fr.Resource):
315
316 def post(self):
317 """
318 Upload a *.son service package to the dummy gatekeeper.
319
320 We expect request with a *.son file and store it in UPLOAD_FOLDER
321 :return: UUID
322 """
323 try:
324 # get file contents
325 print(request.files)
326 # lets search for the package in the request
327 if "package" in request.files:
328 son_file = request.files["package"]
329 # elif "file" in request.files:
330 # son_file = request.files["file"]
331 else:
332 return {"service_uuid": None, "size": 0, "sha1": None, "error": "upload failed. file not found."}, 500
333 # generate a uuid to reference this package
334 service_uuid = str(uuid.uuid4())
335 file_hash = hashlib.sha1(str(son_file)).hexdigest()
336 # ensure that upload folder exists
337 ensure_dir(UPLOAD_FOLDER)
338 upload_path = os.path.join(UPLOAD_FOLDER, "%s.son" % service_uuid)
339 # store *.son file to disk
340 son_file.save(upload_path)
341 size = os.path.getsize(upload_path)
342 # create a service object and register it
343 s = Service(service_uuid, file_hash, upload_path)
344 GK.register_service_package(service_uuid, s)
345 # generate the JSON result
346 return {"service_uuid": service_uuid, "size": size, "sha1": file_hash, "error": None}
347 except Exception as ex:
348 LOG.exception("Service package upload failed:")
349 return {"service_uuid": None, "size": 0, "sha1": None, "error": "upload failed"}, 500
350
351 def get(self):
352 """
353 Return a list of UUID's of uploaded service packages.
354 :return: dict/list
355 """
356 return {"service_uuid_list": list(GK.services.iterkeys())}
357
358
359 class Instantiations(fr.Resource):
360
361 def post(self):
362 """
363 Instantiate a service specified by its UUID.
364 Will return a new UUID to identify the running service instance.
365 :return: UUID
366 """
367 # try to extract the service uuid from the request
368 json_data = request.get_json(force=True)
369 service_uuid = json_data.get("service_uuid")
370
371 # lets be a bit fuzzy here to make testing easier
372 if service_uuid is None and len(GK.services) > 0:
373 # if we don't get a service uuid, we simple start the first service in the list
374 service_uuid = list(GK.services.iterkeys())[0]
375
376 if service_uuid in GK.services:
377 # ok, we have a service uuid, lets start the service
378 service_instance_uuid = GK.services.get(service_uuid).start_service()
379 return {"service_instance_uuid": service_instance_uuid}
380 return "Service not found", 404
381
382 def get(self):
383 """
384 Returns a list of UUIDs containing all running services.
385 :return: dict / list
386 """
387 return {"service_instance_list": [
388 list(s.instances.iterkeys()) for s in GK.services.itervalues()]}
389
390
391 # create a single, global GK object
392 GK = Gatekeeper()
393 # setup Flask
394 app = Flask(__name__)
395 app.config['MAX_CONTENT_LENGTH'] = 512 * 1024 * 1024 # 512 MB max upload
396 api = fr.Api(app)
397 # define endpoints
398 api.add_resource(Packages, '/packages')
399 api.add_resource(Instantiations, '/instantiations')
400
401
402 def start_rest_api(host, port, datacenters=dict()):
403 GK.dcs = datacenters
404 # start the Flask server (not the best performance but ok for our use case)
405 app.run(host=host,
406 port=port,
407 debug=True,
408 use_reloader=False # this is needed to run Flask in a non-main thread
409 )
410
411
412 def ensure_dir(name):
413 if not os.path.exists(name):
414 os.makedirs(name)
415
416
417 def load_yaml(path):
418 with open(path, "r") as f:
419 try:
420 r = yaml.load(f)
421 except yaml.YAMLError as exc:
422 LOG.exception("YAML parse error")
423 r = dict()
424 return r
425
426
427 def make_relative_path(path):
428 if path.startswith("file://"):
429 path = path.replace("file://", "", 1)
430 if path.startswith("/"):
431 path = path.replace("/", "", 1)
432 return path
433
434
435 if __name__ == '__main__':
436 """
437 Lets allow to run the API in standalone mode.
438 """
439 GK_STANDALONE_MODE = True
440 logging.getLogger("werkzeug").setLevel(logging.INFO)
441 start_rest_api("0.0.0.0", 8000)
442