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