Enhancements to 3-node cluster tests
[integration/test.git] / test / csit / libraries / UtilLibrary.py
1 __author__ = "Basheeruddin Ahmed"
2 __copyright__ = "Copyright(c) 2014, Cisco Systems, Inc."
3 __license__ = "New-style BSD"
4 __email__ = "syedbahm@cisco.com"
5
6
7 import requests
8 from SSHLibrary import SSHLibrary
9
10 import robot
11 import time
12
13 global _cache
14
15 #
16 #Helps in making GET REST calls
17 #
18
19 def get(url, userId='admin', password='admin'):
20
21     headers = {}
22     headers['Accept']= 'application/xml'
23
24     # Send the GET request
25     session = _cache.switch("CLUSTERING_GET")
26     resp = session.get(url,headers=headers,auth=(userId,password))    
27     #resp = session.get(url,headers=headers,auth={userId,password})
28     # Read the response
29     return resp
30
31 #
32 #Helps in making POST REST calls without outputs
33 #
34 def nonprintpost(url, userId, password, data):
35
36     if userId == None:
37         userId = 'admin'
38
39     if password == None:
40         password = 'admin'
41
42     headers = {}
43     headers['Content-Type'] = 'application/json'
44     #headers['Accept']= 'application/xml'
45
46     session = _cache.switch("CLUSTERING_POST")
47     resp = session.post(url,data.encode('utf-8'),headers=headers,auth=(userId,password))
48
49
50     return resp
51
52 #
53 #Helps in making POST REST calls
54 #
55 def post(url, userId, password, data):
56
57     if userId == None:
58         userId = 'admin'
59
60     if password == None:
61         password = 'admin'
62
63     print("post request with url "+url)
64     print("post request with data "+data)
65     headers = {}
66     headers['Content-Type'] = 'application/json'
67     #headers['Accept']= 'application/xml'
68     session = _cache.switch("CLUSTERING_POST")
69     resp = session.post(url,data.encode('utf-8'),headers=headers,auth=(userId,password))
70
71     #print (resp.raise_for_status())
72     print (resp.headers)
73     if (resp.status_code >= 500):
74         print (resp.text)
75
76     return resp
77
78 #
79 #Helps in making DELET REST calls
80 #
81 def delete(url, userId='admin', password='admin'):
82     print("delete all resources belonging to url"+url)
83     session = _cache.switch("CLUSTERING_DELETE")
84     resp=session.delete(url,auth=(userId,password))
85
86 def Should_Not_Be_Type_None(var):
87     '''Keyword to check if the given variable is of type NoneType.  If the
88         variable type does match  raise an assertion so the keyword will fail
89     '''
90     if var == None:
91         raise AssertionError('the variable passed was type NoneType')
92     return 'PASS'
93
94 # use username and password of controller server for ssh and need
95 # karaf distribution location like /root/Documents/dist
96 #
97 def execute_ssh_command(ip, username, password, command):
98     print "executing ssh command"
99     lib = SSHLibrary()
100     lib.open_connection(ip)
101     lib.login(username=username,password=password)
102     print "login done"
103     lib.execute_command(command)
104     print "command executed : " + command
105     lib.close_connection()
106
107 def wait_for_controller_up(ip, port="8181"):
108     url = "http://" + ip + ":" + str(port) + \
109           "/restconf/config/opendaylight-inventory:nodes/node/controller-config/yang-ext:mount/config:modules"
110
111     print "Waiting for controller " + ip + " up."
112     # Try 30*10s=5 minutes for the controller to be up.
113     for i in xrange(30):
114         try:
115             print "attempt " + str(i) + " to url " + url
116             resp = get(url, "admin", "admin")
117             print "attempt " + str(i) + " response is " + str(resp)
118             print resp.text
119             if ('clustering-it-provider' in resp.text):
120                 print "Wait for controller " + ip + " succeeded"
121                 return True
122         except Exception as e:
123             print e
124         time.sleep(10)
125
126     print "Wait for controller " + ip + " failed"
127     return False
128
129 def startAllControllers(username, password, karafhome, port, *ips):
130     # Start all controllers
131     for ip in ips:
132         execute_ssh_command(ip, username, password, karafhome+"/bin/start")
133
134     # Wait for all of them to be up
135     for ip in ips:
136         rc = wait_for_controller_up(ip, port)
137         if (rc == False):
138             return False
139     return True
140
141 def startcontroller(ip,username,password,karafhome,port):
142     execute_ssh_command(ip, username, password, karafhome+"/bin/start")
143     return wait_for_controller_up(ip, port)
144
145 def stopcontroller(ip,username,password,karafhome):
146     executeStopController(ip,username,password,karafhome)
147
148     wait_for_controller_stopped(ip,username,password,karafhome)
149
150 def executeStopController(ip,username,password,karafhome):
151     execute_ssh_command(ip, username, password, karafhome+"/bin/stop")
152
153 def stopAllControllers(username,password,karafhome,*ips):
154     for ip in ips:
155         executeStopController(ip,username,password,karafhome)
156
157     for ip in ips:
158         wait_for_controller_stopped(ip, username, password, karafhome)
159
160 def wait_for_controller_stopped(ip, username, password, karafHome):
161     lib = SSHLibrary()
162     lib.open_connection(ip)
163     lib.login(username=username,password=password)
164
165     # Wait 1 minute for the controller to stop gracefully   
166     tries = 20
167     i=1
168     while i <= tries:
169         stdout = lib.execute_command("ps -axf | grep karaf | grep -v grep | wc -l")
170         #print "stdout: "+stdout
171         processCnt = stdout[0].strip('\n')
172         print "processCnt: "+processCnt
173         if processCnt == '0':
174             break;
175         i = i+1
176         time.sleep(3)
177
178     lib.close_connection()
179
180     if i > tries:
181         print "Killing controller"
182         kill_controller(ip, username, password, karafHome)   
183
184 def clean_journal(ip, username, password, karafHome):
185     execute_ssh_command(ip, username, password, "rm -rf " + karafHome + "/journal")
186
187 def kill_controller(ip, username, password, karafHome):
188     execute_ssh_command(ip, username, password, "ps axf | grep karaf | grep -v grep | awk '{print \"kill -9 \" $1}' | sh")
189
190 #
191 # main invoked
192 if __name__ != "__main__":
193     _cache = robot.utils.ConnectionCache('No sessions created')
194     # here create one session for each HTTP functions
195     _cache.register(requests.session(), alias='CLUSTERING_GET')
196     _cache.register(requests.session(),alias='CLUSTERING_POST')
197     _cache.register(requests.session(),alias='CLUSTERING_DELETE')