Added placement interface and a dumb placement algorithm that always uses the first...
[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 LOG.info("Create SONATA dummy gatekeeper.")
33
34 def register_service_package(self, service_uuid, service):
35 """
36 register new service package
37 :param service_uuid
38 :param service object
39 """
40 self.services[service_uuid] = service
41 # lets perform all steps needed to onboard the service
42 service.onboard()
43
44
45 class Service(object):
46 """
47 This class represents a NS uploaded as a *.son package to the
48 dummy gatekeeper.
49 Can have multiple running instances of this service.
50 """
51
52 def __init__(self,
53 service_uuid,
54 package_file_hash,
55 package_file_path):
56 self.uuid = service_uuid
57 self.package_file_hash = package_file_hash
58 self.package_file_path = package_file_path
59 self.package_content_path = os.path.join(CATALOG_FOLDER, "services/%s" % self.uuid)
60 self.manifest = None
61 self.nsd = None
62 self.vnfds = dict()
63 self.local_docker_files = dict()
64 self.instances = dict()
65
66 def onboard(self):
67 """
68 Do all steps to prepare this service to be instantiated
69 :return:
70 """
71 # 1. extract the contents of the package and store them in our catalog
72 self._unpack_service_package()
73 # 2. read in all descriptor files
74 self._load_package_descriptor()
75 self._load_nsd()
76 self._load_vnfd()
77 self._load_docker_files()
78 # 3. prepare container images (e.g. download or build Dockerfile)
79 self._build_images_from_dockerfiles()
80 self._download_predefined_dockerimages()
81
82 LOG.info("On-boarded service: %r" % self.manifest.get("package_name"))
83
84 def start_service(self):
85 # TODO implement method
86 # each service instance gets a new uuid to identify it
87 instance_uuid = str(uuid.uuid4())
88 # compute placement of this service instance (adds DC names to VNFDs)
89 self._calculate_placement(FirstDcPlacement)
90 # 1. parse descriptors and get name of each docker container
91 for vnfd in self.vnfds.itervalues():
92 for u in vnfd.get("virtual_deployment_units"):
93 docker_name = u.get("vm_image")
94 # 2. do the corresponding dc.startCompute(name="foobar") calls
95 print "start %r" % docker_name
96 # 3. store references to the compute objects in self.instantiations
97 return instance_uuid
98
99 def _unpack_service_package(self):
100 """
101 unzip *.son file and store contents in CATALOG_FOLDER/services/<service_uuid>/
102 """
103 with zipfile.ZipFile(self.package_file_path, "r") as z:
104 z.extractall(self.package_content_path)
105
106 def _load_package_descriptor(self):
107 """
108 Load the main package descriptor YAML and keep it as dict.
109 :return:
110 """
111 self.manifest = load_yaml(
112 os.path.join(
113 self.package_content_path, "META-INF/MANIFEST.MF"))
114
115 def _load_nsd(self):
116 """
117 Load the entry NSD YAML and keep it as dict.
118 :return:
119 """
120 if "entry_service_template" in self.manifest:
121 nsd_path = os.path.join(
122 self.package_content_path,
123 make_relative_path(self.manifest.get("entry_service_template")))
124 self.nsd = load_yaml(nsd_path)
125 LOG.debug("Loaded NSD: %r" % self.nsd.get("ns_name"))
126
127 def _load_vnfd(self):
128 """
129 Load all VNFD YAML files referenced in MANIFEST.MF and keep them in dict.
130 :return:
131 """
132 if "package_content" in self.manifest:
133 for pc in self.manifest.get("package_content"):
134 if pc.get("content-type") == "application/sonata.function_descriptor":
135 vnfd_path = os.path.join(
136 self.package_content_path,
137 make_relative_path(pc.get("name")))
138 vnfd = load_yaml(vnfd_path)
139 self.vnfds[vnfd.get("vnf_name")] = vnfd
140 LOG.debug("Loaded VNFD: %r" % vnfd.get("vnf_name"))
141
142 def _load_docker_files(self):
143 """
144 Get all paths to Dockerfiles from MANIFEST.MF and store them in dict.
145 :return:
146 """
147 if "package_content" in self.manifest:
148 for df in self.manifest.get("package_content"):
149 if df.get("content-type") == "application/sonata.docker_files":
150 docker_path = os.path.join(
151 self.package_content_path,
152 make_relative_path(df.get("name")))
153 # FIXME: Mapping to docker image names is hardcoded because of the missing mapping in the example package
154 self.local_docker_files[helper_map_docker_name(df.get("name"))] = docker_path
155 LOG.debug("Found Dockerfile: %r" % docker_path)
156
157 def _build_images_from_dockerfiles(self):
158 """
159 Build Docker images for each local Dockerfile found in the package: self.local_docker_files
160 """
161 dc = DockerClient()
162 LOG.info("Building %d Docker images (this may take several minutes) ..." % len(self.local_docker_files))
163 for k, v in self.local_docker_files.iteritems():
164 for line in dc.build(path=v.replace("Dockerfile", ""), tag=k, rm=False, nocache=False):
165 LOG.debug("DOCKER BUILD: %s" % line)
166 LOG.info("Docker image created: %s" % k)
167
168 def _download_predefined_dockerimages(self):
169 """
170 If the package contains URLs to pre-build Docker images, we download them with this method.
171 """
172 # TODO implement
173 pass
174
175 def _calculate_placement(self, algorithm):
176 """
177 Do placement by adding the a field "dc" to
178 each VNFD that points to one of our
179 data center objects known to the gatekeeper.
180 """
181 assert(len(self.vnfds) > 0)
182 assert(len(GK.dcs) > 0)
183 # instantiate algorithm an place
184 p = algorithm()
185 p.place(self.nsd, self.vnfds, GK.dcs)
186 LOG.info("Using placement algorithm: %r" % p.__class__.__name__)
187 # lets print the placement result
188 for name, vnfd in self.vnfds.iteritems():
189 LOG.info("Placed VNF %r on DC %r" % (name, str(vnfd.get("dc"))))
190
191
192 """
193 Some (simple) placement algorithms
194 """
195
196
197 class FirstDcPlacement(object):
198 """
199 Placement: Always use one and the same data center from the GK.dcs dict.
200 """
201 def place(self, nsd, vnfds, dcs):
202 for name, vnfd in vnfds.iteritems():
203 vnfd["dc"] = list(dcs.itervalues())[0]
204
205
206 """
207 Resource definitions and API endpoints
208 """
209
210
211 class Packages(fr.Resource):
212
213 def post(self):
214 """
215 Upload a *.son service package to the dummy gatekeeper.
216
217 We expect request with a *.son file and store it in UPLOAD_FOLDER
218 :return: UUID
219 """
220 try:
221 # get file contents
222 son_file = request.files['file']
223 # generate a uuid to reference this package
224 service_uuid = str(uuid.uuid4())
225 file_hash = hashlib.sha1(str(son_file)).hexdigest()
226 # ensure that upload folder exists
227 ensure_dir(UPLOAD_FOLDER)
228 upload_path = os.path.join(UPLOAD_FOLDER, "%s.son" % service_uuid)
229 # store *.son file to disk
230 son_file.save(upload_path)
231 size = os.path.getsize(upload_path)
232 # create a service object and register it
233 s = Service(service_uuid, file_hash, upload_path)
234 GK.register_service_package(service_uuid, s)
235 # generate the JSON result
236 return {"service_uuid": service_uuid, "size": size, "sha1": file_hash, "error": None}
237 except Exception as ex:
238 LOG.exception("Service package upload failed:")
239 return {"service_uuid": None, "size": 0, "sha1": None, "error": "upload failed"}
240
241 def get(self):
242 """
243 Return a list of UUID's of uploaded service packages.
244 :return: dict/list
245 """
246 return {"service_uuid_list": list(GK.services.iterkeys())}
247
248
249 class Instantiations(fr.Resource):
250
251 def post(self):
252 """
253 Instantiate a service specified by its UUID.
254 Will return a new UUID to identify the running service instance.
255 :return: UUID
256 """
257 # TODO implement method (start real service)
258 json_data = request.get_json(force=True)
259 service_uuid = list(GK.services.iterkeys())[0] #json_data.get("service_uuid") # TODO only for quick testing
260 if service_uuid in GK.services:
261 LOG.info("Starting service %r" % service_uuid)
262 service_instance_uuid = GK.services.get(service_uuid).start_service()
263 LOG.info("Service started. Instance id: %r" % service_instance_uuid)
264 return {"service_instance_uuid": service_instance_uuid}
265 return "Service not found", 404
266
267 def get(self):
268 """
269 Returns a list of UUIDs containing all running services.
270 :return: dict / list
271 """
272 # TODO implement method
273 return {"service_instance_uuid_list": list()}
274
275
276 # create a single, global GK object
277 GK = Gatekeeper()
278 # setup Flask
279 app = Flask(__name__)
280 app.config['MAX_CONTENT_LENGTH'] = 512 * 1024 * 1024 # 512 MB max upload
281 api = fr.Api(app)
282 # define endpoints
283 api.add_resource(Packages, '/api/packages')
284 api.add_resource(Instantiations, '/api/instantiations')
285
286
287 def start_rest_api(host, port, datacenters=dict()):
288 GK.dcs = datacenters
289 # start the Flask server (not the best performance but ok for our use case)
290 app.run(host=host,
291 port=port,
292 debug=True,
293 use_reloader=False # this is needed to run Flask in a non-main thread
294 )
295
296
297 def ensure_dir(name):
298 if not os.path.exists(name):
299 os.makedirs(name)
300
301
302 def load_yaml(path):
303 with open(path, "r") as f:
304 try:
305 r = yaml.load(f)
306 except yaml.YAMLError as exc:
307 LOG.exception("YAML parse error")
308 r = dict()
309 return r
310
311
312 def make_relative_path(path):
313 if path.startswith("/"):
314 return path.replace("/", "", 1)
315 return path
316
317
318 def helper_map_docker_name(name):
319 """
320 Quick hack to fix missing dependency in example package.
321 """
322 # TODO remove this when package description is fixed
323 mapping = {
324 "/docker_files/iperf/Dockerfile": "iperf_docker",
325 "/docker_files/firewall/Dockerfile": "fw_docker",
326 "/docker_files/tcpdump/Dockerfile": "tcpdump_docker"
327 }
328 return mapping.get(name)
329
330
331 if __name__ == '__main__':
332 """
333 Lets allow to run the API in standalone mode.
334 """
335 logging.getLogger("werkzeug").setLevel(logging.INFO)
336 start_rest_api("0.0.0.0", 8000)
337