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