Add SSH connectivity check
[functest.git] / testcases / features / sfc / sfc.py
1 import os
2 import subprocess
3 import sys
4 import time
5
6 import argparse
7 import paramiko
8
9 import functest.utils.functest_logger as ft_logger
10 import functest.utils.functest_utils as ft_utils
11 import functest.utils.openstack_utils as os_utils
12
13 parser = argparse.ArgumentParser()
14
15 parser.add_argument("-r", "--report",
16                     help="Create json result file",
17                     action="store_true")
18
19 args = parser.parse_args()
20
21 """ logging configuration """
22 logger = ft_logger.Logger("ODL_SFC").getLogger()
23
24 FUNCTEST_REPO = ft_utils.FUNCTEST_REPO
25
26 HOME = os.environ['HOME'] + "/"
27
28 VM_BOOT_TIMEOUT = 180
29 INSTANCE_NAME = "client"
30 FLAVOR = "m1.small"
31 IMAGE_NAME = "sf_nsh_colorado"
32 IMAGE_FILENAME = "sf_nsh_colorado.qcow2"
33 IMAGE_FORMAT = "qcow2"
34 IMAGE_PATH = "/home/opnfv/functest/data" + "/" + IMAGE_FILENAME
35
36 # NEUTRON Private Network parameters
37
38 NET_NAME = "example-net"
39 SUBNET_NAME = "example-subnet"
40 SUBNET_CIDR = "11.0.0.0/24"
41 ROUTER_NAME = "example-router"
42
43 SECGROUP_NAME = "example-sg"
44 SECGROUP_DESCR = "Example Security group"
45
46 INSTANCE_NAME_2 = "server"
47
48 # TEST_DB = ft_utils.get_parameter_from_yaml("results.test_db_url")
49
50 PRE_SETUP_SCRIPT = 'sfc_pre_setup.bash'
51 TACKER_SCRIPT = 'sfc_tacker.bash'
52 TEARDOWN_SCRIPT = "sfc_teardown.bash"
53 TACKER_CHANGECLASSI = "sfc_change_classi.bash"
54
55 ssh_options = '-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'
56
57
58 def check_ssh(ip):
59     cmd = "sshpass -p opnfv ssh " + ssh_options + " -q " + ip + " exit"
60     success = subprocess.call(cmd, shell=True) == 0
61     if not success:
62         logger.debug("Wating for SSH connectivity in SF with IP: %s" % ip)
63     return success
64
65
66 def main():
67
68     # Allow any port so that tacker commands reaches the server.
69     # This will be deleted when tacker is included in OPNFV installation
70
71     status = "PASS"
72     failures = 0
73     start_time = time.time()
74     json_results = {}
75
76     contr_cmd = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
77                  " 'fuel node'|grep controller|awk '{print $10}'")
78     logger.info("Executing script to get ip_server: '%s'" % contr_cmd)
79     process = subprocess.Popen(contr_cmd,
80                                shell=True,
81                                stdout=subprocess.PIPE,
82                                stderr=subprocess.PIPE)
83     ip_server = process.stdout.readline().rstrip()
84
85     contr_cmd2 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
86                   " 'fuel node'|grep compute|awk '{print $10}'")
87     logger.info("Executing script to get ip_compute: '%s'" % contr_cmd2)
88     process = subprocess.Popen(contr_cmd2,
89                                shell=True,
90                                stdout=subprocess.PIPE,
91                                stderr=subprocess.PIPE)
92     ip_compute = process.stdout.readline().rstrip()
93
94     iptable_cmd1 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
95                     " ssh " + ip_server + " iptables -P INPUT ACCEPT ")
96     iptable_cmd2 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
97                     " ssh " + ip_server + " iptables -t nat -P INPUT ACCEPT ")
98     iptable_cmd3 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
99                     " ssh " + ssh_options + " " + ip_server +
100                     " iptables -A INPUT -m state"
101                     " --state NEW,ESTABLISHED,RELATED -j ACCEPT")
102
103     logger.info("Changing firewall policy in controller: '%s'" % iptable_cmd1)
104     subprocess.call(iptable_cmd1, shell=True, stderr=subprocess.PIPE)
105
106     logger.info("Changing firewall policy in controller: '%s'" % iptable_cmd2)
107     subprocess.call(iptable_cmd2, shell=True, stderr=subprocess.PIPE)
108
109     logger.info("Changing firewall policy in controller: '%s'" % iptable_cmd3)
110     subprocess.call(iptable_cmd3, shell=True, stderr=subprocess.PIPE)
111
112 # Getting the different clients
113
114     nova_client = os_utils.get_nova_client()
115     neutron_client = os_utils.get_neutron_client()
116     glance_client = os_utils.get_glance_client()
117
118 # Download the image
119
120     if not os.path.isfile(IMAGE_PATH):
121         logger.info("Downloading image")
122         ft_utils.download_url(
123             "http://artifacts.opnfv.org/sfc/demo/sf_nsh_colorado.qcow2",
124             "/home/opnfv/functest/data/")
125     else:
126         logger.info("Using old image")
127
128 # Create glance image and the neutron network
129
130     image_id = os_utils.create_glance_image(glance_client,
131                                             IMAGE_NAME,
132                                             IMAGE_PATH,
133                                             disk=IMAGE_FORMAT,
134                                             container="bare",
135                                             public=True)
136
137     network_dic = os_utils.create_network_full(neutron_client,
138                                                NET_NAME,
139                                                SUBNET_NAME,
140                                                ROUTER_NAME,
141                                                SUBNET_CIDR)
142     if not network_dic:
143         logger.error(
144             "There has been a problem when creating the neutron network")
145         sys.exit(-1)
146
147     network_id = network_dic["net_id"]
148
149     sg_id = os_utils.create_security_group_full(neutron_client,
150                                                 SECGROUP_NAME, SECGROUP_DESCR)
151
152     # boot INSTANCE
153     logger.info("Creating instance '%s'..." % INSTANCE_NAME)
154     logger.debug(
155         "Configuration:\n name=%s \n flavor=%s \n image=%s \n "
156         "network=%s \n" % (INSTANCE_NAME, FLAVOR, image_id, network_id))
157     instance = os_utils.create_instance_and_wait_for_active(FLAVOR,
158                                                             image_id,
159                                                             network_id,
160                                                             INSTANCE_NAME)
161
162     if instance is None:
163         logger.error("Error while booting instance.")
164         sys.exit(-1)
165     # Retrieve IP of INSTANCE
166     instance_ip = instance.networks.get(NET_NAME)[0]
167     logger.debug("Instance '%s' got private ip '%s'." %
168                  (INSTANCE_NAME, instance_ip))
169
170     logger.info("Adding '%s' to security group '%s'..."
171                 % (INSTANCE_NAME, SECGROUP_NAME))
172     os_utils.add_secgroup_to_instance(nova_client, instance.id, sg_id)
173
174     logger.info("Creating floating IP for VM '%s'..." % INSTANCE_NAME)
175     floatip_dic = os_utils.create_floating_ip(neutron_client)
176     floatip_client = floatip_dic['fip_addr']
177     # floatip_id = floatip_dic['fip_id']
178
179     if floatip_client is None:
180         logger.error("Cannot create floating IP.")
181         sys.exit(-1)
182     logger.info("Floating IP created: '%s'" % floatip_client)
183
184     logger.info("Associating floating ip: '%s' to VM '%s' "
185                 % (floatip_client, INSTANCE_NAME))
186     if not os_utils.add_floating_ip(nova_client, instance.id, floatip_client):
187         logger.error("Cannot associate floating IP to VM.")
188         sys.exit(-1)
189
190 # STARTING SECOND VM (server) ###
191
192     # boot INTANCE
193     logger.info("Creating instance '%s'..." % INSTANCE_NAME)
194     logger.debug(
195         "Configuration:\n name=%s \n flavor=%s \n image=%s \n "
196         "network=%s \n" % (INSTANCE_NAME, FLAVOR, image_id, network_id))
197     instance_2 = os_utils.create_instance_and_wait_for_active(FLAVOR,
198                                                               image_id,
199                                                               network_id,
200                                                               INSTANCE_NAME_2)
201
202     if instance_2 is None:
203         logger.error("Error while booting instance.")
204         sys.exit(-1)
205     # Retrieve IP of INSTANCE
206     instance_ip_2 = instance_2.networks.get(NET_NAME)[0]
207     logger.debug("Instance '%s' got private ip '%s'." %
208                  (INSTANCE_NAME_2, instance_ip_2))
209
210     logger.info("Adding '%s' to security group '%s'..."
211                 % (INSTANCE_NAME_2, SECGROUP_NAME))
212     os_utils.add_secgroup_to_instance(nova_client, instance_2.id, sg_id)
213
214     logger.info("Creating floating IP for VM '%s'..." % INSTANCE_NAME_2)
215     floatip_dic = os_utils.create_floating_ip(neutron_client)
216     floatip_server = floatip_dic['fip_addr']
217     # floatip_id = floatip_dic['fip_id']
218
219     if floatip_server is None:
220         logger.error("Cannot create floating IP.")
221         sys.exit(-1)
222     logger.info("Floating IP created: '%s'" % floatip_server)
223
224     logger.info("Associating floating ip: '%s' to VM '%s' "
225                 % (floatip_server, INSTANCE_NAME_2))
226
227     if not os_utils.add_floating_ip(nova_client,
228                                     instance_2.id,
229                                     floatip_server):
230         logger.error("Cannot associate floating IP to VM.")
231         sys.exit(-1)
232
233     # CREATION OF THE 2 SF ####
234
235     tacker_script = "%s/testcases/features/sfc/%s" % \
236                     (FUNCTEST_REPO, TACKER_SCRIPT)
237     logger.info("Executing tacker script: '%s'" % tacker_script)
238     subprocess.call(tacker_script, shell=True)
239
240     # SSH CALL TO START HTTP SERVER
241     ssh = paramiko.SSHClient()
242     ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
243
244     try:
245         ssh.connect(floatip_server, username="root",
246                     password="opnfv", timeout=2)
247         command = "python -m SimpleHTTPServer 80 > /dev/null 2>&1 &"
248         logger.info("Starting HTTP server")
249         (stdin, stdout, stderr) = ssh.exec_command(command)
250     except:
251         logger.debug("Waiting for %s..." % floatip_server)
252         time.sleep(6)
253         # timeout -= 1
254
255     instances = nova_client.servers.list(search_opts={'all_tenants': 1})
256     ips = []
257     try:
258         for instance in instances:
259             if "server" not in instance.name:
260                 if "client" not in instance.name:
261                     logger.debug(
262                         "This is the instance name: %s " % instance.name)
263                     floatip_dic = os_utils.create_floating_ip(neutron_client)
264                     floatip = floatip_dic['fip_addr']
265                     ips.append(floatip)
266                     instance.add_floating_ip(floatip)
267     except:
268         logger.debug("Problems assigning floating IP to SFs")
269
270     # If no IPs were obtained, then we cant continue
271     if not ips:
272         logger.error('Failed to obtain IPs, cant continue, exiting')
273         return
274
275     logger.debug("Floating IPs for SFs: %s..." % ips)
276
277     # Check SSH connectivity to VNFs
278     r = 0
279     retries = 100
280     check = [False, False]
281
282     logger.info("Checking SSH connectivity to the SFs with ips %s" % str(ips))
283     while r < retries and not all(check):
284         try:
285             check = [check_ssh(ips[0]), check_ssh(ips[1])]
286         except Exception:
287             logger.exception("SSH check failed")
288             check = [False, False]
289         time.sleep(3)
290         r += 1
291
292     logger.info("SSH connectivity to the SFs established")
293
294     if not all(check):
295         logger.error("Cannot establish SSH connection to the SFs")
296         sys.exit(1)
297
298     # SSH TO START THE VXLAN_TOOL ON SF1
299     logger.info("Configuring the SFs")
300     try:
301         ssh.connect(ips[0], username="root",
302                     password="opnfv", timeout=2)
303         command = ("nohup python vxlan_tool.py -i eth0 "
304                    "-d forward -v off -b 80 > /dev/null 2>&1 &")
305         (stdin, stdout, stderr) = ssh.exec_command(command)
306     except:
307         logger.debug("Waiting for %s..." % ips[0])
308         time.sleep(6)
309         # timeout -= 1
310
311     try:
312         while 1:
313             (stdin, stdout, stderr) = ssh.exec_command(
314                 "ps aux | grep \"vxlan_tool.py\" | grep -v grep")
315             if len(stdout.readlines()) > 0:
316                 logger.debug("HTTP firewall started")
317                 break
318             else:
319                 logger.debug("HTTP firewall not started")
320                 time.sleep(3)
321     except Exception:
322         logger.exception("vxlan_tool not started in SF1")
323
324     # SSH TO START THE VXLAN_TOOL ON SF2
325     try:
326         ssh.connect(ips[1], username="root",
327                     password="opnfv", timeout=2)
328         command = ("nohup python vxlan_tool.py -i eth0 "
329                    "-d forward -v off -b 22 > /dev/null 2>&1 &")
330         (stdin, stdout, stderr) = ssh.exec_command(command)
331     except:
332         logger.debug("Waiting for %s..." % ips[1])
333         time.sleep(6)
334         # timeout -= 1
335
336     try:
337         while 1:
338             (stdin, stdout, stderr) = ssh.exec_command(
339                 "ps aux | grep \"vxlan_tool.py\" | grep -v grep")
340             if len(stdout.readlines()) > 0:
341                 logger.debug("SSH firewall started")
342                 break
343             else:
344                 logger.debug("SSH firewall not started")
345                 time.sleep(3)
346     except Exception:
347         logger.exception("vxlan_tool not started in SF2")
348
349     # SSH to modify the classification flows in compute
350
351     contr_cmd3 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
352                   " 'ssh " + ip_compute + " 'bash correct_classifier.bash''")
353     logger.info("Executing script to modify the classi: '%s'" % contr_cmd3)
354     process = subprocess.Popen(contr_cmd3,
355                                shell=True,
356                                stdout=subprocess.PIPE)
357
358     i = 0
359
360     # SSH TO EXECUTE cmd_client
361     logger.info("TEST STARTED")
362     try:
363         ssh.connect(floatip_client, username="root",
364                     password="opnfv", timeout=2)
365         command = "nc -w 5 -zv " + instance_ip_2 + " 22 2>&1"
366         (stdin, stdout, stderr) = ssh.exec_command(command)
367
368         # WRITE THE CORRECT WAY TO DO LOGGING
369         if "timed out" in stdout.readlines()[0]:
370             logger.info('\033[92m' + "TEST 1 [PASSED] "
371                         "==> SSH BLOCKED" + '\033[0m')
372             i = i + 1
373             json_results.update({"Test 1: SSH Blocked": "Passed"})
374         else:
375             logger.error('\033[91m' + "TEST 1 [FAILED] "
376                          "==> SSH NOT BLOCKED" + '\033[0m')
377             status = "FAIL"
378             json_results.update({"Test 1: SSH Blocked": "Failed"})
379             failures += 1
380     except:
381         logger.debug("Waiting for %s..." % floatip_client)
382         time.sleep(6)
383         # timeout -= 1
384
385     # SSH TO EXECUTE cmd_client
386     try:
387         ssh.connect(floatip_client, username="root",
388                     password="opnfv", timeout=2)
389         command = "nc -w 5 -zv " + instance_ip_2 + " 80 2>&1"
390         (stdin, stdout, stderr) = ssh.exec_command(command)
391
392         if "succeeded" in stdout.readlines()[0]:
393             logger.info('\033[92m' + "TEST 2 [PASSED] "
394                         "==> HTTP WORKS" + '\033[0m')
395             i = i + 1
396             json_results.update({"Test 2: HTTP works": "Passed"})
397         else:
398             logger.error('\033[91m' + "TEST 2 [FAILED] "
399                          "==> HTTP BLOCKED" + '\033[0m')
400             status = "FAIL"
401             json_results.update({"Test 2: HTTP works": "Failed"})
402             failures += 1
403     except:
404         logger.debug("Waiting for %s..." % floatip_client)
405         time.sleep(6)
406         # timeout -= 1
407
408     # CHANGE OF CLASSIFICATION #
409     logger.info("Changing the classification")
410     tacker_classi = "%s/testcases/features/sfc/%s" % \
411                     (FUNCTEST_REPO, TACKER_CHANGECLASSI)
412     subprocess.call(tacker_classi, shell=True)
413
414     logger.info("Wait for ODL to update the classification rules in OVS")
415     time.sleep(10)
416
417     # SSH to modify the classification flows in compute
418
419     contr_cmd4 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
420                   " 'ssh " + ip_compute + " 'bash correct_classifier.bash''")
421     logger.info("Executing script to modify the classi: '%s'" % contr_cmd4)
422     process = subprocess.Popen(contr_cmd4,
423                                shell=True,
424                                stdout=subprocess.PIPE)
425
426     # SSH TO EXECUTE cmd_client
427
428     try:
429         ssh.connect(floatip_client, username="root",
430                     password="opnfv", timeout=2)
431         command = "nc -w 5 -zv " + instance_ip_2 + " 80 2>&1"
432         (stdin, stdout, stderr) = ssh.exec_command(command)
433
434         if "timed out" in stdout.readlines()[0]:
435             logger.info('\033[92m' + "TEST 3 [PASSED] "
436                         "==> HTTP BLOCKED" + '\033[0m')
437             i = i + 1
438             json_results.update({"Test 3: HTTP Blocked": "Passed"})
439         else:
440             logger.error('\033[91m' + "TEST 3 [FAILED] "
441                          "==> HTTP NOT BLOCKED" + '\033[0m')
442             status = "FAIL"
443             json_results.update({"Test 3: HTTP Blocked": "Failed"})
444             failures += 1
445     except:
446         logger.debug("Waiting for %s..." % floatip_client)
447         time.sleep(6)
448         # timeout -= 1
449
450     # SSH TO EXECUTE cmd_client
451     try:
452         ssh.connect(floatip_client, username="root",
453                     password="opnfv", timeout=2)
454         command = "nc -w 5 -zv " + instance_ip_2 + " 22 2>&1"
455         (stdin, stdout, stderr) = ssh.exec_command(command)
456
457         if "succeeded" in stdout.readlines()[0]:
458             logger.info('\033[92m' + "TEST 4 [PASSED] "
459                         "==> SSH WORKS" + '\033[0m')
460             i = i + 1
461             json_results.update({"Test 4: SSH works": "Passed"})
462         else:
463             logger.error('\033[91m' + "TEST 4 [FAILED] "
464                          "==> SSH BLOCKED" + '\033[0m')
465             status = "FAIL"
466             json_results.update({"Test 4: SSH works": "Failed"})
467             failures += 1
468     except:
469         logger.debug("Waiting for %s..." % floatip_client)
470         time.sleep(6)
471         # timeout -= 1
472
473     if i == 4:
474         for x in range(0, 5):
475             logger.info('\033[92m' + "SFC TEST WORKED"
476                         " :) \n" + '\033[0m')
477
478     if args.report:
479         stop_time = time.time()
480         json_results.update({"tests": "4", "failures": int(failures)})
481         logger.debug("Promise Results json: " + str(json_results))
482         ft_utils.push_results_to_db("sfc",
483                                     "functest-odl-sfc",
484                                     start_time,
485                                     stop_time,
486                                     status,
487                                     json_results)
488     if status == "PASS":
489         sys.exit(0)
490     else:
491         sys.exit(1)
492
493 if __name__ == '__main__':
494     main()