Fix bug in ovs utils
[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', 'udp',
160                                       port_range_min=67,
161                                       port_range_max=68)
162         os_utils.create_secgroup_rule(neutron_client, sg['id'],
163                                       'egress', 'udp',
164                                       port_range_min=67,
165                                       port_range_max=68)
166         os_utils.create_secgroup_rule(neutron_client, sg['id'],
167                                       'ingress', 'tcp',
168                                       port_range_min=22,
169                                       port_range_max=22)
170         os_utils.create_secgroup_rule(neutron_client, sg['id'],
171                                       'egress', 'tcp',
172                                       port_range_min=22,
173                                       port_range_max=22)
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         time.sleep(70)
408         try:
409             ssh.connect(floatip_client, username="root",
410                         password="opnfv", timeout=2)
411             command = "nc -w 5 -zv " + instance_ip_2 + " 22 2>&1"
412             (stdin, stdout, stderr) = ssh.exec_command(command)
413
414             # WRITE THE CORRECT WAY TO DO LOGGING
415             if "timed out" in stdout.readlines()[0]:
416                 logger.info('\033[92m' + "TEST 1 [PASSED] "
417                             "==> SSH BLOCKED" + '\033[0m')
418                 i = i + 1
419                 json_results.update({"Test 1: SSH Blocked": "Passed"})
420             else:
421                 timestamp = time.strftime("%Y%m%d-%H%M%S")
422                 error = ('\033[91m' + "TEST 1 [FAILED] "
423                          "==> SSH NOT BLOCKED" + '\033[0m')
424                 logger.error(error)
425                 ovs_logger.ofctl_dump_flows(controller_client,
426                                             timestamp=timestamp)
427                 ovs_logger.vsctl_show(controller_client,
428                                       timestamp=timestamp)
429
430                 dumpdir = os.path.join(ovs_logger.ovs_dir, timestamp)
431                 with open(os.path.join(dumpdir, 'error'), 'w') as f:
432                     f.write(error)
433                 status = "FAIL"
434                 json_results.update({"Test 1: SSH 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 + " 80 2>&1"
446             (stdin, stdout, stderr) = ssh.exec_command(command)
447
448             if "succeeded" in stdout.readlines()[0]:
449                 logger.info('\033[92m' + "TEST 2 [PASSED] "
450                             "==> HTTP WORKS" + '\033[0m')
451                 i = i + 1
452                 json_results.update({"Test 2: HTTP works": "Passed"})
453             else:
454                 error = ('\033[91m' + "TEST 2 [FAILED] "
455                          "==> HTTP BLOCKED" + '\033[0m')
456                 logger.error(error)
457                 ovs_logger.ofctl_dump_flows(controller_client,
458                                             timestamp=timestamp)
459                 ovs_logger.vsctl_show(controller_client,
460                                       timestamp=timestamp)
461
462                 dumpdir = os.path.join(ovs_logger.ovs_dir, timestamp)
463                 with open(os.path.join(dumpdir, 'error'), 'w') as f:
464                     f.write(error)
465                 status = "FAIL"
466                 json_results.update({"Test 2: HTTP works": "Failed"})
467                 failures += 1
468         except:
469             logger.debug("Waiting for %s..." % floatip_client)
470             time.sleep(6)
471             # timeout -= 1
472
473         # CHANGE OF CLASSIFICATION #
474         logger.info("Changing the classification")
475         tacker_classi = "%s/testcases/features/sfc/%s" % \
476                         (FUNCTEST_REPO, TACKER_CHANGECLASSI)
477         subprocess.call(tacker_classi, shell=True)
478
479         logger.info("Wait for ODL to update the classification rules in OVS")
480         time.sleep(100)
481
482         # SSH TO EXECUTE cmd_client
483
484         try:
485             ssh.connect(floatip_client, username="root",
486                         password="opnfv", timeout=2)
487             command = "nc -w 5 -zv " + instance_ip_2 + " 80 2>&1"
488             (stdin, stdout, stderr) = ssh.exec_command(command)
489
490             if "timed out" in stdout.readlines()[0]:
491                 logger.info('\033[92m' + "TEST 3 [PASSED] "
492                             "==> HTTP BLOCKED" + '\033[0m')
493                 i = i + 1
494                 json_results.update({"Test 3: HTTP Blocked": "Passed"})
495             else:
496                 error = ('\033[91m' + "TEST 3 [FAILED] "
497                          "==> HTTP NOT BLOCKED" + '\033[0m')
498                 logger.error(error)
499                 ovs_logger.ofctl_dump_flows(controller_client,
500                                             timestamp=timestamp)
501                 ovs_logger.vsctl_show(controller_client,
502                                       timestamp=timestamp)
503
504                 dumpdir = os.path.join(ovs_logger.ovs_dir, timestamp)
505                 with open(os.path.join(dumpdir, 'error'), 'w') as f:
506                     f.write(error)
507                 status = "FAIL"
508                 json_results.update({"Test 3: HTTP Blocked": "Failed"})
509                 failures += 1
510         except:
511             logger.debug("Waiting for %s..." % floatip_client)
512             time.sleep(6)
513             # timeout -= 1
514
515         # SSH TO EXECUTE cmd_client
516         try:
517             ssh.connect(floatip_client, username="root",
518                         password="opnfv", timeout=2)
519             command = "nc -w 5 -zv " + instance_ip_2 + " 22 2>&1"
520             (stdin, stdout, stderr) = ssh.exec_command(command)
521
522             if "succeeded" in stdout.readlines()[0]:
523                 logger.info('\033[92m' + "TEST 4 [PASSED] "
524                             "==> SSH WORKS" + '\033[0m')
525                 i = i + 1
526                 json_results.update({"Test 4: SSH works": "Passed"})
527             else:
528                 error = ('\033[91m' + "TEST 4 [FAILED] "
529                          "==> SSH BLOCKED" + '\033[0m')
530                 logger.error(error)
531                 ovs_logger.ofctl_dump_flows(controller_client,
532                                             timestamp=timestamp)
533                 ovs_logger.vsctl_show(controller_client,
534                                       timestamp=timestamp)
535
536                 dumpdir = os.path.join(ovs_logger.ovs_dir, timestamp)
537                 with open(os.path.join(dumpdir, 'error'), 'w') as f:
538                     f.write(error)
539                 status = "FAIL"
540                 json_results.update({"Test 4: SSH works": "Failed"})
541                 failures += 1
542         except:
543             logger.debug("Waiting for %s..." % floatip_client)
544             time.sleep(6)
545             # timeout -= 1
546
547         iterator += 1
548         if i == 4:
549             for x in range(0, 5):
550                 logger.info('\033[92m' + "SFC TEST WORKED"
551                             " :) \n" + '\033[0m')
552             break
553         else:
554             logger.info("Iterating again!")
555             delete = "bash %s/testcases/features/sfc/delete.sh" % \
556                      (FUNCTEST_REPO)
557             try:
558                 subprocess.call(delete, shell=True, stderr=subprocess.PIPE)
559                 time.sleep(10)
560             except Exception, e:
561                 logger.error("Problem when executing the delete.sh")
562                 logger.error("Problem %s" % e)
563
564     if args.report:
565         stop_time = time.time()
566         json_results.update({"tests": "4", "failures": int(failures)})
567         logger.debug("Promise Results json: " + str(json_results))
568         ft_utils.push_results_to_db("sfc",
569                                     "functest-odl-sfc",
570                                     start_time,
571                                     stop_time,
572                                     status,
573                                     json_results)
574     if status == "PASS":
575         sys.exit(0)
576     else:
577         sys.exit(1)
578
579 if __name__ == '__main__':
580     main()