2 # Copyright 2017 Cisco Systems, Inc. All rights reserved.
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
17 from flask import Flask
18 from flask import jsonify
19 from flask import render_template
20 from flask import request
22 from flask_socketio import emit
23 from flask_socketio import SocketIO
24 from fluentd import FluentLogHandler
25 from summarizer import NFVBenchSummarizer
31 from utils import byteify
32 from utils import RunLock
35 # this global cannot reside in Ctx because of the @app and @socketio decorators
40 STATUS_ERROR = 'ERROR'
41 STATUS_PENDING = 'PENDING'
42 STATUS_NOT_FOUND = 'NOT_FOUND'
45 def result_json(status, message, request_id=None):
48 'error_message': message
51 if request_id is not None:
52 body['request_id'] = request_id
58 return json.loads(json.dumps(data), object_hook=byteify)
62 return uuid.uuid4().hex
67 run_queue = Queue.Queue()
70 request_from_socketio = False
76 def enqueue(config, request_id, from_socketio=False):
78 Ctx.request_from_socketio = from_socketio
79 config['request_id'] = request_id
80 Ctx.run_queue.put(config)
82 if len(Ctx.ids) >= Ctx.MAXLEN:
84 del Ctx.results[Ctx.ids.pop(0)]
87 Ctx.ids.append(request_id)
91 config = Ctx.run_queue.get()
92 Ctx.current_id = config['request_id']
102 res['request_id'] = Ctx.current_id
103 Ctx.results[Ctx.current_id] = res
107 def get_result(request_id=None):
110 res = Ctx.results[request_id]
114 if Ctx.result and request_id == Ctx.result['request_id']:
129 def get_current_request_id():
130 return Ctx.current_id
133 def setup_flask(root_path):
136 app = Flask(__name__)
137 app.root_path = root_path
138 socketio = SocketIO(app, async_mode='threading')
139 busy_json = result_json(STATUS_ERROR, 'there is already an NFVbench request running')
140 config_is_null_json = result_json(STATUS_ERROR, 'configuration is missing')
141 not_busy_json = result_json(STATUS_ERROR, 'no pending NFVbench run')
142 not_found_msg = 'results not found'
143 pending_msg = 'NFVbench run still pending'
145 # --------- socketio requests ------------
147 @socketio.on('start_run')
148 def socketio_start_run(config):
149 if not Ctx.is_busy():
150 Ctx.enqueue(config, get_uuid(), from_socketio=True)
152 emit('error', {'reason': 'there is already an NFVbench request running'})
155 def socketio_echo(config):
158 # --------- HTTP requests ------------
162 return render_template('index.html')
164 @app.route('/echo', methods=['GET'])
166 config = request.json
167 return jsonify(config)
169 @app.route('/start_run', methods=['POST'])
171 config = load_json(request.json)
174 return jsonify(busy_json)
176 request_id = get_uuid()
177 Ctx.enqueue(config, request_id)
178 return jsonify(result_json(STATUS_PENDING, pending_msg, request_id))
180 return jsonify(config_is_null_json)
182 @app.route('/status', defaults={'request_id': None}, methods=['GET'])
183 @app.route('/status/<request_id>', methods=['GET'])
184 def get_status(request_id):
186 if Ctx.is_busy() and request_id == Ctx.get_current_request_id():
187 # task with request_id still pending
188 return jsonify(result_json(STATUS_PENDING, pending_msg, request_id))
190 res = Ctx.get_result(request_id)
192 # found result for given request_id
195 # result for given request_id not found
196 return jsonify(result_json(STATUS_NOT_FOUND, not_found_msg, request_id))
199 # task still pending, return with request_id
200 return jsonify(result_json(STATUS_PENDING,
202 Ctx.get_current_request_id()))
204 res = Ctx.get_result()
208 return jsonify(not_busy_json)
211 class WebSocketIoServer(object):
212 """This class takes care of the web socketio server, accepts websocket events, and sends back
213 notifications using websocket events (send_ methods). Caller should simply create an instance
214 of this class and pass a runner object then invoke the run method
217 def __init__(self, http_root, runner, logger):
218 self.nfvbench_runner = runner
219 setup_flask(http_root)
220 self.fluent_logger = logger
221 self.result_fluent_logger = FluentLogHandler("resultnfvbench",
222 fluentd_ip=self.fluent_logger.sender.host,
223 fluentd_port=self.fluent_logger.sender.port) \
224 if self.fluent_logger else None
226 def run(self, host='127.0.0.1', port=7556):
228 # socketio.run will not return so we need to run it in a background thread so that
229 # the calling thread (main thread) can keep doing work
230 socketio.start_background_task(target=socketio.run, app=app, host=host, port=port)
232 # wait for run requests
233 # the runner must be executed from the main thread (Trex client library requirement)
236 # print 'main thread waiting for requests...'
237 config = Ctx.dequeue()
238 # print 'main thread processing request...'
241 # remove unfilled values as we do not want them to override default values with None
242 config = {k: v for k, v in config.items() if v is not None}
244 results = self.nfvbench_runner.run(config, config)
245 except Exception as exc:
246 print 'NFVbench runner exception:'
247 traceback.print_exc()
248 results = result_json(STATUS_ERROR, str(exc))
251 if Ctx.request_from_socketio:
252 socketio.emit('run_end', results)
254 # this might overwrite a previously unfetched result
255 Ctx.set_result(results)
256 summary = NFVBenchSummarizer(results['result'], self.result_fluent_logger)
257 LOG.info(str(summary))
259 if self.fluent_logger:
260 self.fluent_logger.send_run_summary(True)
262 def send_interval_stats(self, time_ms, tx_pps, rx_pps, drop_pct):
263 stats = {'time_ms': time_ms, 'tx_pps': tx_pps, 'rx_pps': rx_pps, 'drop_pct': drop_pct}
264 socketio.emit('run_interval_stats', stats)
266 def send_ndr_found(self, ndr_pps):
267 socketio.emit('ndr_found', {'rate_pps': ndr_pps})
269 def send_pdr_found(self, pdr_pps):
270 socketio.emit('pdr_found', {'rate_pps': pdr_pps})