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()
31 LOG
.info("Create SONATA dummy gatekeeper.")
33 def register_service_package(self
, service_uuid
, service
):
35 register new service package
39 self
.services
[service_uuid
] = service
40 # lets perform all steps needed to onboard the service
44 class Service(object):
46 This class represents a NS uploaded as a *.son package to the
48 Can have multiple running instances of this service.
55 self
.uuid
= service_uuid
56 self
.package_file_hash
= package_file_hash
57 self
.package_file_path
= package_file_path
58 self
.package_content_path
= os
.path
.join(CATALOG_FOLDER
, "services/%s" % self
.uuid
)
62 self
.local_docker_files
= dict()
63 self
.instances
= dict()
65 def start_service(self
, service_uuid
):
66 # TODO implement method
67 # 1. parse descriptors
68 # 2. do the corresponding dc.startCompute(name="foobar") calls
69 # 3. store references to the compute objects in self.instantiations
74 Do all steps to prepare this service to be instantiated
77 # 1. extract the contents of the package and store them in our catalog
78 self
._unpack
_service
_package
()
79 # 2. read in all descriptor files
80 self
._load
_package
_descriptor
()
83 self
._load
_docker
_files
()
84 # 3. prepare container images (e.g. download or build Dockerfile)
85 self
._build
_images
_from
_dockerfiles
()
86 self
._download
_predefined
_dockerimages
()
88 LOG
.info("On-boarded service: %r" % self
.manifest
.get("package_name"))
90 def _unpack_service_package(self
):
92 unzip *.son file and store contents in CATALOG_FOLDER/services/<service_uuid>/
94 with zipfile
.ZipFile(self
.package_file_path
, "r") as z
:
95 z
.extractall(self
.package_content_path
)
97 def _load_package_descriptor(self
):
99 Load the main package descriptor YAML and keep it as dict.
102 self
.manifest
= load_yaml(
104 self
.package_content_path
, "META-INF/MANIFEST.MF"))
108 Load the entry NSD YAML and keep it as dict.
111 if "entry_service_template" in self
.manifest
:
112 nsd_path
= os
.path
.join(
113 self
.package_content_path
,
114 make_relative_path(self
.manifest
.get("entry_service_template")))
115 self
.nsd
= load_yaml(nsd_path
)
116 LOG
.debug("Loaded NSD: %r" % self
.nsd
.get("ns_name"))
118 def _load_vnfd(self
):
120 Load all VNFD YAML files referenced in MANIFEST.MF and keep them in dict.
123 if "package_content" in self
.manifest
:
124 for pc
in self
.manifest
.get("package_content"):
125 if pc
.get("content-type") == "application/sonata.function_descriptor":
126 vnfd_path
= os
.path
.join(
127 self
.package_content_path
,
128 make_relative_path(pc
.get("name")))
129 vnfd
= load_yaml(vnfd_path
)
130 self
.vnfds
[vnfd
.get("vnf_name")] = vnfd
131 LOG
.debug("Loaded VNFD: %r" % vnfd
.get("vnf_name"))
133 def _load_docker_files(self
):
135 Get all paths to Dockerfiles from MANIFEST.MF and store them in dict.
138 if "package_content" in self
.manifest
:
139 for df
in self
.manifest
.get("package_content"):
140 if df
.get("content-type") == "application/sonata.docker_files":
141 docker_path
= os
.path
.join(
142 self
.package_content_path
,
143 make_relative_path(df
.get("name")))
144 # FIXME: Mapping to docker image names is hardcoded because of the missing mapping in the example package
145 self
.local_docker_files
[helper_map_docker_name(df
.get("name"))] = docker_path
146 LOG
.debug("Found Dockerfile: %r" % docker_path
)
148 def _build_images_from_dockerfiles(self
):
150 Build Docker images for each local Dockerfile found in the package: self.local_docker_files
153 LOG
.info("Building %d Docker images (this may take several minutes) ..." % len(self
.local_docker_files
))
154 for k
, v
in self
.local_docker_files
.iteritems():
155 for line
in dc
.build(path
=v
.replace("Dockerfile", ""), tag
=k
, rm
=False, nocache
=False):
156 LOG
.debug("DOCKER BUILD: %s" % line
)
157 LOG
.info("Docker image created: %s" % k
)
159 def _download_predefined_dockerimages(self
):
161 If the package contains URLs to pre-build Docker images, we download them with this method.
168 Resource definitions and API endpoints
172 class Packages(fr
.Resource
):
176 Upload a *.son service package to the dummy gatekeeper.
178 We expect request with a *.son file and store it in UPLOAD_FOLDER
183 son_file
= request
.files
['file']
184 # generate a uuid to reference this package
185 service_uuid
= str(uuid
.uuid4())
186 file_hash
= hashlib
.sha1(str(son_file
)).hexdigest()
187 # ensure that upload folder exists
188 ensure_dir(UPLOAD_FOLDER
)
189 upload_path
= os
.path
.join(UPLOAD_FOLDER
, "%s.son" % service_uuid
)
190 # store *.son file to disk
191 son_file
.save(upload_path
)
192 size
= os
.path
.getsize(upload_path
)
193 # create a service object and register it
194 s
= Service(service_uuid
, file_hash
, upload_path
)
195 GK
.register_service_package(service_uuid
, s
)
196 # generate the JSON result
197 return {"service_uuid": service_uuid
, "size": size
, "sha1": file_hash
, "error": None}
198 except Exception as ex
:
199 LOG
.exception("Service package upload failed:")
200 return {"service_uuid": None, "size": 0, "sha1": None, "error": "upload failed"}
204 Return a list of UUID's of uploaded service packages.
207 return {"service_uuid_list": list(GK
.services
.iterkeys())}
210 class Instantiations(fr
.Resource
):
214 Instantiate a service specified by its UUID.
215 Will return a new UUID to identify the running service instance.
218 # TODO implement method (start real service)
219 json_data
= request
.get_json(force
=True)
220 service_uuid
= json_data
.get("service_uuid")
221 if service_uuid
is not None:
222 service_instance_uuid
= str(uuid
.uuid4())
223 LOG
.info("Starting service %r" % service_uuid
)
224 return {"service_instance_uuid": service_instance_uuid
}
229 Returns a list of UUIDs containing all running services.
232 # TODO implement method
233 return {"service_instance_uuid_list": list()}
236 # create a single, global GK object
239 app
= Flask(__name__
)
240 app
.config
['MAX_CONTENT_LENGTH'] = 512 * 1024 * 1024 # 512 MB max upload
243 api
.add_resource(Packages
, '/api/packages')
244 api
.add_resource(Instantiations
, '/api/instantiations')
247 def start_rest_api(host
, port
):
248 # start the Flask server (not the best performance but ok for our use case)
252 use_reloader
=False # this is needed to run Flask in a non-main thread
256 def ensure_dir(name
):
257 if not os
.path
.exists(name
):
262 with
open(path
, "r") as f
:
265 except yaml
.YAMLError
as exc
:
266 LOG
.exception("YAML parse error")
271 def make_relative_path(path
):
272 if path
.startswith("/"):
273 return path
.replace("/", "", 1)
277 def helper_map_docker_name(name
):
279 Quick hack to fix missing dependency in example package.
281 # TODO remove this when package description is fixed
283 "/docker_files/iperf/Dockerfile": "iperf_docker",
284 "/docker_files/firewall/Dockerfile": "fw_docker",
285 "/docker_files/tcpdump/Dockerfile": "tcpdump_docker"
287 return mapping
.get(name
)
290 if __name__
== '__main__':
292 Lets allow to run the API in standalone mode.
294 logging
.getLogger("werkzeug").setLevel(logging
.INFO
)
295 start_rest_api("0.0.0.0", 8000)