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