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