WORKS! First dummy GK version that is ablte to deploy the example service package...
[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 LOG = logging.getLogger("sonata-dummy-gatekeeper")
19 LOG.setLevel(logging.DEBUG)
20 logging.getLogger("werkzeug").setLevel(logging.WARNING)
21
22
23 UPLOAD_FOLDER = "/tmp/son-dummy-gk/uploads/"
24 CATALOG_FOLDER = "/tmp/son-dummy-gk/catalog/"
25
26
27 class Gatekeeper(object):
28
29 def __init__(self):
30 self.services = dict()
31 self.dcs = dict()
32 self.vnf_counter = 0 # used to generate short names for VNFs (Mininet limitation)
33 LOG.info("Create SONATA dummy gatekeeper.")
34
35 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
45 def get_next_vnf_name(self):
46 self.vnf_counter += 1
47 return "sonvnf%d" % self.vnf_counter
48
49
50 class 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)
65 self.manifest = None
66 self.nsd = None
67 self.vnfds = dict()
68 self.local_docker_files = dict()
69 self.instances = dict()
70
71 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
79 self._load_package_descriptor()
80 self._load_nsd()
81 self._load_vnfd()
82 self._load_docker_files()
83 # 3. prepare container images (e.g. download or build Dockerfile)
84 self._build_images_from_dockerfiles()
85 self._download_predefined_dockerimages()
86
87 LOG.info("On-boarded service: %r" % self.manifest.get("package_name"))
88
89 def start_service(self):
90 """
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
99 instance_uuid = str(uuid.uuid4())
100 # 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)
104 self._calculate_placement(FirstDcPlacement)
105 # iterate over all vnfds that we have to start
106 for vnfd in self.vnfds.itervalues():
107 # iterate over all deployment units within each VNFDs
108 for u in vnfd.get("virtual_deployment_units"):
109 # 3. get the name of the docker image to start and the assigned DC
110 docker_name = u.get("vm_image")
111 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)
123 return instance_uuid
124
125 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
132 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
180 self.local_docker_files[helper_map_docker_name(df.get("name"))] = docker_path
181 LOG.debug("Found Dockerfile: %r" % docker_path)
182
183 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 """
198 # TODO implement
199 pass
200
201 def _check_docker_image_exists(self, image_name):
202 # TODO implement
203 return True
204
205 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 """
223 Some (simple) placement algorithms
224 """
225
226
227 class 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
235
236 """
237 Resource definitions and API endpoints
238 """
239
240
241 class Packages(fr.Resource):
242
243 def post(self):
244 """
245 Upload a *.son service package to the dummy gatekeeper.
246
247 We expect request with a *.son file and store it in UPLOAD_FOLDER
248 :return: UUID
249 """
250 try:
251 # get file contents
252 son_file = request.files['file']
253 # generate a uuid to reference this package
254 service_uuid = str(uuid.uuid4())
255 file_hash = hashlib.sha1(str(son_file)).hexdigest()
256 # 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
260 son_file.save(upload_path)
261 size = os.path.getsize(upload_path)
262 # create a service object and register it
263 s = Service(service_uuid, file_hash, upload_path)
264 GK.register_service_package(service_uuid, s)
265 # generate the JSON result
266 return {"service_uuid": service_uuid, "size": size, "sha1": file_hash, "error": None}
267 except Exception as ex:
268 LOG.exception("Service package upload failed:")
269 return {"service_uuid": None, "size": 0, "sha1": None, "error": "upload failed"}
270
271 def get(self):
272 """
273 Return a list of UUID's of uploaded service packages.
274 :return: dict/list
275 """
276 return {"service_uuid_list": list(GK.services.iterkeys())}
277
278
279 class Instantiations(fr.Resource):
280
281 def post(self):
282 """
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)
289 service_uuid = list(GK.services.iterkeys())[0] #json_data.get("service_uuid") # TODO only for quick testing
290 if service_uuid in GK.services:
291 service_instance_uuid = GK.services.get(service_uuid).start_service()
292 return {"service_instance_uuid": service_instance_uuid}
293 return "Service not found", 404
294
295 def get(self):
296 """
297 Returns a list of UUIDs containing all running services.
298 :return: dict / list
299 """
300 # TODO implement method
301 return {"service_instance_uuid_list": list()}
302
303
304 # create a single, global GK object
305 GK = Gatekeeper()
306 # setup Flask
307 app = Flask(__name__)
308 app.config['MAX_CONTENT_LENGTH'] = 512 * 1024 * 1024 # 512 MB max upload
309 api = fr.Api(app)
310 # define endpoints
311 api.add_resource(Packages, '/api/packages')
312 api.add_resource(Instantiations, '/api/instantiations')
313
314
315 def start_rest_api(host, port, datacenters=dict()):
316 GK.dcs = datacenters
317 # 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
325 def ensure_dir(name):
326 if not os.path.exists(name):
327 os.makedirs(name)
328
329
330 def 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
340 def make_relative_path(path):
341 if path.startswith("/"):
342 return path.replace("/", "", 1)
343 return path
344
345
346 def 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)
357
358
359 if __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