1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
|
##############################################################################
# Copyright (c) 2015 Orange
# guyrodrigue.koffi@orange.com / koffirodrigue@gmail.com
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0
# feng.xiaowei@zte.com.cn refactor db.pod to db.pods 5-19-2016
# feng.xiaowei@zte.com.cn refactor test_project to project 5-19-2016
# feng.xiaowei@zte.com.cn refactor response body 5-19-2016
# feng.xiaowei@zte.com.cn refactor pod/project response info 5-19-2016
# feng.xiaowei@zte.com.cn refactor testcase related handler 5-20-2016
# feng.xiaowei@zte.com.cn refactor result related handler 5-23-2016
# feng.xiaowei@zte.com.cn refactor dashboard related handler 5-24-2016
# feng.xiaowei@zte.com.cn add methods to GenericApiHandler 5-26-2016
# feng.xiaowei@zte.com.cn remove PodHandler 5-26-2016
# feng.xiaowei@zte.com.cn remove ProjectHandler 5-26-2016
# feng.xiaowei@zte.com.cn remove TestcaseHandler 5-27-2016
# feng.xiaowei@zte.com.cn remove ResultHandler 5-29-2016
# feng.xiaowei@zte.com.cn remove DashboardHandler 5-30-2016
##############################################################################
from datetime import datetime
import json
from tornado import gen
from tornado import web
from opnfv_testapi.common import check
from opnfv_testapi.common import message
from opnfv_testapi.common import raises
from opnfv_testapi.db import api as dbapi
from opnfv_testapi.models import base_models
from opnfv_testapi.tornado_swagger import swagger
DEFAULT_REPRESENTATION = "application/json"
class GenericApiHandler(web.RequestHandler):
def __init__(self, application, request, **kwargs):
super(GenericApiHandler, self).__init__(application, request, **kwargs)
self.json_args = None
self.table = None
self.table_cls = None
self.db_projects = 'projects'
self.db_pods = 'pods'
self.db_testcases = 'testcases'
self.db_results = 'results'
self.db_scenarios = 'scenarios'
self.db_deployresults = 'deployresults'
self.auth = self.settings["auth"]
def prepare(self):
if self.request.body:
if self.request.headers.get("Content-Type") is not None:
if self.request.headers["Content-Type"].startswith(
DEFAULT_REPRESENTATION):
try:
self.json_args = json.loads(self.request.body)
except (ValueError, KeyError, TypeError) as error:
raises.BadRequest(message.bad_format(str(error)))
def finish_request(self, json_object=None):
if json_object:
self.write(json.dumps(json_object))
self.set_header("Content-Type", DEFAULT_REPRESENTATION)
self.finish()
def _create_response(self, resource):
href = self.request.full_url() + '/' + str(resource)
return base_models.CreateResponse(href=href).format()
def format_data(self, data):
cls_data = self.table_cls.from_dict(data)
return cls_data.format_http()
@web.asynchronous
@gen.coroutine
@check.valid_token
@check.no_body
@check.miss_fields
@check.new_not_exists
@check.is_authorized
@check.values_check
@check.carriers_exist
def _create(self, **kwargs):
"""
:param miss_checks: [miss1, miss2]
:param db_checks: [(table, exist, query, error)]
"""
data = self.table_cls.from_dict(self.json_args)
for k, v in kwargs.iteritems():
if k != 'query':
data.__setattr__(k, v)
if 'results' not in self.table:
data.creation_date = datetime.now()
_id = yield dbapi.db_save(self.table, data.format())
if 'name' in self.json_args:
resource = data.name
else:
resource = _id
self.finish_request(self._create_response(resource))
@web.asynchronous
@gen.coroutine
@check.query_by_name
def _list(self, query=None, **kwargs):
sort = kwargs.get('sort')
page = kwargs.get('page', 0)
last = kwargs.get('last', 0)
per_page = kwargs.get('per_page', 0)
if query is None:
query = {}
pipelines = list()
pipelines.append({'$match': query})
total_pages = 0
data = list()
cursor = dbapi.db_list(self.table, query)
records_count = yield cursor.count()
if records_count > 0:
if page > 0:
total_pages, return_nr = self._calc_total_pages(records_count,
last,
page,
per_page)
pipelines = self._set_pipelines(pipelines,
sort,
return_nr,
page,
per_page)
cursor = dbapi.db_aggregate(self.table, pipelines)
while (yield cursor.fetch_next):
data.append(self.format_data(cursor.next_object()))
res = {self.table: data}
if page > 0:
res.update({
'pagination': {
'current_page': kwargs.get('page'),
'total_pages': total_pages
}
})
self.finish_request(res)
@staticmethod
def _calc_total_pages(records_count, last, page, per_page):
records_nr = records_count
if (records_count > last) and (last > 0):
records_nr = last
total_pages, remainder = divmod(records_nr, per_page)
if remainder > 0:
total_pages += 1
if page > 1 and page > total_pages:
raises.BadRequest(
'Request page > total_pages [{}]'.format(total_pages))
return total_pages, records_nr
@staticmethod
def _set_pipelines(pipelines, sort, return_nr, page, per_page):
if sort:
pipelines.append({'$sort': sort})
over = (page - 1) * per_page
left = return_nr - over
pipelines.append({'$skip': over})
pipelines.append({'$limit': per_page if per_page < left else left})
return pipelines
@web.asynchronous
@gen.coroutine
@check.not_exist
def _get_one(self, data, query=None):
self.finish_request(self.format_data(data))
@web.asynchronous
@gen.coroutine
@check.not_exist
@check.is_authorized
@check.is_reource_tied
def _delete(self, data, query=None):
yield dbapi.db_delete(self.table, query)
self.finish_request()
@web.asynchronous
@gen.coroutine
@check.no_body
@check.not_exist
@check.updated_one_not_exist
@check.is_authorized
@check.is_reource_tied
def _update(self, data, query=None, **kwargs):
data = self.table_cls.from_dict(data)
update_req = self._update_requests(data)
yield dbapi.db_update(self.table, query, update_req)
update_req['_id'] = str(data._id)
self.finish_request(update_req)
@web.asynchronous
@gen.coroutine
@check.no_body
@check.not_exist
@check.is_authorized
@check.updated_one_not_exist
def pure_update(self, data, query=None, **kwargs):
data = self.table_cls.from_dict(data)
update_req = self._update_requests(data)
yield dbapi.db_update(self.table, query, update_req)
self.finish_request()
def _update_requests(self, data):
request = dict()
for k, v in self.json_args.iteritems():
request = self._update_request(request, k, v,
data.__getattribute__(k))
if not request:
raises.Forbidden(message.no_update())
edit_request = data.format()
edit_request.update(request)
return edit_request
@staticmethod
def _update_request(edit_request, key, new_value, old_value):
"""
This function serves to prepare the elements in the update request.
We try to avoid replace the exact values in the db
edit_request should be a dict in which we add an entry (key) after
comparing values
"""
if not (new_value is None):
if new_value != old_value:
edit_request[key] = new_value
return edit_request
def _update_query(self, keys, data):
query = dict()
equal = True
for key in keys:
new = self.json_args.get(key)
old = data.get(key)
if new is None:
new = old
elif new != old:
equal = False
query[key] = new
return query if not equal else dict()
class VersionHandler(GenericApiHandler):
@swagger.operation(nickname='listAllVersions')
def get(self):
"""
@description: list all supported versions
@rtype: L{Versions}
"""
versions = [{'version': 'v1.0', 'description': 'basics'}]
self.finish_request({'versions': versions})
|