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