2 This module implements a simple REST API that behaves like SONATA's gatekeeper.
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.
14 from docker
import Client
as DockerClient
15 from flask
import Flask
, request
16 import flask_restful
as fr
18 LOG
= logging
.getLogger("sonata-dummy-gatekeeper")
19 LOG
.setLevel(logging
.DEBUG
)
20 logging
.getLogger("werkzeug").setLevel(logging
.WARNING
)
23 UPLOAD_FOLDER
= "/tmp/son-dummy-gk/uploads/"
24 CATALOG_FOLDER
= "/tmp/son-dummy-gk/catalog/"
27 class Gatekeeper(object):
30 self
.services
= dict()
32 LOG
.info("Create SONATA dummy gatekeeper.")
34 def register_service_package(self
, service_uuid
, service
):
36 register new service package
40 self
.services
[service_uuid
] = service
41 # lets perform all steps needed to onboard the service
45 class Service(object):
47 This class represents a NS uploaded as a *.son package to the
49 Can have multiple running instances of this service.
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
)
63 self
.local_docker_files
= dict()
64 self
.instances
= dict()
68 Do all steps to prepare this service to be instantiated
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
()
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
()
82 LOG
.info("On-boarded service: %r" % self
.manifest
.get("package_name"))
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
99 def _unpack_service_package(self
):
101 unzip *.son file and store contents in CATALOG_FOLDER/services/<service_uuid>/
103 with zipfile
.ZipFile(self
.package_file_path
, "r") as z
:
104 z
.extractall(self
.package_content_path
)
106 def _load_package_descriptor(self
):
108 Load the main package descriptor YAML and keep it as dict.
111 self
.manifest
= load_yaml(
113 self
.package_content_path
, "META-INF/MANIFEST.MF"))
117 Load the entry NSD YAML and keep it as dict.
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"))
127 def _load_vnfd(self
):
129 Load all VNFD YAML files referenced in MANIFEST.MF and keep them in dict.
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"))
142 def _load_docker_files(self
):
144 Get all paths to Dockerfiles from MANIFEST.MF and store them in dict.
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
)
157 def _build_images_from_dockerfiles(self
):
159 Build Docker images for each local Dockerfile found in the package: self.local_docker_files
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
)
168 def _download_predefined_dockerimages(self
):
170 If the package contains URLs to pre-build Docker images, we download them with this method.
175 def _calculate_placement(self
, algorithm
):
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.
181 assert(len(self
.vnfds
) > 0)
182 assert(len(GK
.dcs
) > 0)
183 # instantiate algorithm an place
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"))))
193 Some (simple) placement algorithms
197 class FirstDcPlacement(object):
199 Placement: Always use one and the same data center from the GK.dcs dict.
201 def place(self
, nsd
, vnfds
, dcs
):
202 for name
, vnfd
in vnfds
.iteritems():
203 vnfd
["dc"] = list(dcs
.itervalues())[0]
207 Resource definitions and API endpoints
211 class Packages(fr
.Resource
):
215 Upload a *.son service package to the dummy gatekeeper.
217 We expect request with a *.son file and store it in UPLOAD_FOLDER
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"}
243 Return a list of UUID's of uploaded service packages.
246 return {"service_uuid_list": list(GK
.services
.iterkeys())}
249 class Instantiations(fr
.Resource
):
253 Instantiate a service specified by its UUID.
254 Will return a new UUID to identify the running service instance.
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
269 Returns a list of UUIDs containing all running services.
272 # TODO implement method
273 return {"service_instance_uuid_list": list()}
276 # create a single, global GK object
279 app
= Flask(__name__
)
280 app
.config
['MAX_CONTENT_LENGTH'] = 512 * 1024 * 1024 # 512 MB max upload
283 api
.add_resource(Packages
, '/api/packages')
284 api
.add_resource(Instantiations
, '/api/instantiations')
287 def start_rest_api(host
, port
, datacenters
=dict()):
289 # start the Flask server (not the best performance but ok for our use case)
293 use_reloader
=False # this is needed to run Flask in a non-main thread
297 def ensure_dir(name
):
298 if not os
.path
.exists(name
):
303 with
open(path
, "r") as f
:
306 except yaml
.YAMLError
as exc
:
307 LOG
.exception("YAML parse error")
312 def make_relative_path(path
):
313 if path
.startswith("/"):
314 return path
.replace("/", "", 1)
318 def helper_map_docker_name(name
):
320 Quick hack to fix missing dependency in example package.
322 # TODO remove this when package description is fixed
324 "/docker_files/iperf/Dockerfile": "iperf_docker",
325 "/docker_files/firewall/Dockerfile": "fw_docker",
326 "/docker_files/tcpdump/Dockerfile": "tcpdump_docker"
328 return mapping
.get(name
)
331 if __name__
== '__main__':
333 Lets allow to run the API in standalone mode.
335 logging
.getLogger("werkzeug").setLevel(logging
.INFO
)
336 start_rest_api("0.0.0.0", 8000)