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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
|
##############################################################################
# Copyright (c) 2015 EMC and others.
#
# 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
##############################################################################
import json
import logging.config
import os
import sys
from flask import abort, Flask, request, jsonify
from flask_cors import CORS
from flask_restful import Resource, Api, fields
from flask_restful_swagger import swagger
from storperf.storperf_master import StorPerfMaster
class ReverseProxied(object):
'''Wrap the application in this middleware and configure the
front-end server to add these headers, to let you quietly bind
this to a URL other than / and to an HTTP scheme that is
different than what is used locally.
In nginx:
location /storperf/ {
proxy_pass http://localhost:8085/;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Scheme $scheme;
proxy_set_header X-Script-Name /storperf;
}
:param app: the WSGI application
'''
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
script_name = environ.get('HTTP_X_SCRIPT_NAME', '')
if script_name:
environ['SCRIPT_NAME'] = script_name
path_info = environ['PATH_INFO']
if path_info.startswith(script_name):
environ['PATH_INFO'] = path_info[len(script_name):]
scheme = environ.get('HTTP_X_SCHEME', '')
if scheme:
environ['wsgi.url_scheme'] = scheme
return self.app(environ, start_response)
app = Flask(__name__, static_url_path="")
CORS(app)
api = swagger.docs(Api(app), apiVersion='1.0')
app.wsgi_app = ReverseProxied(app.wsgi_app)
storperf = StorPerfMaster()
class Logs(Resource):
def __init__(self):
self.logger = logging.getLogger(__name__)
@swagger.operation(
notes="Fetch logs",
parameters=[
{
"name": "lines",
"description": "The number of lines to fetch",
"required": "False",
"type": "string",
"allowedMultiple": "False",
"paramType": "query"
}
]
)
def get(self):
lines = request.args.get('lines')
if lines:
try:
lines = int(lines)
except Exception:
pass
else:
lines = 35
return jsonify({'logs': storperf.get_logs(lines)})
@swagger.model
class ConfigurationRequestModel:
resource_fields = {
'agent_count': fields.Integer,
'agent_flavor': fields.String,
'agent_image': fields.String,
'public_network': fields.String,
'volume_size': fields.Integer,
'availability_zone': fields.String,
'username': fields.String,
'password': fields.String
}
@swagger.model
class ConfigurationResponseModel:
resource_fields = {
'agent_count': fields.Integer,
'agent_flavor': fields.String,
'agent_image': fields.String,
'public_network': fields.String,
'stack_created': fields.Boolean,
'stack_id': fields.String,
'volume_size': fields.Integer,
'availability_zone': fields.String
}
class Configure(Resource):
"""Configuration API"""
def __init__(self):
self.logger = logging.getLogger(__name__)
@swagger.operation(
notes='Fetch the current agent configuration',
type=ConfigurationResponseModel.__name__
)
def get(self):
return jsonify({'agent_count': storperf.agent_count,
'agent_flavor': storperf.agent_flavor,
'agent_image': storperf.agent_image,
'public_network': storperf.public_network,
'volume_size': storperf.volume_size,
'stack_created': storperf.is_stack_created,
'availability_zone': storperf.availability_zone,
'stack_id': storperf.stack_id})
@swagger.operation(
notes='''Set the current agent configuration and create a stack in
the controller. Returns once the stack create is completed.''',
parameters=[
{
"name": "configuration",
"description": '''Configuration to be set. All parameters are
optional, and will retain their previous value if not
specified. Volume size is in GB.
''',
"required": True,
"type": "ConfigurationRequestModel",
"paramType": "body"
}
],
type=ConfigurationResponseModel.__name__
)
def post(self):
if not request.json:
abort(400, "ERROR: No data specified")
try:
if ('agent_count' in request.json):
storperf.agent_count = request.json['agent_count']
if ('agent_flavor' in request.json):
storperf.agent_flavor = request.json['agent_flavor']
if ('agent_image' in request.json):
storperf.agent_image = request.json['agent_image']
if ('public_network' in request.json):
storperf.public_network = request.json['public_network']
if ('volume_size' in request.json):
storperf.volume_size = request.json['volume_size']
if ('availability_zone' in request.json):
storperf.availability_zone = request.json['availability_zone']
if ('username' in request.json):
storperf.username = request.json['username']
if ('password' in request.json):
storperf.password = request.json['password']
storperf.create_stack()
if storperf.stack_id is None:
abort(400, storperf.status_reason)
return jsonify({'agent_count': storperf.agent_count,
'agent_flavor': storperf.agent_flavor,
'agent_image': storperf.agent_image,
'availability_zone': storperf.availability_zone,
'public_network': storperf.public_network,
'volume_size': storperf.volume_size,
'stack_id': storperf.stack_id})
except Exception as e:
self.logger.exception(e)
abort(400, str(e))
@swagger.operation(
notes='Deletes the agent configuration and the stack'
)
def delete(self):
try:
return jsonify({'stack_id': storperf.delete_stack()})
except Exception as e:
self.logger.exception(e)
abort(400, str(e))
@swagger.model
class WorkloadModel:
resource_fields = {
'target': fields.String,
'deadline': fields.Integer,
"steady_state_samples": fields.Integer,
'workload': fields.String,
'queue_depths': fields.String,
'block_sizes': fields.String
}
@swagger.model
class WorkloadResponseModel:
resource_fields = {
'job_id': fields.String
}
class Job(Resource):
"""Job API"""
def __init__(self):
self.logger = logging.getLogger(__name__)
@swagger.operation(
notes='Fetch the metrics of the specified workload',
parameters=[
{
"name": "id",
"description": "The UUID of the workload in the format "
"NNNNNNNN-NNNN-NNNN-NNNN-NNNNNNNNNNNN",
"required": False,
"type": "string",
"allowMultiple": False,
"paramType": "query"
},
{
"name": "type",
"description": "The type of metrics to report. May be "
"metrics (default), metadata, or status",
"required": False,
"type": "string",
"allowMultiple": False,
"paramType": "query"
}
],
responseMessages=[
{
"code": 200,
"message": "Workload ID found, response in JSON format"
},
{
"code": 404,
"message": "Workload ID not found"
}
]
)
def get(self):
workload_id = request.args.get('id')
if workload_id:
metrics_type = "metrics"
if request.args.get('type'):
metrics_type = request.args.get('type')
if metrics_type == "metrics":
return jsonify(storperf.fetch_results(workload_id))
if metrics_type == "metadata":
return jsonify(storperf.fetch_metadata(workload_id))
if metrics_type == "status":
return jsonify(storperf.fetch_job_status(workload_id))
else:
metrics_type = None
if request.args.get('type'):
metrics_type = request.args.get('type')
if metrics_type == "status":
return jsonify(storperf.fetch_job_status(workload_id))
else:
return jsonify(storperf.fetch_all_jobs(metrics_type))
@swagger.operation(
parameters=[
{
"name": "body",
"description": """Start execution of a workload with the
following parameters:
"target": The target device to profile",
"deadline": if specified, the maximum duration in minutes
for any single test iteration.
"workload":if specified, the workload to run. Defaults to all.
""",
"required": True,
"type": "WorkloadModel",
"paramType": "body"
}
],
type=WorkloadResponseModel.__name__,
responseMessages=[
{
"code": 200,
"message": "Job submitted"
},
{
"code": 400,
"message": "Missing configuration data"
}
]
)
def post(self):
if not request.json:
abort(400, "ERROR: Missing configuration data")
self.logger.info(request.json)
try:
if ('target' in request.json):
storperf.filename = request.json['target']
if ('deadline' in request.json):
storperf.deadline = request.json['deadline']
if ('steady_state_samples' in request.json):
storperf.steady_state_samples = request.json[
'steady_state_samples']
if ('queue_depths' in request.json):
storperf.queue_depths = request.json['queue_depths']
if ('block_sizes' in request.json):
storperf.block_sizes = request.json['block_sizes']
if ('workload' in request.json):
storperf.workloads = request.json['workload']
else:
storperf.workloads = None
if ('metadata' in request.json):
metadata = request.json['metadata']
else:
metadata = {}
job_id = storperf.execute_workloads(metadata)
return jsonify({'job_id': job_id})
except Exception as e:
self.logger.exception(e)
abort(400, str(e))
@swagger.operation(
notes='Cancels the currently running workload',
responseMessages=[
{
"code": 200,
"message": "Wordload ID found, response in JSON format"
},
]
)
def delete(self):
self.logger.info("Threads: %s" % sys._current_frames())
print sys._current_frames()
try:
return jsonify({'Slaves': storperf.terminate_workloads()})
except Exception as e:
abort(400, str(e))
@swagger.model
class QuotaModel:
resource_fields = {
'quota': fields.Integer
}
class Quota(Resource):
"""Quota API"""
@swagger.operation(
notes='''Fetch the current Cinder volume quota. This value limits
the number of volumes that can be created, and by extension, defines
the maximum number of agents that can be created for any given test
scenario''',
type=QuotaModel.__name__
)
def get(self):
quota = storperf.volume_quota
return jsonify({'quota': quota})
def setup_logging(default_path='logging.json',
default_level=logging.INFO, env_key='LOG_CFG'):
"""Setup logging configuration
"""
path = default_path
value = os.getenv(env_key, None)
if value:
path = value
if os.path.exists(path):
with open(path, 'rt') as f:
config = json.load(f)
logging.config.dictConfig(config)
else:
logging.basicConfig(level=default_level)
socketHandler = logging.handlers.DatagramHandler(
'localhost', logging.handlers.DEFAULT_UDP_LOGGING_PORT)
rootLogger = logging.getLogger('')
rootLogger.addHandler(socketHandler)
api.add_resource(Configure, "/api/v1.0/configurations")
api.add_resource(Quota, "/api/v1.0/quotas")
api.add_resource(Job, "/api/v1.0/jobs")
api.add_resource(Logs, "/api/v1.0/logs")
if __name__ == "__main__":
setup_logging()
logging.getLogger("storperf").setLevel(logging.DEBUG)
app.run(host='0.0.0.0', debug=True, threaded=True)
|