1 __author__ = "Basheeruddin Ahmed"
2 __copyright__ = "Copyright(c) 2014, Cisco Systems, Inc."
3 __license__ = "New-style BSD"
4 __email__ = "syedbahm@cisco.com"
8 from SSHLibrary import SSHLibrary
17 def get(url, userId='admin', password='admin'):
18 """Helps in making GET REST calls"""
21 headers['Accept'] = 'application/xml'
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})
31 def nonprintpost(url, userId, password, data):
32 """Helps in making POST REST calls without outputs"""
41 headers['Content-Type'] = 'application/json'
42 # headers['Accept']= 'application/xml'
44 session = _cache.switch("CLUSTERING_POST")
45 resp = session.post(url, data.encode('utf-8'), headers=headers, auth=(userId, password))
50 def post(url, userId, password, data):
51 """Helps in making POST REST calls"""
59 print("post request with url "+url)
60 print("post request with data "+data)
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))
67 # print (resp.raise_for_status())
69 if resp.status_code >= 500:
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
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
87 raise AssertionError('the variable passed was type NoneType')
91 def execute_ssh_command(ip, username, password, command):
92 """Execute SSH Command
94 use username and password of controller server for ssh and need
95 karaf distribution location like /root/Documents/dist
97 print "executing ssh command"
99 lib.open_connection(ip)
100 lib.login(username=username, password=password)
102 cmd_response = lib.execute_command(command)
103 print "command executed : " + command
104 lib.close_connection()
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"
112 print "Waiting for controller " + ip + " up."
113 # Try 30*10s=5 minutes for the controller to be up.
116 print "attempt " + str(i) + " to url " + url
117 resp = get(url, "admin", "admin")
118 print "attempt " + str(i) + " response is " + str(resp)
120 if ('clustering-it-provider' in resp.text):
121 print "Wait for controller " + ip + " succeeded"
123 except Exception as e:
127 print "Wait for controller " + ip + " failed"
131 def startAllControllers(username, password, karafhome, port, *ips):
132 # Start all controllers
134 execute_ssh_command(ip, username, password, karafhome+"/bin/start")
136 # Wait for all of them to be up
138 rc = wait_for_controller_up(ip, port)
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)
149 def stopcontroller(ip, username, password, karafhome):
150 executeStopController(ip, username, password, karafhome)
152 wait_for_controller_stopped(ip, username, password, karafhome)
155 def executeStopController(ip, username, password, karafhome):
156 execute_ssh_command(ip, username, password, karafhome+"/bin/stop")
159 def stopAllControllers(username, password, karafhome, *ips):
161 executeStopController(ip, username, password, karafhome)
164 wait_for_controller_stopped(ip, username, password, karafhome)
167 def wait_for_controller_stopped(ip, username, password, karafHome):
169 lib.open_connection(ip)
170 lib.login(username=username, password=password)
172 # Wait 1 minute for the controller to stop gracefully
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':
185 lib.close_connection()
188 print "Killing controller"
189 kill_controller(ip, username, password, karafHome)
192 def clean_journal(ip, username, password, karafHome):
193 execute_ssh_command(ip, username, password, "rm -rf " + karafHome + "/journal")
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")
201 def isolate_controller(controllers, username, password, isolated):
202 """ Isolate one controller from the others in the cluster
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.
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')
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
233 def rejoin_controller(controllers, username, password, isolated):
234 """ Return an isolated controller to the cluster.
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.
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')
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
265 def flush_iptables(controllers, username, password):
266 """Removes all entries from IPTables on all controllers.
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".
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)
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."
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')