Updated code to match new rules
[integration/test.git] / tools / odl-mdsal-clustering-tests / clustering-performance-test / inventory_read_blaster.py
1 #!/usr/bin/python
2
3 import requests
4 import argparse
5 import time
6 import threading
7 import functools
8 import operator
9 import collections
10
11 from Queue import Queue
12
13
14 __author__ = "Gary Wu"
15 __email__ = "gary.wu1@huawei.com"
16
17
18 GET_HEADERS = {'Accept': 'application/json'}
19
20 INVENTORY_URL = 'http://%s:%d/restconf/%s/opendaylight-inventory:nodes'
21
22
23 class Timer(object):
24     def __init__(self, verbose=False):
25         self.verbose = verbose
26
27     def __enter__(self):
28         self.start = time.time()
29         return self
30
31     def __exit__(self, *args):
32         self.end = time.time()
33         self.secs = self.end - self.start
34         self.msecs = self.secs * 1000  # millisecs
35         if self.verbose:
36             print ("elapsed time: %f ms" % self.msecs)
37
38
39 def read(hosts, port, auth, datastore, print_lock, cycles, results_queue):
40     """
41     Make RESTconf request to read the flow configuration from the specified data store.
42
43     Args:
44
45         :param hosts: A comma-separated list of hosts to read from.
46
47         :param port: The port number to read from.
48
49         :param auth: The username and password pair to use for basic authentication, or None
50             if no authentication is required.
51
52         :param datastore: The datastore (operational/config) to read flows from.
53
54         :param print_lock: The thread lock to allow only one thread to output at a time.
55
56         :param cycles: The number of reads that this thread will perform.
57
58         :param results_queue: Used to store the HTTP status results of this method call.
59     """
60     s = requests.Session()
61     stats = {}
62     for i in range(cycles):
63         host = hosts[i % len(hosts)]
64         url = INVENTORY_URL % (host, port, datastore)
65         r = s.get(url, headers=GET_HEADERS, stream=False, auth=auth)
66         # If dict has no such entry, default to 0
67         stats[r.status_code] = stats.get(r.status_code, 0) + 1
68
69     with print_lock:
70         print '   ', threading.current_thread().name, 'results:', stats
71
72     results_queue.put(stats)
73
74
75 if __name__ == "__main__":
76     parser = argparse.ArgumentParser(description='Inventory read performance test: Repeatedly read openflow node data '
77                                      'from config datastore.  Note that the data needs to be created in the datastore '
78                                      'first using flow_config_blaster.py --no-delete.')
79
80     parser.add_argument('--host', default='127.0.0.1',
81                         help='Host where odl controller is running (default is 127.0.0.1).  '
82                              'Specify a comma-separated list of hosts to perform round-robin load-balancing.')
83     parser.add_argument('--port', default='8181', type=int,
84                         help='Port on which odl\'s RESTCONF is listening (default is 8181)')
85     parser.add_argument('--datastore', choices=['operational', 'config'],
86                         default='operational', help='Which data store to crawl; default operational')
87     parser.add_argument('--cycles', type=int, default=100,
88                         help='Number of repeated reads; default 100. ')
89     parser.add_argument('--threads', type=int, default=1,
90                         help='Number of request worker threads to start in each cycle; default=1. '
91                              'Each thread will add/delete <FLOWS> flows.')
92     parser.add_argument('--auth', dest='auth', action='store_true', default=False,
93                         help="Use the ODL default username/password 'admin'/'admin' to authenticate access to REST; "
94                              'default: no authentication')
95
96     args = parser.parse_args()
97
98     hosts = args.host.split(",")
99     port = args.port
100     auth = ("admin", "admin") if args.auth else None
101
102     # Use a lock to ensure that output from multiple threads don't interrupt/overlap each other
103     print_lock = threading.Lock()
104     results = Queue()
105
106     with Timer() as t:
107         threads = []
108         for i in range(args.threads):
109             thread = threading.Thread(target=read, args=(hosts, port, auth, args.datastore, print_lock, args.cycles,
110                                                          results))
111             threads.append(thread)
112             thread.start()
113
114         # Wait for all threads to finish and measure the execution time
115         for thread in threads:
116             thread.join()
117
118     # Aggregate the results
119     stats = functools.reduce(operator.add, map(collections.Counter, results.queue))
120
121     print '\n*** Test summary:'
122     print '    Elapsed time:    %.2fs' % t.secs
123     print '    HTTP[OK] results:  %d\n' % stats[200]