let OpenStack APIs work inside a container
[osm/vim-emu.git] / src / emuvim / api / openstack / openstack_dummies / glance_dummy_api.py
1 from flask_restful import Resource
2 from flask import Response, request
3 from emuvim.api.openstack.openstack_dummies.base_openstack_dummy import BaseOpenstackDummy
4 from emuvim.api.openstack.helper import get_host
5 import logging
6 import json
7
8
9 LOG = logging.getLogger("api.openstack.glance")
10
11
12 class GlanceDummyApi(BaseOpenstackDummy):
13 def __init__(self, in_ip, in_port, compute):
14 super(GlanceDummyApi, self).__init__(in_ip, in_port)
15 self.compute = compute
16 self.api.add_resource(Shutdown,
17 "/shutdown")
18 self.api.add_resource(GlanceListApiVersions,
19 "/versions")
20 self.api.add_resource(GlanceSchema,
21 "/v2/schemas/image",
22 "/v2/schemas/metadefs/namespace",
23 "/v2/schemas/metadefs/resource_type")
24 self.api.add_resource(GlanceListImagesApi,
25 "/v1/images",
26 "/v1/images/detail",
27 "/v2/images",
28 "/v2/images/detail",
29 resource_class_kwargs={'api': self})
30 self.api.add_resource(GlanceImageByIdApi,
31 "/v1/images/<id>",
32 "/v2/images/<id>",
33 resource_class_kwargs={'api': self})
34 self.api.add_resource(GlanceImageByDockerNameApi,
35 "/v1/images/<owner>/<container>",
36 "/v2/images/<owner>/<container>",
37 resource_class_kwargs={'api': self})
38
39 def _start_flask(self):
40 LOG.info("Starting %s endpoint @ http://%s:%d" % ("GlanceDummyApi", self.ip, self.port))
41 if self.app is not None:
42 self.app.before_request(self.dump_playbook)
43 self.app.run(self.ip, self.port, debug=True, use_reloader=False)
44
45
46 class Shutdown(Resource):
47 def get(self):
48 LOG.debug(("%s is beeing shut down") % (__name__))
49 func = request.environ.get('werkzeug.server.shutdown')
50 if func is None:
51 raise RuntimeError('Not running with the Werkzeug Server')
52 func()
53
54
55 class GlanceListApiVersions(Resource):
56 def get(self):
57 LOG.debug("API CALL: %s GET" % str(self.__class__.__name__))
58 resp = dict()
59 resp['versions'] = dict()
60 versions = [{
61 "status": "CURRENT",
62 "id": "v2",
63 "links": [
64 {
65 "href": request.url_root + '/v2',
66 "rel": "self"
67 }
68 ]
69 }]
70 resp['versions'] = versions
71 return Response(json.dumps(resp), status=200, mimetype='application/json')
72
73
74 class GlanceSchema(Resource):
75 def get(self):
76 LOG.debug("API CALL: %s GET" % str(self.__class__.__name__))
77 resp = dict()
78 resp['name'] = 'someImageName'
79 resp['properties'] = dict()
80 # just an ugly hack to allow the openstack client to work
81 return Response(json.dumps(resp), status=200, mimetype='application/json')
82
83
84 class GlanceListImagesApi(Resource):
85 def __init__(self, api):
86 self.api = api
87
88 def get(self):
89 LOG.debug("API CALL: %s GET" % str(self.__class__.__name__))
90 try:
91 resp = dict()
92 resp['next'] = None
93 resp['first'] = "/v2/images"
94 resp['schema'] = "/v2/schemas/images"
95 resp['images'] = list()
96 limit = 18
97 c = 0
98 for image in self.api.compute.images.values():
99 f = dict()
100 f['id'] = image.id
101 f['name'] = str(image.name).replace(":latest", "")
102 f['checksum'] = "2dad48f09e2a447a9bf852bcd93548c1"
103 f['container_format'] = "docker"
104 f['disk_format'] = "raw"
105 f['size'] = 1
106 f['created_at'] = "2016-03-15T15:09:07.000000"
107 f['deleted'] = False
108 f['deleted_at'] = None
109 f['is_public'] = True
110 f['min_disk'] = 1
111 f['min_ram'] = 128
112 f['owner'] = "3dad48f09e2a447a9bf852bcd93548c1"
113 f['properties'] = {}
114 f['protected'] = False
115 f['status'] = "active"
116 f['updated_at'] = "2016-03-15T15:09:07.000000"
117 f['virtual_size'] = 1
118 f['marker'] = None
119 resp['images'].append(f)
120 c += 1
121 if c > limit: # ugly hack to stop buggy glance client to do infinite requests
122 break
123 if "marker" in request.args: # ugly hack to fix pageination of openstack client
124 resp['images'] = None
125 return Response(json.dumps(resp), status=200, mimetype="application/json")
126
127 except Exception as ex:
128 LOG.exception(u"%s: Could not retrieve the list of images." % __name__)
129 return ex.message, 500
130
131 def post(self):
132 """
133 This one is a real fake! It does not really create anything and the mentioned image
134 should already be registered with Docker. However, this function returns a reply that looks
135 like the image was just created to make orchestrators, like OSM, happy.
136 """
137 LOG.debug("API CALL: %s POST" % str(self.__class__.__name__))
138 try:
139 body_data = json.loads(request.data)
140 except:
141 body_data = dict()
142 # lets see what we should create
143 img_name = request.headers.get("X-Image-Meta-Name")
144 img_size = request.headers.get("X-Image-Meta-Size")
145 img_disk_format = request.headers.get("X-Image-Meta-Disk-Format")
146 img_is_public = request.headers.get("X-Image-Meta-Is-Public")
147 img_container_format = request.headers.get("X-Image-Meta-Container-Format")
148 # try to use body payload if header fields are empty
149 if img_name is None:
150 img_name = body_data.get("name")
151 img_size = 1234
152 img_disk_format = body_data.get("disk_format")
153 img_is_public = True if "public" in body_data.get("visibility") else False
154 img_container_format = body_data.get("container_format")
155 # try to find ID of already existing image (matched by name)
156 img_id = None
157 for image in self.api.compute.images.values():
158 if str(img_name) in image.name:
159 img_id = image.id
160 LOG.debug("Image name: %s" % img_name)
161 LOG.debug("Image id: %s" % img_id)
162 # build a response body that looks like a real one
163 resp = dict()
164 f = dict()
165 f['id'] = img_id
166 f['name'] = img_name
167 f['checksum'] = "2dad48f09e2a447a9bf852bcd93548c1"
168 f['container_format'] = img_container_format
169 f['disk_format'] = img_disk_format
170 f['size'] = img_size
171 f['created_at'] = "2016-03-15T15:09:07.000000"
172 f['deleted'] = False
173 f['deleted_at'] = None
174 f['is_public'] = img_is_public
175 f['min_disk'] = 1
176 f['min_ram'] = 128
177 f['owner'] = "3dad48f09e2a447a9bf852bcd93548c1"
178 f['properties'] = {}
179 f['protected'] = False
180 f['status'] = "active"
181 f['updated_at'] = "2016-03-15T15:09:07.000000"
182 f['virtual_size'] = 1
183 resp['image'] = f
184 # build actual response with headers and everything
185 r = Response(json.dumps(resp), status=201, mimetype="application/json")
186 r.headers.add("Location", "http://%s:%d/v1/images/%s" % (get_host(request),
187 self.api.port,
188 img_id))
189 return r
190
191
192 class GlanceImageByIdApi(Resource):
193 def __init__(self, api):
194 self.api = api
195
196 def get(self, id):
197 LOG.debug("API CALL: %s GET" % str(self.__class__.__name__))
198 try:
199 resp = dict()
200 for image in self.api.compute.images.values():
201 if image.id == id or image.name == id:
202 resp['id'] = image.id
203 resp['name'] = image.name
204
205 return Response(json.dumps(resp), status=200, mimetype="application/json")
206
207 response = Response("Image with id or name %s does not exists." % id, status=404)
208 response.headers['Access-Control-Allow-Origin'] = '*'
209 return response
210
211 except Exception as ex:
212 LOG.exception(u"%s: Could not retrieve image with id %s." % (__name__, id))
213 return Response(ex.message, status=500, mimetype='application/json')
214
215 def put(self, id):
216 LOG.debug("API CALL: %s " % str(self.__class__.__name__))
217 LOG.warning("Endpoint not implemented")
218 return None
219
220
221 class GlanceImageByDockerNameApi(Resource):
222 def __init__(self, api):
223 self.api = api
224
225 def get(self, owner, container):
226 logging.debug("API CALL: %s GET" % str(self.__class__.__name__))
227 try:
228 name = "%s/%s" % (owner, container)
229 if name in self.api.compute.images:
230 image = self.api.compute.images[name]
231 resp = dict()
232 resp['id'] = image.id
233 resp['name'] = image.name
234 return Response(json.dumps(resp), status=200, mimetype="application/json")
235
236 response = Response("Image with id or name %s does not exists." % id, status=404)
237 response.headers['Access-Control-Allow-Origin'] = '*'
238 return response
239
240 except Exception as ex:
241 logging.exception(u"%s: Could not retrieve image with id %s." % (__name__, id))
242 return Response(ex.message, status=500, mimetype='application/json')