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