Merge pull request #41 from mpeuster/master
[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 json
13 from flask import Flask, request
14 import flask_restful as fr
15
16 logging.getLogger("werkzeug").setLevel(logging.WARNING)
17
18
19 UPLOAD_FOLDER = "/tmp/son-dummy-gk/uploads/"
20 CATALOG_FOLDER = "/tmp/son-dummy-gk/catalog/"
21
22
23 class Gatekeeper(object):
24
25 def __init__(self):
26 self.packages = dict()
27 self.instantiations = dict()
28 logging.info("Create SONATA dummy gatekeeper.")
29
30 def unpack_service_package(self, service_uuid):
31 # TODO implement method
32 # 1. unzip *.son file and store contents in CATALOG_FOLDER/services/<service_uuid>/
33 pass
34
35 def start_service(self, service_uuid):
36 # TODO implement method
37 # 1. parse descriptors
38 # 2. do the corresponding dc.startCompute(name="foobar") calls
39 # 3. store references to the compute objects in self.instantiations
40 pass
41
42
43 """
44 Resource definitions and API endpoints
45 """
46
47
48 class Packages(fr.Resource):
49
50 def post(self):
51 """
52 Upload a *.son service package to the dummy gatekeeper.
53
54 We expect request with a *.son file and store it in UPLOAD_FOLDER
55 :return: UUID
56 """
57 try:
58 # get file contents
59 file = request.files['file']
60 # generate a uuid to reference this package
61 service_uuid = str(uuid.uuid4())
62 hash = hashlib.sha1(str(file)).hexdigest()
63 # ensure that upload folder exists
64 ensure_dir(UPLOAD_FOLDER)
65 upload_path = os.path.join(UPLOAD_FOLDER, "%s.son" % service_uuid)
66 # store *.son file to disk
67 file.save(upload_path)
68 size = os.path.getsize(upload_path)
69 # store a reference to the uploaded package in our gatekeeper
70 GK.packages[service_uuid] = upload_path
71 # generate the JSON result
72 return {"service_uuid": service_uuid, "size": size, "sha1": hash, "error": None}
73 except Exception as ex:
74 logging.exception("Service package upload failed:")
75 return {"service_uuid": None, "size": 0, "sha1": None, "error": "upload failed"}
76
77 def get(self):
78 """
79 Return a list of UUID's of uploaded service packages.
80 :return: dict/list
81 """
82 return {"service_uuid_list": list(GK.packages.iterkeys())}
83
84
85 class Instantiations(fr.Resource):
86
87 def post(self):
88 """
89 Instantiate a service specified by its UUID.
90 Will return a new UUID to identify the running service instance.
91 :return: UUID
92 """
93 # TODO implement method (start real service)
94 json_data = request.get_json(force=True)
95 service_uuid = json_data.get("service_uuid")
96 if service_uuid is not None:
97 service_instance_uuid = str(uuid.uuid4())
98 GK.instantiations[service_instance_uuid] = service_uuid
99 logging.info("Starting service %r" % service_uuid)
100 return {"service_instance_uuid": service_instance_uuid}
101 return None
102
103 def get(self):
104 """
105 Returns a list of UUIDs containing all running services.
106 :return: dict / list
107 """
108 # TODO implement method
109 return {"service_instance_uuid_list": list(GK.instantiations.iterkeys())}
110
111 # create a single, global GK object
112 GK = Gatekeeper()
113 # setup Flask
114 app = Flask(__name__)
115 app.config['MAX_CONTENT_LENGTH'] = 512 * 1024 * 1024 # 512 MB max upload
116 api = fr.Api(app)
117 # define endpoints
118 api.add_resource(Packages, '/api/packages/uploads')
119 api.add_resource(Instantiations, '/api/instantiations')
120
121
122 def start_rest_api(host, port):
123 # start the Flask server (not the best performance but ok for our use case)
124 app.run(host=host,
125 port=port,
126 debug=True,
127 use_reloader=False # this is needed to run Flask in a non-main thread
128 )
129
130
131 def ensure_dir(name):
132 if not os.path.exists(name):
133 os.makedirs(name)
134
135
136 if __name__ == '__main__':
137 """
138 Lets allow to run the API in standalone mode.
139 """
140 logging.getLogger("werkzeug").setLevel(logging.INFO)
141 start_rest_api("0.0.0.0", 8000)
142