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