2 __author__ = "Jan Medved"
3 __copyright__ = "Copyright(c) 2014, Cisco Systems, Inc."
4 __license__ = "New-style BSD"
5 __email__ = "jmedved@cisco.com"
7 from random import randrange
19 class Counter(object):
20 def __init__(self, start=0):
21 self.lock = threading.Lock()
24 def increment(self, value=1):
35 def __init__(self, verbose=False):
36 self.verbose = verbose
39 self.start = time.time()
42 def __exit__(self, *args):
43 self.end = time.time()
44 self.secs = self.end - self.start
45 self.msecs = self.secs * 1000 # millisecs
47 print ("elapsed time: %f ms" % self.msecs)
50 class FlowConfigBlaster(object):
51 putheaders = {'content-type': 'application/json'}
52 getheaders = {'Accept': 'application/json'}
54 FLWURL = "restconf/config/opendaylight-inventory:nodes/node/openflow:%d/table/0/flow/%d"
55 TBLURL = "restconf/config/opendaylight-inventory:nodes/node/openflow:%d/table/0"
56 INVURL = 'restconf/operational/opendaylight-inventory:nodes'
61 # The "built-in" flow template
62 flow_mode_template = {
65 u'hard-timeout': 65000,
66 u'idle-timeout': 65000,
67 u'cookie_mask': 4294967295,
68 u'flow-name': u'FLOW-NAME-TEMPLATE',
74 u'id': u'FLOW-ID-TEMPLATE',
76 u'ipv4-destination': u'0.0.0.0/32',
102 class FcbStats(object):
104 FlowConfigBlaster Statistics: a class that stores and further processes
105 statistics collected by Blaster worker threads during their execution.
108 self.ok_rqst_rate = Counter(0.0)
109 self.total_rqst_rate = Counter(0.0)
110 self.ok_flow_rate = Counter(0.0)
111 self.total_flow_rate = Counter(0.0)
112 self.ok_rqsts = Counter(0)
113 self.total_rqsts = Counter(0)
114 self.ok_flows = Counter(0)
115 self.total_flows = Counter(0)
117 def process_stats(self, rqst_stats, flow_stats, elapsed_time):
119 Calculates the stats for RESTCONF request and flow programming
120 throughput, and aggregates statistics across all Blaster threads.
122 ok_rqsts = rqst_stats[200] + rqst_stats[204]
123 total_rqsts = sum(rqst_stats.values())
124 ok_flows = flow_stats[200] + flow_stats[204]
125 total_flows = sum(flow_stats.values())
127 ok_rqst_rate = ok_rqsts / elapsed_time
128 total_rqst_rate = total_rqsts / elapsed_time
129 ok_flow_rate = ok_flows / elapsed_time
130 total_flow_rate = total_flows / elapsed_time
132 self.ok_rqsts.increment(ok_rqsts)
133 self.total_rqsts.increment(total_rqsts)
134 self.ok_flows.increment(ok_flows)
135 self.total_flows.increment(total_flows)
137 self.ok_rqst_rate.increment(ok_rqst_rate)
138 self.total_rqst_rate.increment(total_rqst_rate)
139 self.ok_flow_rate.increment(ok_flow_rate)
140 self.total_flow_rate.increment(total_flow_rate)
142 return ok_rqst_rate, total_rqst_rate, ok_flow_rate, total_flow_rate
144 def get_ok_rqst_rate(self):
145 return self.ok_rqst_rate.value
147 def get_total_rqst_rate(self):
148 return self.total_rqst_rate.value
150 def get_ok_flow_rate(self):
151 return self.ok_flow_rate.value
153 def get_total_flow_rate(self):
154 return self.total_flow_rate.value
156 def get_ok_rqsts(self):
157 return self.ok_rqsts.value
159 def get_total_rqsts(self):
160 return self.total_rqsts.value
162 def get_ok_flows(self):
163 return self.ok_flows.value
165 def get_total_flows(self):
166 return self.total_flows.value
168 def __init__(self, host, port, ncycles, nthreads, fpr, nnodes, nflows, startflow, auth, flow_mod_template=None):
171 self.ncycles = ncycles
172 self.nthreads = nthreads
176 self.startflow = startflow
179 if flow_mod_template:
180 self.flow_mode_template = flow_mod_template
182 self.post_url_template = 'http://%s:' + self.port + '/' + self.TBLURL
183 self.del_url_template = 'http://%s:' + self.port + '/' + self.FLWURL
185 self.stats = self.FcbStats()
186 self.total_ok_flows = 0
187 self.total_ok_rqsts = 0
189 self.ip_addr = Counter(int(netaddr.IPAddress('10.0.0.1')) + startflow)
191 self.print_lock = threading.Lock()
192 self.cond = threading.Condition()
193 self.threads_done = 0
195 for i in range(self.nthreads):
198 def get_num_nodes(self, session):
200 Determines the number of OF nodes in the connected mininet network. If
201 mininet is not connected, the default number of flows is set to 16.
202 :param session: 'requests' session which to use to query the controller
206 hosts = self.host.split(",")
208 inventory_url = 'http://' + host + ":" + self.port + '/' + self.INVURL
212 r = session.get(inventory_url, headers=self.getheaders, stream=False, timeout=self.TIMEOUT)
214 r = session.get(inventory_url, headers=self.getheaders, stream=False, auth=('admin', 'admin'),
215 timeout=self.TIMEOUT)
217 if r.status_code == 200:
219 inv = json.loads(r.content)['nodes']['node']
221 for n in range(len(inv)):
222 if re.search('openflow', inv[n]['id']) is not None:
231 def create_flow_from_template(self, flow_id, ipaddr, node_id):
233 Create a new flow instance from the flow template specified during
234 FlowConfigBlaster instantiation. Flow templates are json-compatible
235 dictionaries that MUST contain elements for flow cookie, flow name,
236 flow id and the destination IPv4 address in the flow match field.
237 :param flow_id: Id for the new flow to create
238 :param ipaddr: IP Address to put into the flow's match
239 :return: The newly created flow instance
241 flow = copy.deepcopy(self.flow_mode_template['flow'][0])
242 flow['cookie'] = flow_id
243 flow['flow-name'] = 'TestFlow-%d' % flow_id
244 flow['id'] = str(flow_id)
245 flow['match']['ipv4-destination'] = '%s/32' % str(netaddr.IPAddress(ipaddr))
248 def post_flows(self, session, node, flow_list, flow_count):
250 Performs a RESTCONF post of flows passed in the 'flow_list' parameters
251 :param session: 'requests' session on which to perform the POST
252 :param node: The ID of the openflow node to which to post the flows
253 :param flow_list: List of flows (in dictionary form) to POST
254 :return: status code from the POST operation
256 flow_data = self.convert_to_json(flow_list, node)
258 hosts = self.host.split(",")
259 host = hosts[flow_count % len(hosts)]
260 flow_url = self.assemble_post_url(host, node)
264 r = session.post(flow_url, data=flow_data, headers=self.putheaders, stream=False, timeout=self.TIMEOUT)
266 r = session.post(flow_url, data=flow_data, headers=self.putheaders, stream=False, auth=('admin', 'admin'),
267 timeout=self.TIMEOUT)
271 def assemble_post_url(self, host, node):
273 Creates url pointing to config dataStore: /nodes/node/<node-id>/table/<table-id>
274 :param host: ip address or host name pointing to controller
275 :param node: id of node (without protocol prefix and colon)
276 :return: url suitable for sending a flow to controller via POST method
278 return self.post_url_template % (host, node)
280 def convert_to_json(self, flow_list, node_id=None):
282 Dumps flows to json form.
283 :param flow_list: list of flows in json friendly structure
284 :param node_id: node identifier of corresponding node
285 :return: string containing plain json
287 fmod = dict(self.flow_mode_template)
288 fmod['flow'] = flow_list
289 flow_data = json.dumps(fmod)
293 def add_flows(self, start_flow_id, tid):
295 Adds flows into the ODL config data store. This function is executed by
296 a worker thread (the Blaster thread). The number of flows created and
297 the batch size (i.e. how many flows will be put into a RESTCONF request)
298 are determined by control parameters initialized when FlowConfigBlaster
300 :param start_flow_id - the ID of the first flow. Each Blaster thread
301 programs a different set of flows
302 :param tid: Thread ID - used to id the Blaster thread when statistics
303 for the thread are printed out
306 rqst_stats = {200: 0, 204: 0}
307 flow_stats = {200: 0, 204: 0}
309 s = requests.Session()
311 n_nodes = self.get_num_nodes(s)
313 with self.print_lock:
314 print ' Thread %d:\n Adding %d flows on %d nodes' % (tid, self.nflows, n_nodes)
318 while nflows < self.nflows:
319 node_id = randrange(1, n_nodes + 1)
321 for i in range(self.fpr):
322 flow_id = tid * (self.ncycles * self.nflows) + nflows + start_flow_id + self.startflow
323 self.flows[tid][flow_id] = node_id
324 flow_list.append(self.create_flow_from_template(flow_id, self.ip_addr.increment(), node_id))
326 if nflows >= self.nflows:
328 sts = self.post_flows(s, node_id, flow_list, nflows)
331 flow_stats[sts] += len(flow_list)
334 flow_stats[sts] = len(flow_list)
336 ok_rps, total_rps, ok_fps, total_fps = self.stats.process_stats(rqst_stats, flow_stats, t.secs)
338 with self.print_lock:
339 print '\n Thread %d results (ADD): ' % tid
340 print ' Elapsed time: %.2fs,' % t.secs
341 print ' Requests/s: %.2f OK, %.2f Total' % (ok_rps, total_rps)
342 print ' Flows/s: %.2f OK, %.2f Total' % (ok_fps, total_fps)
343 print ' Stats ({Requests}, {Flows}): ',
346 self.threads_done += 1
351 self.cond.notifyAll()
353 def delete_flow(self, session, node, flow_id, flow_count):
355 Deletes a single flow from the ODL config data store using RESTCONF
356 :param session: 'requests' session on which to perform the POST
357 :param node: Id of the openflow node from which to delete the flow
358 :param flow_id: ID of the to-be-deleted flow
359 :return: status code from the DELETE operation
362 hosts = self.host.split(",")
363 host = hosts[flow_count % len(hosts)]
364 flow_url = self.del_url_template % (host, node, flow_id)
368 r = session.delete(flow_url, headers=self.getheaders, timeout=self.TIMEOUT)
370 r = session.delete(flow_url, headers=self.getheaders, auth=('admin', 'admin'), timeout=self.TIMEOUT)
374 def delete_flows(self, start_flow, tid):
376 Deletes flow from the ODL config space that have been added using the
377 'add_flows()' function. This function is executed by a worker thread
378 :param start_flow - the ID of the first flow. Each Blaster thread
379 deletes a different set of flows
380 :param tid: Thread ID - used to id the Blaster thread when statistics
381 for the thread are printed out
385 rqst_stats = {200: 0, 204: 0}
387 s = requests.Session()
388 n_nodes = self.get_num_nodes(s)
390 with self.print_lock:
391 print 'Thread %d: Deleting %d flows on %d nodes' % (tid, self.nflows, n_nodes)
394 for flow in range(self.nflows):
395 flow_id = tid * (self.ncycles * self.nflows) + flow + start_flow + self.startflow
396 sts = self.delete_flow(s, self.flows[tid][flow_id], flow_id, flow)
402 ok_rps, total_rps, ok_fps, total_fps = self.stats.process_stats(rqst_stats, rqst_stats, t.secs)
404 with self.print_lock:
405 print '\n Thread %d results (DELETE): ' % tid
406 print ' Elapsed time: %.2fs,' % t.secs
407 print ' Requests/s: %.2f OK, %.2f Total' % (ok_rps, total_rps)
408 print ' Flows/s: %.2f OK, %.2f Total' % (ok_fps, total_fps)
409 print ' Stats ({Requests})',
411 self.threads_done += 1
416 self.cond.notifyAll()
418 def run_cycle(self, function):
420 Runs a flow-add or flow-delete test cycle. Each test consists of a
421 <cycles> test cycles, where <threads> worker (Blaster) threads are
422 started in each test cycle. Each Blaster thread programs <flows>
423 OpenFlow flows into the controller using the controller's RESTCONF API.
424 :param function: Add or delete, determines what test will be executed.
427 self.total_ok_flows = 0
428 self.total_ok_rqsts = 0
430 for c in range(self.ncycles):
431 self.stats = self.FcbStats()
432 with self.print_lock:
433 print '\nCycle %d:' % c
436 for i in range(self.nthreads):
437 t = threading.Thread(target=function, args=(c * self.nflows, i))
441 # Wait for all threads to finish and measure the execution time
443 for thread in threads:
446 with self.print_lock:
447 print '\n*** Test summary:'
448 print ' Elapsed time: %.2fs' % t.secs
449 print ' Peak requests/s: %.2f OK, %.2f Total' % (
450 self.stats.get_ok_rqst_rate(), self.stats.get_total_rqst_rate())
451 print ' Peak flows/s: %.2f OK, %.2f Total' % (
452 self.stats.get_ok_flow_rate(), self.stats.get_total_flow_rate())
453 print ' Avg. requests/s: %.2f OK, %.2f Total (%.2f%% of peak total)' % (
454 self.stats.get_ok_rqsts() / t.secs,
455 self.stats.get_total_rqsts() / t.secs,
456 (self.stats.get_total_rqsts() / t.secs * 100) / self.stats.get_total_rqst_rate())
457 print ' Avg. flows/s: %.2f OK, %.2f Total (%.2f%% of peak total)' % (
458 self.stats.get_ok_flows() / t.secs,
459 self.stats.get_total_flows() / t.secs,
460 (self.stats.get_total_flows() / t.secs * 100) / self.stats.get_total_flow_rate())
462 self.total_ok_flows += self.stats.get_ok_flows()
463 self.total_ok_rqsts += self.stats.get_ok_rqsts()
464 self.threads_done = 0
466 def add_blaster(self):
467 self.run_cycle(self.add_flows)
469 def delete_blaster(self):
470 self.run_cycle(self.delete_flows)
472 def get_ok_flows(self):
473 return self.total_ok_flows
475 def get_ok_rqsts(self):
476 return self.total_ok_rqsts
479 def get_json_from_file(filename):
481 Get a flow programming template from a file
482 :param filename: File from which to get the template
483 :return: The json flow template (string)
485 with open(filename, 'r') as f:
488 keys = ft['flow'][0].keys()
489 if (u'cookie' in keys) and (u'flow-name' in keys) and (u'id' in keys) and (u'match' in keys):
490 if u'ipv4-destination' in ft[u'flow'][0]['match'].keys():
491 print 'File "%s" ok to use as flow template' % filename
494 print 'JSON parsing of file %s failed' % filename
499 ###############################################################################
500 # This is an example of what the content of a JSON flow mode template should
501 # look like. Cut & paste to create a custom template. "id" and "ipv4-destination"
502 # MUST be unique if multiple flows will be programmed in the same test. It's
503 # also beneficial to have unique "cookie" and "flow-name" attributes for easier
504 # identification of the flow.
505 ###############################################################################
506 example_flow_mod_json = '''{
526 "hard-timeout": 65000,
533 "ipv4-destination": "10.0.0.38/32"
535 "flow-name": "TestFlow-8",
537 "cookie_mask": 4294967295,
540 "idle-timeout": 65000,
548 def create_arguments_parser():
550 Shorthand to arg parser on library level in order to access and eventually enhance in ancestors.
551 :return: argument parser supporting config blaster arguments and parameters
553 my_parser = argparse.ArgumentParser(description='Flow programming performance test: First adds and then'
554 ' deletes flows into the config tree, as specified by'
555 ' optional parameters.')
557 my_parser.add_argument('--host', default='127.0.0.1',
558 help='Host where odl controller is running (default is 127.0.0.1). '
559 'Specify a comma-separated list of hosts to perform round-robin load-balancing.')
560 my_parser.add_argument('--port', default='8181',
561 help='Port on which odl\'s RESTCONF is listening (default is 8181)')
562 my_parser.add_argument('--cycles', type=int, default=1,
563 help='Number of flow add/delete cycles; default 1. Both Flow Adds and Flow Deletes are '
564 'performed in cycles. <THREADS> worker threads are started in each cycle and the cycle '
565 'ends when all threads finish. Another cycle is started when the previous cycle '
567 my_parser.add_argument('--threads', type=int, default=1,
568 help='Number of request worker threads to start in each cycle; default=1. '
569 'Each thread will add/delete <FLOWS> flows.')
570 my_parser.add_argument('--flows', type=int, default=10,
571 help='Number of flows that will be added/deleted by each worker thread in each cycle; '
573 my_parser.add_argument('--fpr', type=int, default=1,
574 help='Flows-per-Request - number of flows (batch size) sent in each HTTP request; '
576 my_parser.add_argument('--nodes', type=int, default=16,
577 help='Number of nodes if mininet is not connected; default=16. If mininet is connected, '
578 'flows will be evenly distributed (programmed) into connected nodes.')
579 my_parser.add_argument('--delay', type=int, default=0,
580 help='Time (in seconds) to wait between the add and delete cycles; default=0')
581 my_parser.add_argument('--delete', dest='delete', action='store_true', default=True,
582 help='Delete all added flows one by one, benchmark delete '
584 my_parser.add_argument('--no-delete', dest='delete', action='store_false',
585 help='Do not perform the delete cycle.')
586 my_parser.add_argument('--auth', dest='auth', action='store_true', default=False,
587 help="Use the ODL default username/password 'admin'/'admin' to authenticate access to REST; "
588 'default: no authentication')
589 my_parser.add_argument('--startflow', type=int, default=0,
590 help='The starting Flow ID; default=0')
591 my_parser.add_argument('--file', default='',
592 help='File from which to read the JSON flow template; default: no file, use a built in '
597 if __name__ == "__main__":
598 ############################################################################
599 # This program executes the base performance test. The test adds flows into
600 # the controller's config space. This function is basically the CLI frontend
601 # to the FlowConfigBlaster class and drives its main functions: adding and
602 # deleting flows from the controller's config data store
603 ############################################################################
605 parser = create_arguments_parser()
606 in_args = parser.parse_args()
608 if in_args.file != '':
609 flow_template = get_json_from_file(in_args.file)
613 fct = FlowConfigBlaster(in_args.host, in_args.port, in_args.cycles, in_args.threads, in_args.fpr, in_args.nodes,
614 in_args.flows, in_args.startflow, in_args.auth)
616 # Run through <cycles>, where <threads> are started in each cycle and
617 # <flows> are added from each thread
620 print '\n*** Total flows added: %s' % fct.get_ok_flows()
621 print ' HTTP[OK] results: %d\n' % fct.get_ok_rqsts()
623 if in_args.delay > 0:
624 print '*** Waiting for %d seconds before the delete cycle ***\n' % in_args.delay
625 time.sleep(in_args.delay)
627 # Run through <cycles>, where <threads> are started in each cycle and
628 # <flows> previously added in an add cycle are deleted in each thread
631 print '\n*** Total flows deleted: %s' % fct.get_ok_flows()
632 print ' HTTP[OK] results: %d\n' % fct.get_ok_rqsts()