Bug fix odl-sfc
[functest.git] / testcases / features / sfc / sfc.py
1 import argparse
2 import os
3 import subprocess
4 import sys
5 import time
6 import functest.utils.functest_logger as ft_logger
7 import functest.utils.functest_utils as ft_utils
8 import functest.utils.openstack_utils as os_utils
9 import re
10 import json
11 import SSHUtils as ssh_utils
12 import ovs_utils
13 import thread
14
15 parser = argparse.ArgumentParser()
16
17 parser.add_argument("-r", "--report",
18                     help="Create json result file",
19                     action="store_true")
20
21 args = parser.parse_args()
22
23 """ logging configuration """
24 logger = ft_logger.Logger("ODL_SFC").getLogger()
25
26 FUNCTEST_RESULTS_DIR = '/home/opnfv/functest/results/odl-sfc'
27 FUNCTEST_REPO = ft_utils.FUNCTEST_REPO
28 REPO_PATH = os.environ['repos_dir'] + '/functest/'
29 HOME = os.environ['HOME'] + "/"
30 CLIENT = "client"
31 SERVER = "server"
32 FLAVOR = "custom"
33 IMAGE_NAME = "sf_nsh_colorado"
34 IMAGE_FILENAME = "sf_nsh_colorado.qcow2"
35 IMAGE_FORMAT = "qcow2"
36 IMAGE_DIR = "/home/opnfv/functest/data"
37 IMAGE_PATH = IMAGE_DIR + "/" + IMAGE_FILENAME
38 IMAGE_URL = "http://artifacts.opnfv.org/sfc/demo/" + IMAGE_FILENAME
39
40 # NEUTRON Private Network parameters
41 NET_NAME = "example-net"
42 SUBNET_NAME = "example-subnet"
43 SUBNET_CIDR = "11.0.0.0/24"
44 ROUTER_NAME = "example-router"
45 SECGROUP_NAME = "example-sg"
46 SECGROUP_DESCR = "Example Security group"
47 SFC_TEST_DIR = REPO_PATH + "/testcases/features/sfc/"
48 TACKER_SCRIPT = SFC_TEST_DIR + "sfc_tacker.bash"
49 TACKER_CHANGECLASSI = SFC_TEST_DIR + "sfc_change_classi.bash"
50 ssh_options = '-q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'
51 json_results = {"tests": 4, "failures": 0}
52
53 PROXY = {
54     'ip': '10.20.0.2',
55     'username': 'root',
56     'password': 'r00tme'
57 }
58
59 # run given command locally and return commands output if success
60
61
62 def run_cmd(cmd, wdir=None, ignore_stderr=False, ignore_no_output=True):
63     pipe = subprocess.Popen(cmd, shell=True,
64                             stdin=subprocess.PIPE,
65                             stdout=subprocess.PIPE,
66                             stderr=subprocess.PIPE, cwd=wdir)
67
68     (output, errors) = pipe.communicate()
69     if output:
70         output = output.strip()
71     if pipe.returncode < 0:
72         logger.error(errors)
73         return False
74     if errors:
75         logger.error(errors)
76         if ignore_stderr:
77             return True
78         else:
79             return False
80
81     if ignore_no_output:
82         if not output:
83             return True
84
85     return output
86
87 # run given command on OpenStack controller
88
89
90 def run_cmd_on_cntlr(cmd):
91     ip_cntlrs = get_openstack_node_ips("controller")
92     if not ip_cntlrs:
93         return None
94
95     ssh_cmd = "ssh %s %s %s" % (ssh_options, ip_cntlrs[0], cmd)
96     return run_cmd_on_fm(ssh_cmd)
97
98 # run given command on OpenStack Compute node
99
100
101 def run_cmd_on_compute(cmd):
102     ip_computes = get_openstack_node_ips("compute")
103     if not ip_computes:
104         return None
105
106     ssh_cmd = "ssh %s %s %s" % (ssh_options, ip_computes[0], cmd)
107     return run_cmd_on_fm(ssh_cmd)
108
109 # run given command on Fuel Master
110
111
112 def run_cmd_on_fm(cmd, username="root", passwd="r00tme"):
113     ip = os.environ.get("INSTALLER_IP")
114     ssh_cmd = "sshpass -p %s ssh %s %s@%s %s" % (
115         passwd, ssh_options, username, ip, cmd)
116     return run_cmd(ssh_cmd)
117
118 # run given command on Remote Machine, Can be VM
119
120
121 def run_cmd_remote(ip, cmd, username="root", passwd="opnfv"):
122     ssh_opt_append = "%s -o ConnectTimeout=50 " % ssh_options
123     ssh_cmd = "sshpass -p %s ssh %s %s@%s %s" % (
124         passwd, ssh_opt_append, username, ip, cmd)
125     return run_cmd(ssh_cmd)
126
127 # Get OpenStack Nodes IP Address
128
129
130 def get_openstack_node_ips(role):
131     fuel_env = os.environ.get("FUEL_ENV")
132     if fuel_env is not None:
133         cmd = "fuel2 node list -f json -e %s" % fuel_env
134     else:
135         cmd = "fuel2 node list -f json"
136
137     nodes = run_cmd_on_fm(cmd)
138     ips = []
139     nodes = json.loads(nodes)
140     for node in nodes:
141         if role in node["roles"]:
142             ips.append(node["ip"])
143
144     return ips
145
146 # Configures IPTABLES on OpenStack Controller
147
148
149 def configure_iptables():
150     iptable_cmds = ["iptables -P INPUT ACCEPT",
151                     "iptables -t nat -P INPUT ACCEPT",
152                     "iptables -A INPUT -m state \
153                     --state NEW,ESTABLISHED,RELATED -j ACCEPT"]
154
155     for cmd in iptable_cmds:
156         logger.info("Configuring %s on contoller" % cmd)
157         run_cmd_on_cntlr(cmd)
158
159     return
160
161
162 def download_image():
163     if not os.path.isfile(IMAGE_PATH):
164         logger.info("Downloading image")
165         ft_utils.download_url(IMAGE_URL, IMAGE_DIR)
166
167     logger.info("Using old image")
168     return
169
170
171 def setup_glance(glance_client):
172     image_id = os_utils.create_glance_image(glance_client,
173                                             IMAGE_NAME,
174                                             IMAGE_PATH,
175                                             disk=IMAGE_FORMAT,
176                                             container="bare",
177                                             public=True)
178
179     return image_id
180
181
182 def setup_neutron(neutron_client):
183     n_dict = os_utils.create_network_full(neutron_client,
184                                           NET_NAME,
185                                           SUBNET_NAME,
186                                           ROUTER_NAME,
187                                           SUBNET_CIDR)
188     if not n_dict:
189         logger.error("failed to create neutron network")
190         sys.exit(-1)
191
192     network_id = n_dict["net_id"]
193     return network_id
194
195
196 def setup_ingress_egress_secgroup(neutron_client, protocol,
197                                   min_port=None, max_port=None):
198     secgroups = os_utils.get_security_groups(neutron_client)
199     for sg in secgroups:
200         os_utils.create_secgroup_rule(neutron_client, sg['id'],
201                                       'ingress', protocol,
202                                       port_range_min=min_port,
203                                       port_range_max=max_port)
204         os_utils.create_secgroup_rule(neutron_client, sg['id'],
205                                       'egress', protocol,
206                                       port_range_min=min_port,
207                                       port_range_max=max_port)
208     return
209
210
211 def setup_security_groups(neutron_client):
212     sg_id = os_utils.create_security_group_full(neutron_client,
213                                                 SECGROUP_NAME, SECGROUP_DESCR)
214     setup_ingress_egress_secgroup(neutron_client, "icmp")
215     setup_ingress_egress_secgroup(neutron_client, "udp", 67, 68)
216     setup_ingress_egress_secgroup(neutron_client, "tcp", 22, 22)
217     setup_ingress_egress_secgroup(neutron_client, "tcp", 80, 80)
218     return sg_id
219
220
221 def boot_instance(nova_client, name, flavor, image_id, network_id, sg_id):
222     logger.info("Creating instance '%s'..." % name)
223     logger.debug(
224         "Configuration:\n name=%s \n flavor=%s \n image=%s \n "
225         "network=%s \n" % (name, flavor, image_id, network_id))
226
227     instance = os_utils.create_instance_and_wait_for_active(flavor,
228                                                             image_id,
229                                                             network_id,
230                                                             name)
231
232     if instance is None:
233         logger.error("Error while booting instance.")
234         sys.exit(-1)
235
236     instance_ip = instance.networks.get(NET_NAME)[0]
237     logger.debug("Instance '%s' got private ip '%s'." %
238                  (name, instance_ip))
239
240     logger.info("Adding '%s' to security group %s" % (name, SECGROUP_NAME))
241     os_utils.add_secgroup_to_instance(nova_client, instance.id, sg_id)
242
243     return instance_ip
244
245
246 def ping(remote, pkt_cnt=1, iface=None, retries=100, timeout=None):
247     ping_cmd = 'ping'
248
249     if timeout:
250         ping_cmd = ping_cmd + ' -w %s' % timeout
251
252     grep_cmd = "grep -e 'packet loss' -e rtt"
253
254     if iface is not None:
255         ping_cmd = ping_cmd + ' -I %s' % iface
256
257     ping_cmd = ping_cmd + ' -i 0 -c %d %s' % (pkt_cnt, remote)
258     cmd = ping_cmd + '|' + grep_cmd
259
260     while retries > 0:
261         output = run_cmd(cmd)
262         if not output:
263             return False
264
265         match = re.search('(\d*)% packet loss', output)
266         if not match:
267             return False
268
269         packet_loss = int(match.group(1))
270         if packet_loss == 0:
271             return True
272
273         retries = retries - 1
274
275     return False
276
277
278 def get_floating_ips(nova_client, neutron_client):
279     ips = []
280     instances = nova_client.servers.list(search_opts={'all_tenants': 1})
281     for instance in instances:
282         floatip_dic = os_utils.create_floating_ip(neutron_client)
283         floatip = floatip_dic['fip_addr']
284         instance.add_floating_ip(floatip)
285         logger.info("Instance name and ip %s:%s " % (instance.name, floatip))
286         logger.info("Waiting for instance %s:%s to come up" %
287                     (instance.name, floatip))
288         if not ping(floatip):
289             logger.info("Instance %s:%s didn't come up" %
290                         (instance.name, floatip))
291             sys.exit(1)
292
293         if instance.name == "server":
294             logger.info("Server:%s is reachable" % floatip)
295             server_ip = floatip
296         elif instance.name == "client":
297             logger.info("Client:%s is reachable" % floatip)
298             client_ip = floatip
299         else:
300             logger.info("SF:%s is reachable" % floatip)
301             ips.append(floatip)
302
303     return server_ip, client_ip, ips[1], ips[0]
304
305 # Start http server on a give machine, Can be VM
306
307
308 def start_http_server(ip):
309     cmd = "\'python -m SimpleHTTPServer 80"
310     cmd = cmd + " > /dev/null 2>&1 &\'"
311     return run_cmd_remote(ip, cmd)
312
313 # Set firewall using vxlan_tool.py on a give machine, Can be VM
314
315
316 def vxlan_firewall(sf, iface="eth0", port="22", block=True):
317     cmd = "python vxlan_tool.py"
318     cmd = cmd + " -i " + iface + " -d forward -v off"
319     if block:
320         cmd = "python vxlan_tool.py -i eth0 -d forward -v off -b " + port
321
322     cmd = "sh -c 'cd /root;nohup " + cmd + " > /dev/null 2>&1 &'"
323     run_cmd_remote(sf, cmd)
324
325 # Run netcat on a give machine, Can be VM
326
327
328 def netcat(s_ip, c_ip, port="80", timeout=5):
329     cmd = "nc -zv "
330     cmd = cmd + " -w %s %s %s" % (timeout, s_ip, port)
331     cmd = cmd + " 2>&1"
332     output = run_cmd_remote(c_ip, cmd)
333     logger.info("%s" % output)
334     return output
335
336
337 def is_ssh_blocked(srv_prv_ip, client_ip):
338     res = netcat(srv_prv_ip, client_ip, port="22")
339     match = re.search("nc:.*timed out:.*", res, re.M)
340     if match:
341         return True
342
343     return False
344
345
346 def is_http_blocked(srv_prv_ip, client_ip):
347     res = netcat(srv_prv_ip, client_ip, port="80")
348     match = re.search(".* 80 port.* succeeded!", res, re.M)
349     if match:
350         return False
351
352     return True
353
354
355 def capture_err_logs(controller_clients, compute_clients, error):
356     ovs_logger = ovs_utils.OVSLogger(
357         os.path.join(os.getcwd(), 'ovs-logs'),
358         FUNCTEST_RESULTS_DIR)
359
360     timestamp = time.strftime("%Y%m%d-%H%M%S")
361     ovs_logger.dump_ovs_logs(controller_clients,
362                              compute_clients,
363                              related_error=error,
364                              timestamp=timestamp)
365     return
366
367
368 def update_json_results(name, result):
369     json_results.update({name: result})
370     if result is not "Passed":
371         json_results["failures"] += 1
372
373     return
374
375
376 def get_ssh_clients(role):
377     clients = []
378     for ip in get_openstack_node_ips(role):
379         s_client = ssh_utils.get_ssh_client(ip,
380                                             'root',
381                                             proxy=PROXY)
382         clients.append(s_client)
383
384     return clients
385
386 # Check SSH connectivity to VNFs
387
388
389 def check_ssh(ips, retries=100):
390     check = [False, False]
391     logger.info("Checking SSH connectivity to the SFs with ips %s" % str(ips))
392     while retries and not all(check):
393         for index, ip in enumerate(ips):
394             check[index] = run_cmd_remote(ip, "exit")
395
396         if all(check):
397             logger.info("SSH connectivity to the SFs established")
398             return True
399
400         time.sleep(3)
401         retries -= 1
402
403     return False
404
405 # Measure the time it takes to update the classification rules
406
407
408 def capture_time_log(compute_clients):
409     ovs_logger = ovs_utils.OVSLogger(
410         os.path.join(os.getcwd(), 'ovs-logs'),
411         "test")
412     i = 0
413     first_RSP = ""
414     start_time = time.time()
415     while True:
416         rsps = ovs_logger.ofctl_time_counter(compute_clients[0])
417         if not i:
418             if len(rsps) > 0:
419                 first_RSP = rsps[0]
420                 i = i + 1
421             else:
422                 first_RSP = 0
423                 i = i + 1
424         if (len(rsps) > 1):
425             if(first_RSP != rsps[0]):
426                 if (rsps[0] == rsps[1]):
427                     stop_time = time.time()
428                     logger.info("classification rules updated")
429                     difference = stop_time - start_time
430                     logger.info("It took %s seconds" % difference)
431                     break
432         time.sleep(1)
433     return
434
435
436 def main():
437     installer_type = os.environ.get("INSTALLER_TYPE")
438     if installer_type != "fuel":
439         logger.error(
440             '\033[91mCurrently supported only Fuel Installer type\033[0m')
441         sys.exit(1)
442
443     installer_ip = os.environ.get("INSTALLER_IP")
444     if not installer_ip:
445         logger.error(
446             '\033[91minstaller ip is not set\033[0m')
447         logger.error(
448             '\033[91mexport INSTALLER_IP=<ip>\033[0m')
449         sys.exit(1)
450
451     start_time = time.time()
452     status = "PASS"
453     configure_iptables()
454     download_image()
455     _, custom_flv_id = os_utils.get_or_create_flavor(
456         FLAVOR, 1500, 10, 1, public=True)
457     if not custom_flv_id:
458         logger.error("Failed to create custom flavor")
459         sys.exit(1)
460
461     glance_client = os_utils.get_glance_client()
462     neutron_client = os_utils.get_neutron_client()
463     nova_client = os_utils.get_nova_client()
464
465     controller_clients = get_ssh_clients("controller")
466     compute_clients = get_ssh_clients("compute")
467
468     image_id = setup_glance(glance_client)
469     network_id = setup_neutron(neutron_client)
470     sg_id = setup_security_groups(neutron_client)
471
472     boot_instance(
473         nova_client, CLIENT, FLAVOR, image_id, network_id, sg_id)
474     srv_prv_ip = boot_instance(
475         nova_client, SERVER, FLAVOR, image_id, network_id, sg_id)
476
477     subprocess.call(TACKER_SCRIPT, shell=True)
478
479     # Start measuring the time it takes to implement the classification rules
480     try:
481         thread.start_new_thread(capture_time_log, (compute_clients,))
482     except Exception, e:
483         logger.error("Unable to start the thread that counts time %s" % e)
484
485     server_ip, client_ip, sf1, sf2 = get_floating_ips(
486         nova_client, neutron_client)
487
488     if not check_ssh([sf1, sf2]):
489         logger.error("Cannot establish SSH connection to the SFs")
490         sys.exit(1)
491
492     logger.info("Starting HTTP server on %s" % server_ip)
493     if not start_http_server(server_ip):
494         logger.error(
495             '\033[91mFailed to start HTTP server on %s\033[0m' % server_ip)
496         sys.exit(1)
497
498     logger.info("Starting HTTP firewall on %s" % sf2)
499     vxlan_firewall(sf2, port="80")
500     logger.info("Starting SSH firewall on %s" % sf1)
501     vxlan_firewall(sf1, port="22")
502
503     logger.info("Wait for ODL to update the classification rules in OVS")
504     time.sleep(120)
505
506     logger.info("Test SSH")
507     if is_ssh_blocked(srv_prv_ip, client_ip):
508         logger.info('\033[92mTEST 1 [PASSED] ==> SSH BLOCKED\033[0m')
509         update_json_results("Test 1: SSH Blocked", "Passed")
510     else:
511         error = ('\033[91mTEST 1 [FAILED] ==> SSH NOT BLOCKED\033[0m')
512         logger.error(error)
513         capture_err_logs(controller_clients, compute_clients, error)
514         update_json_results("Test 1: SSH Blocked", "Failed")
515
516     logger.info("Test HTTP")
517     if not is_http_blocked(srv_prv_ip, client_ip):
518         logger.info('\033[92mTEST 2 [PASSED] ==> HTTP WORKS\033[0m')
519         update_json_results("Test 2: HTTP works", "Passed")
520     else:
521         error = ('\033[91mTEST 2 [FAILED] ==> HTTP BLOCKED\033[0m')
522         logger.error(error)
523         capture_err_logs(controller_clients, compute_clients, error)
524         update_json_results("Test 2: HTTP works", "Failed")
525
526     logger.info("Changing the classification")
527     subprocess.call(TACKER_CHANGECLASSI, shell=True)
528
529     # Start measuring the time it takes to implement the classification rules
530     try:
531         thread.start_new_thread(capture_time_log, (compute_clients,))
532     except Exception, e:
533         logger.error("Unable to start the thread that counts time %s" % e)
534
535     logger.info("Wait for ODL to update the classification rules in OVS")
536     time.sleep(100)
537
538     logger.info("Test HTTP")
539     if is_http_blocked(srv_prv_ip, client_ip):
540         logger.info('\033[92mTEST 3 [PASSED] ==> HTTP Blocked\033[0m')
541         update_json_results("Test 3: HTTP Blocked", "Passed")
542     else:
543         error = ('\033[91mTEST 3 [FAILED] ==> HTTP WORKS\033[0m')
544         logger.error(error)
545         capture_err_logs(controller_clients, compute_clients, error)
546         update_json_results("Test 3: HTTP Blocked", "Failed")
547
548     logger.info("Test SSH")
549     if not is_ssh_blocked(srv_prv_ip, client_ip):
550         logger.info('\033[92mTEST 4 [PASSED] ==> SSH Works\033[0m')
551         update_json_results("Test 4: SSH Works", "Passed")
552     else:
553         error = ('\033[91mTEST 4 [FAILED] ==> SSH BLOCKED\033[0m')
554         logger.error(error)
555         capture_err_logs(controller_clients, compute_clients, error)
556         update_json_results("Test 4: SSH Works", "Failed")
557
558     if json_results["failures"]:
559         status = "FAIL"
560         logger.error('\033[91mSFC TESTS: %s :( FOUND %s FAIL \033[0m' % (
561             status, json_results["failures"]))
562
563     if args.report:
564         stop_time = time.time()
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
573     if status == "PASS":
574         logger.info('\033[92mSFC ALL TESTS: %s :)\033[0m' % status)
575         sys.exit(0)
576
577     sys.exit(1)
578
579 if __name__ == '__main__':
580     main()