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