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