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