forked from LemonPi/benchtracker
/
server_db.py
executable file
·315 lines (270 loc) · 10.7 KB
/
server_db.py
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
#!/usr/bin/python
# web service, so return only JSON (no HTML)
from flask import Flask, jsonify, request, url_for, make_response, render_template, send_file
import sqlite3
import interface_db as d
import os.path
import urlparse
import argparse
import textwrap
import functools # need to wrap own decorators to comply with flask views
import zipfile
from io import BytesIO
from util import strip_last_word, sql_escape
try:
from flask.ext.cors import CORS # The typical way to import flask-cors
except ImportError:
# Path hack allows examples to be run without installation.
import os
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.sys.path.insert(0, parentdir)
from flask_cors import CORS
app = Flask(__name__)
app.debug=False
if not app.debug:
print("adding logger")
import logging
from logging import FileHandler
from logging import Formatter
data_dir = os.path.expanduser('~/benchtracker_data/')
if not os.path.isdir(data_dir):
os.makedirs(data_dir)
file_handler = FileHandler(os.path.join(data_dir, 'log.txt'))
file_handler.setFormatter(Formatter(
'%(asctime)s %(levelname)s: %(message)s '
'[in %(pathname)s:%(lineno)d'
))
file_handler.setLevel(logging.WARNING)
app.logger.addHandler(file_handler)
cors = CORS(app)
port = 5000
root_directory = None
# a set of valid names that the user is allowed to query for using db=
valid_databases = set()
# default database is the first database given
default_database = None
def parse_args(ns=None):
"""parse arguments from command line and return as namespace object"""
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description=textwrap.dedent("""\
serve a central database with benchmark information
Generated database:
Database should be created by populate_db.py, with each task
organized as a table. A task is a collection of related benchmarks
that are commonly run together."""),
usage="%(prog)s [OPTIONS]")
parser.add_argument("-d", "--databases",
nargs='+',
default=["results.db"],
help="names of databases in root directory to serve; users will\
only be allowed to query for these; The first specified will\
be the default; default: %(default)s")
parser.add_argument("-r", "--root_directory",
default="~/benchtracker_data/",
help="name of the directory to store databases in; if given,\
will allow users to query any database in the directory using\
the db query string parameter. default: %(default)s")
parser.add_argument("-p", "--port",
default=5000,
type=int,
help="port number to listen on; default: %(default)s")
params = parser.parse_args(namespace=ns)
global default_database, valid_databases, port, root_directory
root_directory = os.path.expanduser(params.root_directory)
# sanitize given databases to make sure they exist
for db in params.databases:
if os.path.isfile(os.path.join(root_directory, db)):
if not default_database:
default_database = db
valid_databases.add(db)
else:
print("WARNING: {} does not exist under {}".format(db, root_directory))
port = params.port
print("serving: ", [real_db(db) for db in valid_databases])
return params
def catch_operation_errors(func):
@functools.wraps(func)
def task_checker(*args, **kwargs):
try:
return func(*args, **kwargs)
except IOError as e:
return jsonify({'status': 'File does not exist! ({})'.format(e)})
except IndexError:
return jsonify({'status': 'Index out of bounds! (likely table index)'})
except sqlite3.OperationalError as e:
return jsonify({'status': 'Malformed request! ({})'.format(e)})
return task_checker
# each URI should be a noun since it is a resource (vs a verb for most library functions)
@app.route('/')
@app.route('/tasks', methods=['GET'])
@catch_operation_errors
def get_tasks():
database = parse_db()
return jsonify({'tasks':d.list_tasks(real_db(database)), 'database':database})
@app.route('/db', methods=['GET'])
def get_database():
return jsonify({'database':database})
@app.route('/param', methods=['GET'])
@catch_operation_errors
def get_param_desc():
database = parse_db()
tasks = parse_tasks()
param = request.args.get('p')
mode = request.args.get('m', 'range') # by default give ranges, overriden if param is text
try:
(param_type, param_val) = d.describe_param(param, mode, tasks, real_db(database))
except ValueError as e:
return jsonify({'status': 'Parameter value error: {}'.format(e)})
return jsonify({'status': 'OK',
'database':database,
'tasks':tasks,
'param': param,
'type': param_type,
'val': param_val})
@app.route('/params/', methods=['GET'])
@catch_operation_errors
def get_shared_params():
database = parse_db()
tasks = parse_tasks()
params = d.describe_tasks(tasks, real_db(database))
return jsonify({'status': 'OK', 'database':database, 'tasks':tasks, 'params': params})
@app.route('/data', methods=['GET'])
@catch_operation_errors
def get_filtered_data():
(exception, payload) = parse_data()
if exception:
return payload
else:
(database, tasks, params, data) = payload
return jsonify({'status': 'OK',
'database':database,
'tasks':tasks,
'params':params,
'data':data})
@app.route('/csv', methods=['GET'])
@catch_operation_errors
def get_csv_data():
"""Return a zipped archive of csv files for selected tasks"""
(exception, payload) = parse_data()
if exception:
return payload
else:
(database, tasks, params, data) = payload
memory_file = BytesIO()
with zipfile.ZipFile(memory_file, 'a', zipfile.ZIP_DEFLATED) as zf:
t = 0
for csvf in d.export_data_csv(params, data):
# characters the filesystem might complain about (/|) are replaced
zf.writestr("benchmark_results/" + tasks[t].replace('/','.').replace('|','__'), csvf.getvalue())
t += 1
# prepare to send over network
memory_file.seek(0)
return send_file(memory_file, attachment_filename="benchmark_results.zip", as_attachment=True)
@app.route('/view')
@catch_operation_errors
def get_view():
database = parse_db()
tasks = {task_name: task_context for (task_name, task_context) in [t.split('|',1) for t in d.list_tasks(real_db(database))]}
queried_tasks = parse_tasks()
x = y = filters = ""
# only pass other argument values if valid tasks selected
if queried_tasks:
x = request.args.get('x')
y = request.args.get('y')
(temp, filters) = parse_filters(verbose=True)
return render_template('viewer.html',
database=database,
tasks=tasks,
queried_tasks=queried_tasks,
queried_x = x,
queried_y = y,
filters = filters)
@app.errorhandler(404)
def not_found(error):
resp = jsonify({'error': 'Not found'})
resp.status_code = 404
return resp
# library call knows path to database, web viewer doesn't for security reasons
def real_db(relative_db):
return os.path.join(root_directory, relative_db)
# should always be run before all other querying since it determines where to look from
def parse_db():
db = request.args.get('db')
# sanitize against valid databases
if db:
if db in valid_databases:
return db
else:
raise IOError(db)
# default to the first database given if none given
return default_database
def parse_tasks():
database = parse_db()
tasks = request.args.getlist('t')
if tasks and tasks[0].isdigit():
all_tasks = d.list_tasks(database)
tasks = [all_tasks[int(t)] for t in tasks]
return tasks
def parse_filters(verbose=False):
"""
Parse filter from current request query string and return the filtered parameters and filters in a list
verbose mode returns filters without splitting out the type
"""
filter_param = None
filter_method = None
filters = []
filter_args = []
filter_params = []
for arg in urlparse.parse_qsl(request.query_string):
if arg[0][0] != 'f':
continue
# new filter parameter
if arg[0] == 'fp':
# previous filter ready to be built
if filter_param and filter_method and filter_args:
filters.append(d.Task_filter(filter_param, filter_method, filter_args))
filter_args = [] # clear arguments; important!
print("{}: {}".format(filters[-1], filters[-1].args))
filter_params.append(filter_param)
# split out the optional type following parameter name
if verbose:
filter_param = arg[1]
else:
filter_param = sql_escape(strip_last_word(arg[1]))
if arg[0] == 'fm':
filter_method = arg[1]
if arg[0] == 'fa':
filter_args.append(arg[1])
# last filter to be added
if (not filters or filter_param != filters[-1].param) and filter_args:
filters.append(d.Task_filter(filter_param, filter_method, filter_args))
print("{}: {}".format(filters[-1], filters[-1].args))
filter_params.append(filter_param)
return filter_params,filters
def parse_data():
"""
Parses request for data and returns a 2-tuple payload.
First item is True for an exception occurance, with the 2nd item being the json response for error.
Else false for no exception occruance, with second item being a 3-tuple.
"""
database = parse_db()
# split to get name only in case type is also given
x_param = request.args.get('x')
y_param = request.args.get('y')
if not x_param:
return (True, jsonify({'status': 'Missing x parameter!'}))
if not y_param:
return (True, jsonify({'status': 'Missing y parameter!'}))
try:
(filtered_params, filters) = parse_filters()
except IndexError:
return (True, jsonify({'status': 'Incomplete filter arguments!'}))
except ValueError:
return (True, jsonify({'status': 'Unsupported filter method!'}))
tasks = parse_tasks()
(params, data) = d.retrieve_data(x_param, y_param, filters, tasks, real_db(database))
return (False, (database, tasks, params, data))
if __name__ == '__main__':
parse_args()
app.run(host='0.0.0.0', port=port)