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