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