Fixed flow_config_blaster Floodlight edition
[integration/test.git] / tools / odl-mdsal-clustering-tests / clustering-performance-test / flow_config_blaster.py
1 #!/usr/bin/python
2
3 from random import randrange
4 import json
5 import argparse
6 import time
7 import threading
8 import re
9 import copy
10
11 import requests
12 import netaddr
13
14
15 __author__ = "Jan Medved"
16 __copyright__ = "Copyright(c) 2014, Cisco Systems, Inc."
17 __license__ = "New-style BSD"
18 __email__ = "jmedved@cisco.com"
19
20
21 class Counter(object):
22     def __init__(self, start=0):
23         self.lock = threading.Lock()
24         self.value = start
25
26     def increment(self, value=1):
27         self.lock.acquire()
28         val = self.value
29         try:
30             self.value += value
31         finally:
32             self.lock.release()
33         return val
34
35
36 class Timer(object):
37     def __init__(self, verbose=False):
38         self.verbose = verbose
39
40     def __enter__(self):
41         self.start = time.time()
42         return self
43
44     def __exit__(self, *args):
45         self.end = time.time()
46         self.secs = self.end - self.start
47         self.msecs = self.secs * 1000  # millisecs
48         if self.verbose:
49             print ("elapsed time: %f ms" % self.msecs)
50
51
52 class FlowConfigBlaster(object):
53     putheaders = {'content-type': 'application/json'}
54     getheaders = {'Accept': 'application/json'}
55
56     FLWURL = "restconf/config/opendaylight-inventory:nodes/node/openflow:%d/table/0/flow/%d"
57     TBLURL = "restconf/config/opendaylight-inventory:nodes/node/openflow:%d/table/0"
58     INVURL = 'restconf/operational/opendaylight-inventory:nodes'
59     TIMEOUT = 10
60
61     flows = {}
62
63     # The "built-in" flow template
64     flow_mode_template = {
65         u'flow': [
66             {
67                 u'hard-timeout': 65000,
68                 u'idle-timeout': 65000,
69                 u'cookie_mask': 4294967295,
70                 u'flow-name': u'FLOW-NAME-TEMPLATE',
71                 u'priority': 2,
72                 u'strict': False,
73                 u'cookie': 0,
74                 u'table_id': 0,
75                 u'installHw': False,
76                 u'id': u'FLOW-ID-TEMPLATE',
77                 u'match': {
78                     u'ipv4-destination': u'0.0.0.0/32',
79                     u'ethernet-match': {
80                         u'ethernet-type': {
81                             u'type': 2048
82                         }
83                     }
84                 },
85                 u'instructions': {
86                     u'instruction': [
87                         {
88                             u'order': 0,
89                             u'apply-actions': {
90                                 u'action': [
91                                     {
92                                         u'drop-action': {},
93                                         u'order': 0
94                                     }
95                                 ]
96                             }
97                         }
98                     ]
99                 }
100             }
101         ]
102     }
103
104     class FcbStats(object):
105         """
106         FlowConfigBlaster Statistics: a class that stores and further processes
107         statistics collected by Blaster worker threads during their execution.
108         """
109         def __init__(self):
110             self.ok_rqst_rate = Counter(0.0)
111             self.total_rqst_rate = Counter(0.0)
112             self.ok_flow_rate = Counter(0.0)
113             self.total_flow_rate = Counter(0.0)
114             self.ok_rqsts = Counter(0)
115             self.total_rqsts = Counter(0)
116             self.ok_flows = Counter(0)
117             self.total_flows = Counter(0)
118
119         def process_stats(self, rqst_stats, flow_stats, elapsed_time):
120             """
121             Calculates the stats for RESTCONF request and flow programming
122             throughput, and aggregates statistics across all Blaster threads.
123
124             Args:
125                 rqst_stats: Request statistics dictionary
126                 flow_stats: Flow statistcis dictionary
127                 elapsed_time: Elapsed time for the test
128
129             Returns: Rates (requests/sec) for successfully finished requests,
130                      the total number of requests, sucessfully installed flow and
131                      the total number of flows
132             """
133             ok_rqsts = rqst_stats[200] + rqst_stats[204]
134             total_rqsts = sum(rqst_stats.values())
135             ok_flows = flow_stats[200] + flow_stats[204]
136             total_flows = sum(flow_stats.values())
137
138             ok_rqst_rate = ok_rqsts / elapsed_time
139             total_rqst_rate = total_rqsts / elapsed_time
140             ok_flow_rate = ok_flows / elapsed_time
141             total_flow_rate = total_flows / elapsed_time
142
143             self.ok_rqsts.increment(ok_rqsts)
144             self.total_rqsts.increment(total_rqsts)
145             self.ok_flows.increment(ok_flows)
146             self.total_flows.increment(total_flows)
147
148             self.ok_rqst_rate.increment(ok_rqst_rate)
149             self.total_rqst_rate.increment(total_rqst_rate)
150             self.ok_flow_rate.increment(ok_flow_rate)
151             self.total_flow_rate.increment(total_flow_rate)
152
153             return ok_rqst_rate, total_rqst_rate, ok_flow_rate, total_flow_rate
154
155         def get_ok_rqst_rate(self):
156             return self.ok_rqst_rate.value
157
158         def get_total_rqst_rate(self):
159             return self.total_rqst_rate.value
160
161         def get_ok_flow_rate(self):
162             return self.ok_flow_rate.value
163
164         def get_total_flow_rate(self):
165             return self.total_flow_rate.value
166
167         def get_ok_rqsts(self):
168             return self.ok_rqsts.value
169
170         def get_total_rqsts(self):
171             return self.total_rqsts.value
172
173         def get_ok_flows(self):
174             return self.ok_flows.value
175
176         def get_total_flows(self):
177             return self.total_flows.value
178
179     def __init__(self, host, port, ncycles, nthreads, fpr, nnodes, nflows, startflow, auth, flow_mod_template=None):
180         self.host = host
181         self.port = port
182         self.ncycles = ncycles
183         self.nthreads = nthreads
184         self.fpr = fpr
185         self.nnodes = nnodes
186         self.nflows = nflows
187         self.startflow = startflow
188         self.auth = auth
189
190         if flow_mod_template:
191             self.flow_mode_template = flow_mod_template
192
193         self.post_url_template = 'http://%s:' + self.port + '/' + self.TBLURL
194         self.del_url_template = 'http://%s:' + self.port + '/' + self.FLWURL
195
196         self.stats = self.FcbStats()
197         self.total_ok_flows = 0
198         self.total_ok_rqsts = 0
199
200         self.ip_addr = Counter(int(netaddr.IPAddress('10.0.0.1')) + startflow)
201
202         self.print_lock = threading.Lock()
203         self.cond = threading.Condition()
204         self.threads_done = 0
205
206         for i in range(self.nthreads):
207             self.flows[i] = {}
208
209     def get_num_nodes(self, session):
210         """
211         Determines the number of OF nodes in the connected mininet network. If
212         mininet is not connected, the default number of flows is set to 16.
213         :param session: 'requests' session which to use to query the controller
214                         for openflow nodes
215         :return: None
216         """
217         hosts = self.host.split(",")
218         host = hosts[0]
219         inventory_url = 'http://' + host + ":" + self.port + '/' + self.INVURL
220         nodes = self.nnodes
221
222         if not self.auth:
223             r = session.get(inventory_url, headers=self.getheaders, stream=False, timeout=self.TIMEOUT)
224         else:
225             r = session.get(inventory_url, headers=self.getheaders, stream=False, auth=('admin', 'admin'),
226                             timeout=self.TIMEOUT)
227
228         if r.status_code == 200:
229             try:
230                 inv = json.loads(r.content)['nodes']['node']
231                 nn = 0
232                 for n in range(len(inv)):
233                     if re.search('openflow', inv[n]['id']) is not None:
234                         nn += 1
235                 if nn != 0:
236                     nodes = nn
237             except KeyError:
238                 pass
239
240         return nodes
241
242     def create_flow_from_template(self, flow_id, ipaddr, node_id):
243         """
244         Create a new flow instance from the flow template specified during
245         FlowConfigBlaster instantiation. Flow templates are json-compatible
246         dictionaries that MUST contain elements for flow cookie, flow name,
247         flow id and the destination IPv4 address in the flow match field.
248
249         Args:
250             flow_id: Id for the new flow to create
251             ipaddr: IP Address to put into the flow's match
252             node_id: ID of the node where to create the flow
253
254         Returns: The flow that gas been created from the template
255
256         """
257         flow = copy.deepcopy(self.flow_mode_template['flow'][0])
258         flow['cookie'] = flow_id
259         flow['flow-name'] = self.create_flow_name(flow_id)
260         flow['id'] = str(flow_id)
261         flow['match']['ipv4-destination'] = '%s/32' % str(netaddr.IPAddress(ipaddr))
262         return flow
263
264     def post_flows(self, session, node, flow_list, flow_count):
265         """
266         Performs a RESTCONF post of flows passed in the 'flow_list' parameters
267         :param session: 'requests' session on which to perform the POST
268         :param node: The ID of the openflow node to which to post the flows
269         :param flow_list: List of flows (in dictionary form) to POST
270         :param flow_count: Flow counter for round-robin host load balancing
271
272         :return: status code from the POST operation
273         """
274         flow_data = self.convert_to_json(flow_list, node)
275
276         hosts = self.host.split(",")
277         host = hosts[flow_count % len(hosts)]
278         flow_url = self.assemble_post_url(host, node)
279         # print flow_url
280
281         if not self.auth:
282             r = session.post(flow_url, data=flow_data, headers=self.putheaders, stream=False, timeout=self.TIMEOUT)
283         else:
284             r = session.post(flow_url, data=flow_data, headers=self.putheaders, stream=False, auth=('admin', 'admin'),
285                              timeout=self.TIMEOUT)
286
287         return r.status_code
288
289     def assemble_post_url(self, host, node):
290         """
291         Creates url pointing to config dataStore: /nodes/node/<node-id>/table/<table-id>
292         :param host: ip address or host name pointing to controller
293         :param node: id of node (without protocol prefix and colon)
294         :return: url suitable for sending a flow to controller via POST method
295         """
296         return self.post_url_template % (host, node)
297
298     def convert_to_json(self, flow_list, node_id=None):
299         """
300         Dumps flows to json form.
301         :param flow_list: list of flows in json friendly structure
302         :param node_id: node identifier of corresponding node
303         :return: string containing plain json
304         """
305         fmod = dict(self.flow_mode_template)
306         fmod['flow'] = flow_list
307         flow_data = json.dumps(fmod)
308         # print flow_data
309         return flow_data
310
311     def add_flows(self, start_flow_id, tid):
312         """
313         Adds flows into the ODL config data store. This function is executed by
314         a worker thread (the Blaster thread). The number of flows created and
315         the batch size (i.e. how many flows will be put into a RESTCONF request)
316         are determined by control parameters initialized when FlowConfigBlaster
317         is created.
318         :param start_flow_id - the ID of the first flow. Each Blaster thread
319                                programs a different set of flows
320         :param tid: Thread ID - used to id the Blaster thread when statistics
321                                 for the thread are printed out
322         :return: None
323         """
324         rqst_stats = {200: 0, 204: 0}
325         flow_stats = {200: 0, 204: 0}
326
327         s = requests.Session()
328
329         n_nodes = self.get_num_nodes(s)
330
331         with self.print_lock:
332             print '    Thread %d:\n        Adding %d flows on %d nodes' % (tid, self.nflows, n_nodes)
333
334         nflows = 0
335         with Timer() as t:
336             while nflows < self.nflows:
337                 node_id = randrange(1, n_nodes + 1)
338                 flow_list = []
339                 for i in range(self.fpr):
340                     flow_id = tid * (self.ncycles * self.nflows) + nflows + start_flow_id + self.startflow
341                     self.flows[tid][flow_id] = node_id
342                     flow_list.append(self.create_flow_from_template(flow_id, self.ip_addr.increment(), node_id))
343                     nflows += 1
344                     if nflows >= self.nflows:
345                         break
346                 sts = self.post_flows(s, node_id, flow_list, nflows)
347                 try:
348                     rqst_stats[sts] += 1
349                     flow_stats[sts] += len(flow_list)
350                 except KeyError:
351                     rqst_stats[sts] = 1
352                     flow_stats[sts] = len(flow_list)
353
354         ok_rps, total_rps, ok_fps, total_fps = self.stats.process_stats(rqst_stats, flow_stats, t.secs)
355
356         with self.print_lock:
357             print '\n    Thread %d results (ADD): ' % tid
358             print '        Elapsed time: %.2fs,' % t.secs
359             print '        Requests/s: %.2f OK, %.2f Total' % (ok_rps, total_rps)
360             print '        Flows/s:    %.2f OK, %.2f Total' % (ok_fps, total_fps)
361             print '        Stats ({Requests}, {Flows}): ',
362             print rqst_stats,
363             print flow_stats
364             self.threads_done += 1
365
366         s.close()
367
368         with self.cond:
369             self.cond.notifyAll()
370
371     def delete_flow(self, session, node, flow_id, flow_count):
372         """
373         Deletes a single flow from the ODL config data store using RESTCONF
374         Args:
375             session: 'requests' session on which to perform the POST
376             node:  Id of the openflow node from which to delete the flow
377             flow_id: ID of the to-be-deleted flow
378             flow_count: Index of the flow being processed (for round-robin LB)
379
380         Returns: status code from the DELETE operation
381
382         """
383
384         hosts = self.host.split(",")
385         host = hosts[flow_count % len(hosts)]
386         flow_url = self.del_url_template % (host, node, flow_id)
387         # print flow_url
388
389         if not self.auth:
390             r = session.delete(flow_url, headers=self.getheaders, timeout=self.TIMEOUT)
391         else:
392             r = session.delete(flow_url, headers=self.getheaders, auth=('admin', 'admin'), timeout=self.TIMEOUT)
393
394         return r.status_code
395
396     def delete_flows(self, start_flow, tid):
397         """
398         Deletes flow from the ODL config space that have been added using the
399         'add_flows()' function. This function is executed by a worker thread
400         :param start_flow - the ID of the first flow. Each Blaster thread
401                                deletes a different set of flows
402         :param tid: Thread ID - used to id the Blaster thread when statistics
403                                 for the thread are printed out
404         :return:
405         """
406
407         rqst_stats = {200: 0, 204: 0}
408
409         s = requests.Session()
410         n_nodes = self.get_num_nodes(s)
411
412         with self.print_lock:
413             print 'Thread %d: Deleting %d flows on %d nodes' % (tid, self.nflows, n_nodes)
414
415         with Timer() as t:
416             for flow in range(self.nflows):
417                 flow_id = tid * (self.ncycles * self.nflows) + flow + start_flow + self.startflow
418                 sts = self.delete_flow(s, self.flows[tid][flow_id], flow_id, flow)
419                 try:
420                     rqst_stats[sts] += 1
421                 except KeyError:
422                     rqst_stats[sts] = 1
423
424         ok_rps, total_rps, ok_fps, total_fps = self.stats.process_stats(rqst_stats, rqst_stats, t.secs)
425
426         with self.print_lock:
427             print '\n    Thread %d results (DELETE): ' % tid
428             print '        Elapsed time: %.2fs,' % t.secs
429             print '        Requests/s:  %.2f OK,  %.2f Total' % (ok_rps, total_rps)
430             print '        Flows/s:     %.2f OK,  %.2f Total' % (ok_fps, total_fps)
431             print '        Stats ({Requests})',
432             print rqst_stats
433             self.threads_done += 1
434
435         s.close()
436
437         with self.cond:
438             self.cond.notifyAll()
439
440     def run_cycle(self, function):
441         """
442         Runs a flow-add or flow-delete test cycle. Each test consists of a
443         <cycles> test cycles, where <threads> worker (Blaster) threads are
444         started in each test cycle. Each Blaster thread programs <flows>
445         OpenFlow flows into the controller using the controller's RESTCONF API.
446         :param function: Add or delete, determines what test will be executed.
447         :return: None
448         """
449         self.total_ok_flows = 0
450         self.total_ok_rqsts = 0
451
452         for c in range(self.ncycles):
453             self.stats = self.FcbStats()
454             with self.print_lock:
455                 print '\nCycle %d:' % c
456
457             threads = []
458             for i in range(self.nthreads):
459                 t = threading.Thread(target=function, args=(c * self.nflows, i))
460                 threads.append(t)
461                 t.start()
462
463             # Wait for all threads to finish and measure the execution time
464             with Timer() as t:
465                 for thread in threads:
466                     thread.join()
467
468             with self.print_lock:
469                 print '\n*** Test summary:'
470                 print '    Elapsed time:    %.2fs' % t.secs
471                 print '    Peak requests/s: %.2f OK, %.2f Total' % (
472                     self.stats.get_ok_rqst_rate(), self.stats.get_total_rqst_rate())
473                 print '    Peak flows/s:    %.2f OK, %.2f Total' % (
474                     self.stats.get_ok_flow_rate(), self.stats.get_total_flow_rate())
475                 print '    Avg. requests/s: %.2f OK, %.2f Total (%.2f%% of peak total)' % (
476                     self.stats.get_ok_rqsts() / t.secs,
477                     self.stats.get_total_rqsts() / t.secs,
478                     (self.stats.get_total_rqsts() / t.secs * 100) / self.stats.get_total_rqst_rate())
479                 print '    Avg. flows/s:    %.2f OK, %.2f Total (%.2f%% of peak total)' % (
480                     self.stats.get_ok_flows() / t.secs,
481                     self.stats.get_total_flows() / t.secs,
482                     (self.stats.get_total_flows() / t.secs * 100) / self.stats.get_total_flow_rate())
483
484                 self.total_ok_flows += self.stats.get_ok_flows()
485                 self.total_ok_rqsts += self.stats.get_ok_rqsts()
486                 self.threads_done = 0
487
488     def add_blaster(self):
489         self.run_cycle(self.add_flows)
490
491     def delete_blaster(self):
492         self.run_cycle(self.delete_flows)
493
494     def get_ok_flows(self):
495         return self.total_ok_flows
496
497     def get_ok_rqsts(self):
498         return self.total_ok_rqsts
499
500     def create_flow_name(self, flow_id):
501         return 'TestFlow-%d' % flow_id
502
503
504 def get_json_from_file(filename):
505     """
506     Get a flow programming template from a file
507     :param filename: File from which to get the template
508     :return: The json flow template (string)
509     """
510     with open(filename, 'r') as f:
511         try:
512             ft = json.load(f)
513             keys = ft['flow'][0].keys()
514             if (u'cookie' in keys) and (u'flow-name' in keys) and (u'id' in keys) and (u'match' in keys):
515                 if u'ipv4-destination' in ft[u'flow'][0]['match'].keys():
516                     print 'File "%s" ok to use as flow template' % filename
517                     return ft
518         except ValueError:
519             print 'JSON parsing of file %s failed' % filename
520             pass
521
522     return None
523
524
525 ###############################################################################
526 # This is an example of what the content of a JSON flow mode template should
527 # look like. Cut & paste to create a custom template. "id" and "ipv4-destination"
528 # MUST be unique if multiple flows will be programmed in the same test. It's
529 # also beneficial to have unique "cookie" and "flow-name" attributes for easier
530 # identification of the flow.
531 ###############################################################################
532 example_flow_mod_json = '''{
533     "flow": [
534         {
535             "id": "38",
536             "cookie": 38,
537             "instructions": {
538                 "instruction": [
539                     {
540                         "order": 0,
541                         "apply-actions": {
542                             "action": [
543                                 {
544                                     "order": 0,
545                                     "drop-action": { }
546                                 }
547                             ]
548                         }
549                     }
550                 ]
551             },
552             "hard-timeout": 65000,
553             "match": {
554                 "ethernet-match": {
555                     "ethernet-type": {
556                         "type": 2048
557                     }
558                 },
559                 "ipv4-destination": "10.0.0.38/32"
560             },
561             "flow-name": "TestFlow-8",
562             "strict": false,
563             "cookie_mask": 4294967295,
564             "priority": 2,
565             "table_id": 0,
566             "idle-timeout": 65000,
567             "installHw": false
568         }
569
570     ]
571 }'''
572
573
574 def create_arguments_parser():
575     """
576     Shorthand to arg parser on library level in order to access and eventually enhance in ancestors.
577     :return: argument parser supporting config blaster arguments and parameters
578     """
579     my_parser = argparse.ArgumentParser(description='Flow programming performance test: First adds and then'
580                                                     ' deletes flows into the config tree, as specified by'
581                                                     ' optional parameters.')
582
583     my_parser.add_argument('--host', default='127.0.0.1',
584                            help='Host where odl controller is running (default is 127.0.0.1).  '
585                                 'Specify a comma-separated list of hosts to perform round-robin load-balancing.')
586     my_parser.add_argument('--port', default='8181',
587                            help='Port on which odl\'s RESTCONF is listening (default is 8181)')
588     my_parser.add_argument('--cycles', type=int, default=1,
589                            help='Number of flow add/delete cycles; default 1. Both Flow Adds and Flow Deletes are '
590                                 'performed in cycles. <THREADS> worker threads are started in each cycle and the cycle '
591                                 'ends when all threads finish. Another cycle is started when the previous cycle '
592                                 'finished.')
593     my_parser.add_argument('--threads', type=int, default=1,
594                            help='Number of request worker threads to start in each cycle; default=1. '
595                                 'Each thread will add/delete <FLOWS> flows.')
596     my_parser.add_argument('--flows', type=int, default=10,
597                            help='Number of flows that will be added/deleted by each worker thread in each cycle; '
598                                 'default 10')
599     my_parser.add_argument('--fpr', type=int, default=1,
600                            help='Flows-per-Request - number of flows (batch size) sent in each HTTP request; '
601                                 'default 1')
602     my_parser.add_argument('--nodes', type=int, default=16,
603                            help='Number of nodes if mininet is not connected; default=16. If mininet is connected, '
604                                 'flows will be evenly distributed (programmed) into connected nodes.')
605     my_parser.add_argument('--delay', type=int, default=0,
606                            help='Time (in seconds) to wait between the add and delete cycles; default=0')
607     my_parser.add_argument('--delete', dest='delete', action='store_true', default=True,
608                            help='Delete all added flows one by one, benchmark delete '
609                                 'performance.')
610     my_parser.add_argument('--no-delete', dest='delete', action='store_false',
611                            help='Do not perform the delete cycle.')
612     my_parser.add_argument('--auth', dest='auth', action='store_true', default=False,
613                            help="Use the ODL default username/password 'admin'/'admin' to authenticate access to REST; "
614                                 'default: no authentication')
615     my_parser.add_argument('--startflow', type=int, default=0,
616                            help='The starting Flow ID; default=0')
617     my_parser.add_argument('--file', default='',
618                            help='File from which to read the JSON flow template; default: no file, use a built in '
619                                 'template.')
620     return my_parser
621
622
623 if __name__ == "__main__":
624     ############################################################################
625     # This program executes the base performance test. The test adds flows into
626     # the controller's config space. This function is basically the CLI frontend
627     # to the FlowConfigBlaster class and drives its main functions: adding and
628     # deleting flows from the controller's config data store
629     ############################################################################
630
631     parser = create_arguments_parser()
632     in_args = parser.parse_args()
633
634     if in_args.file != '':
635         flow_template = get_json_from_file(in_args.file)
636     else:
637         flow_template = None
638
639     fct = FlowConfigBlaster(in_args.host, in_args.port, in_args.cycles, in_args.threads, in_args.fpr, in_args.nodes,
640                             in_args.flows, in_args.startflow, in_args.auth)
641
642     # Run through <cycles>, where <threads> are started in each cycle and
643     # <flows> are added from each thread
644     fct.add_blaster()
645
646     print '\n*** Total flows added: %s' % fct.get_ok_flows()
647     print '    HTTP[OK] results:  %d\n' % fct.get_ok_rqsts()
648
649     if in_args.delay > 0:
650         print '*** Waiting for %d seconds before the delete cycle ***\n' % in_args.delay
651         time.sleep(in_args.delay)
652
653     # Run through <cycles>, where <threads> are started in each cycle and
654     # <flows> previously added in an add cycle are deleted in each thread
655     if in_args.delete:
656         fct.delete_blaster()
657         print '\n*** Total flows deleted: %s' % fct.get_ok_flows()
658         print '    HTTP[OK] results:    %d\n' % fct.get_ok_rqsts()