Step 1: Move vm scripts to the right place
[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 import re
13
14 global _cache
15
16
17 def get(url, userId='admin', password='admin'):
18     """Helps in making GET REST calls"""
19
20     headers = {}
21     headers['Accept'] = 'application/xml'
22
23     # Send the GET request
24     session = _cache.switch("CLUSTERING_GET")
25     resp = session.get(url, headers=headers, auth=(userId, password))
26     # resp = session.get(url,headers=headers,auth={userId,password})
27     # Read the response
28     return resp
29
30
31 def nonprintpost(url, userId, password, data):
32     """Helps in making POST REST calls without outputs"""
33
34     if userId is None:
35         userId = 'admin'
36
37     if password is None:
38         password = 'admin'
39
40     headers = {}
41     headers['Content-Type'] = 'application/json'
42     # headers['Accept']= 'application/xml'
43
44     session = _cache.switch("CLUSTERING_POST")
45     resp = session.post(url, data.encode('utf-8'), headers=headers, auth=(userId, password))
46
47     return resp
48
49
50 def post(url, userId, password, data):
51     """Helps in making POST REST calls"""
52
53     if userId is None:
54         userId = 'admin'
55
56     if password is None:
57         password = 'admin'
58
59     print("post request with url "+url)
60     print("post request with data "+data)
61     headers = {}
62     headers['Content-Type'] = 'application/json'
63     # headers['Accept']= 'application/xml'
64     session = _cache.switch("CLUSTERING_POST")
65     resp = session.post(url, data.encode('utf-8'), headers=headers, auth=(userId, password))
66
67     # print (resp.raise_for_status())
68     print (resp.headers)
69     if resp.status_code >= 500:
70         print(resp.text)
71
72     return resp
73
74
75 def delete(url, userId='admin', password='admin'):
76     """Helps in making DELET REST calls"""
77     print("delete all resources belonging to url"+url)
78     session = _cache.switch("CLUSTERING_DELETE")
79     resp = session.delete(url, auth=(userId, password))  # noqa
80
81
82 def Should_Not_Be_Type_None(var):
83     '''Keyword to check if the given variable is of type NoneType.  If the
84         variable type does match  raise an assertion so the keyword will fail
85     '''
86     if var is None:
87         raise AssertionError('the variable passed was type NoneType')
88     return 'PASS'
89
90
91 def execute_ssh_command(ip, username, password, command):
92     """Execute SSH Command
93
94     use username and password of controller server for ssh and need
95     karaf distribution location like /root/Documents/dist
96     """
97     print "executing ssh command"
98     lib = SSHLibrary()
99     lib.open_connection(ip)
100     lib.login(username=username, password=password)
101     print "login done"
102     cmd_response = lib.execute_command(command)
103     print "command executed : " + command
104     lib.close_connection()
105     return cmd_response
106
107
108 def wait_for_controller_up(ip, port="8181"):
109     url = "http://" + ip + ":" + str(port) + \
110           "/restconf/config/opendaylight-inventory:nodes/node/controller-config/yang-ext:mount/config:modules"
111
112     print "Waiting for controller " + ip + " up."
113     # Try 30*10s=5 minutes for the controller to be up.
114     for i in xrange(30):
115         try:
116             print "attempt " + str(i) + " to url " + url
117             resp = get(url, "admin", "admin")
118             print "attempt " + str(i) + " response is " + str(resp)
119             print resp.text
120             if ('clustering-it-provider' in resp.text):
121                 print "Wait for controller " + ip + " succeeded"
122                 return True
123         except Exception as e:
124             print e
125         time.sleep(10)
126
127     print "Wait for controller " + ip + " failed"
128     return False
129
130
131 def startAllControllers(username, password, karafhome, port, *ips):
132     # Start all controllers
133     for ip in ips:
134         execute_ssh_command(ip, username, password, karafhome+"/bin/start")
135
136     # Wait for all of them to be up
137     for ip in ips:
138         rc = wait_for_controller_up(ip, port)
139         if rc is False:
140             return False
141     return True
142
143
144 def startcontroller(ip, username, password, karafhome, port):
145     execute_ssh_command(ip, username, password, karafhome + "/bin/start")
146     return wait_for_controller_up(ip, port)
147
148
149 def stopcontroller(ip, username, password, karafhome):
150     executeStopController(ip, username, password, karafhome)
151
152     wait_for_controller_stopped(ip, username, password, karafhome)
153
154
155 def executeStopController(ip, username, password, karafhome):
156     execute_ssh_command(ip, username, password, karafhome+"/bin/stop")
157
158
159 def stopAllControllers(username, password, karafhome, *ips):
160     for ip in ips:
161         executeStopController(ip, username, password, karafhome)
162
163     for ip in ips:
164         wait_for_controller_stopped(ip, username, password, karafhome)
165
166
167 def wait_for_controller_stopped(ip, username, password, karafHome):
168     lib = SSHLibrary()
169     lib.open_connection(ip)
170     lib.login(username=username, password=password)
171
172     # Wait 1 minute for the controller to stop gracefully
173     tries = 20
174     i = 1
175     while i <= tries:
176         stdout = lib.execute_command("ps -axf | grep karaf | grep -v grep | wc -l")
177         # print "stdout: "+stdout
178         processCnt = stdout[0].strip('\n')
179         print("processCnt: " + processCnt)
180         if processCnt == '0':
181             break
182         i = i + 1
183         time.sleep(3)
184
185     lib.close_connection()
186
187     if i > tries:
188         print "Killing controller"
189         kill_controller(ip, username, password, karafHome)
190
191
192 def clean_journal(ip, username, password, karafHome):
193     execute_ssh_command(ip, username, password, "rm -rf " + karafHome + "/journal")
194
195
196 def kill_controller(ip, username, password, karafHome):
197     execute_ssh_command(ip, username, password,
198                         "ps axf | grep karaf | grep -v grep | awk '{print \"kill -9 \" $1}' | sh")
199
200
201 def isolate_controller(controllers, username, password, isolated):
202     """ Isolate one controller from the others in the cluster
203
204     :param controllers: A list of ip addresses or host names as strings.
205     :param username: Username for the controller to be isolated.
206     :param password: Password for the controller to be isolated.
207     :param isolated: Number (starting at one) of the controller to be isolated.
208     :return: If successful, returns "pass", otherwise returns the last failed IPTables text.
209     """
210     isolated_controller = controllers[isolated-1]
211     for controller in controllers:
212         if controller != isolated_controller:
213             base_str = 'sudo iptables -I OUTPUT -p all --source '
214             cmd_str = base_str + isolated_controller + ' --destination ' + controller + ' -j DROP'
215             execute_ssh_command(isolated_controller, username, password, cmd_str)
216             cmd_str = base_str + controller + ' --destination ' + isolated_controller + ' -j DROP'
217             execute_ssh_command(isolated_controller, username, password, cmd_str)
218     ip_tables = execute_ssh_command(isolated_controller, username, password, 'sudo iptables -L')
219     print ip_tables
220     iso_result = 'pass'
221     for controller in controllers:
222         controller_regex_string = "[\s\S]*" + isolated_controller + " *" + controller + "[\s\S]*"
223         controller_regex = re.compile(controller_regex_string)
224         if not controller_regex.match(ip_tables):
225             iso_result = ip_tables
226         controller_regex_string = "[\s\S]*" + controller + " *" + isolated_controller + "[\s\S]*"
227         controller_regex = re.compile(controller_regex_string)
228         if not controller_regex.match(ip_tables):
229             iso_result = ip_tables
230     return iso_result
231
232
233 def rejoin_controller(controllers, username, password, isolated):
234     """ Return an isolated controller to the cluster.
235
236     :param controllers: A list of ip addresses or host names as strings.
237     :param username: Username for the isolated controller.
238     :param password: Password for the isolated controller.
239     :param isolated: Number (starting at one) of the isolated controller isolated.
240     :return: If successful, returns "pass", otherwise returns the last failed IPTables text.
241     """
242     isolated_controller = controllers[isolated-1]
243     for controller in controllers:
244         if controller != isolated_controller:
245             base_str = 'sudo iptables -D OUTPUT -p all --source '
246             cmd_str = base_str + isolated_controller + ' --destination ' + controller + ' -j DROP'
247             execute_ssh_command(isolated_controller, username, password, cmd_str)
248             cmd_str = base_str + controller + ' --destination ' + isolated_controller + ' -j DROP'
249             execute_ssh_command(isolated_controller, username, password, cmd_str)
250     ip_tables = execute_ssh_command(isolated_controller, username, password, 'sudo iptables -L')
251     print ip_tables
252     iso_result = 'pass'
253     for controller in controllers:
254         controller_regex_string = "[\s\S]*" + isolated_controller + " *" + controller + "[\s\S]*"
255         controller_regex = re.compile(controller_regex_string)
256         if controller_regex.match(ip_tables):
257             iso_result = ip_tables
258         controller_regex_string = "[\s\S]*" + controller + " *" + isolated_controller + "[\s\S]*"
259         controller_regex = re.compile(controller_regex_string)
260         if controller_regex.match(ip_tables):
261             iso_result = ip_tables
262     return iso_result
263
264
265 def flush_iptables(controllers, username, password):
266     """Removes all entries from IPTables on all controllers.
267
268     :param controllers: A list of ip address or host names as strings.
269     :param username: Username for all controllers.
270     :param password: Password for all controllers.
271     :return: If successful, returns "pass", otherwise returns "fail".
272     """
273     flush_result = 'pass'
274     for controller in controllers:
275         print 'Flushing ' + controller
276         cmd_str = 'sudo iptables -v -F'
277         cmd_result = execute_ssh_command(controller, username, password, cmd_str)
278         print cmd_result
279         success_string = "Flushing chain `INPUT'" + "\n"
280         success_string += "Flushing chain `FORWARD'" + "\n"
281         success_string += "Flushing chain `OUTPUT'"
282         if not cmd_result == success_string:
283             flush_result = "Failed to flush IPTables. Check Log."
284         print "."
285         print "."
286         print "."
287     return flush_result
288
289
290 #
291 # main invoked
292 if __name__ != "__main__":
293     _cache = robot.utils.ConnectionCache('No sessions created')
294     # here create one session for each HTTP functions
295     _cache.register(requests.session(), alias='CLUSTERING_GET')
296     _cache.register(requests.session(), alias='CLUSTERING_POST')
297     _cache.register(requests.session(), alias='CLUSTERING_DELETE')