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
11 import SSHUtils as ssh_utils
15 parser = argparse.ArgumentParser()
17 parser.add_argument("-r", "--report",
18 help="Create json result file",
21 args = parser.parse_args()
23 """ logging configuration """
24 logger = ft_logger.Logger("ODL_SFC").getLogger()
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'] + "/"
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
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}
59 # run given command locally and return commands output if success
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)
68 (output, errors) = pipe.communicate()
70 output = output.strip()
71 if pipe.returncode < 0:
87 # run given command on OpenStack controller
90 def run_cmd_on_cntlr(cmd):
91 ip_cntlrs = get_openstack_node_ips("controller")
95 ssh_cmd = "ssh %s %s %s" % (ssh_options, ip_cntlrs[0], cmd)
96 return run_cmd_on_fm(ssh_cmd)
98 # run given command on OpenStack Compute node
101 def run_cmd_on_compute(cmd):
102 ip_computes = get_openstack_node_ips("compute")
106 ssh_cmd = "ssh %s %s %s" % (ssh_options, ip_computes[0], cmd)
107 return run_cmd_on_fm(ssh_cmd)
109 # run given command on Fuel Master
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)
118 # run given command on Remote Machine, Can be VM
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)
127 # Get OpenStack Nodes IP Address
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
135 cmd = "fuel2 node list -f json"
137 nodes = run_cmd_on_fm(cmd)
139 nodes = json.loads(nodes)
141 if role in node["roles"]:
142 ips.append(node["ip"])
146 # Configures IPTABLES on OpenStack Controller
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"]
155 for cmd in iptable_cmds:
156 logger.info("Configuring %s on contoller" % cmd)
157 run_cmd_on_cntlr(cmd)
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)
167 logger.info("Using old image")
171 def setup_glance(glance_client):
172 image_id = os_utils.create_glance_image(glance_client,
182 def setup_neutron(neutron_client):
183 n_dict = os_utils.create_network_full(neutron_client,
189 logger.error("failed to create neutron network")
192 network_id = n_dict["net_id"]
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)
200 os_utils.create_secgroup_rule(neutron_client, sg['id'],
202 port_range_min=min_port,
203 port_range_max=max_port)
204 os_utils.create_secgroup_rule(neutron_client, sg['id'],
206 port_range_min=min_port,
207 port_range_max=max_port)
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)
221 def boot_instance(nova_client, name, flavor, image_id, network_id, sg_id):
222 logger.info("Creating instance '%s'..." % name)
224 "Configuration:\n name=%s \n flavor=%s \n image=%s \n "
225 "network=%s \n" % (name, flavor, image_id, network_id))
227 instance = os_utils.create_instance_and_wait_for_active(flavor,
233 logger.error("Error while booting instance.")
236 instance_ip = instance.networks.get(NET_NAME)[0]
237 logger.debug("Instance '%s' got private ip '%s'." %
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)
246 def ping(remote, pkt_cnt=1, iface=None, retries=100, timeout=None):
250 ping_cmd = ping_cmd + ' -w %s' % timeout
252 grep_cmd = "grep -e 'packet loss' -e rtt"
254 if iface is not None:
255 ping_cmd = ping_cmd + ' -I %s' % iface
257 ping_cmd = ping_cmd + ' -i 0 -c %d %s' % (pkt_cnt, remote)
258 cmd = ping_cmd + '|' + grep_cmd
261 output = run_cmd(cmd)
265 match = re.search('(\d*)% packet loss', output)
269 packet_loss = int(match.group(1))
273 retries = retries - 1
278 def get_floating_ips(nova_client, neutron_client):
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))
293 if instance.name == "server":
294 logger.info("Server:%s is reachable" % floatip)
296 elif instance.name == "client":
297 logger.info("Client:%s is reachable" % floatip)
300 logger.info("SF:%s is reachable" % floatip)
303 return server_ip, client_ip, ips[1], ips[0]
305 # Start http server on a give machine, Can be VM
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)
313 # Set firewall using vxlan_tool.py on a give machine, Can be VM
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"
320 cmd = "python vxlan_tool.py -i eth0 -d forward -v off -b " + port
322 cmd = "sh -c 'cd /root;nohup " + cmd + " > /dev/null 2>&1 &'"
323 run_cmd_remote(sf, cmd)
325 # Run netcat on a give machine, Can be VM
328 def netcat(s_ip, c_ip, port="80", timeout=5):
330 cmd = cmd + " -w %s %s %s" % (timeout, s_ip, port)
332 output = run_cmd_remote(c_ip, cmd)
333 logger.info("%s" % output)
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)
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)
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)
360 timestamp = time.strftime("%Y%m%d-%H%M%S")
361 ovs_logger.dump_ovs_logs(controller_clients,
368 def update_json_results(name, result):
369 json_results.update({name: result})
370 if result is not "Passed":
371 json_results["failures"] += 1
376 def get_ssh_clients(role):
378 for ip in get_openstack_node_ips(role):
379 s_client = ssh_utils.get_ssh_client(ip,
382 clients.append(s_client)
386 # Check SSH connectivity to VNFs
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")
397 logger.info("SSH connectivity to the SFs established")
405 # Measure the time it takes to update the classification rules
408 def capture_time_log(compute_clients):
409 ovs_logger = ovs_utils.OVSLogger(
410 os.path.join(os.getcwd(), 'ovs-logs'),
414 start_time = time.time()
416 rsps = ovs_logger.ofctl_time_counter(compute_clients[0])
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)
437 installer_type = os.environ.get("INSTALLER_TYPE")
438 if installer_type != "fuel":
440 '\033[91mCurrently supported only Fuel Installer type\033[0m')
443 installer_ip = os.environ.get("INSTALLER_IP")
446 '\033[91minstaller ip is not set\033[0m')
448 '\033[91mexport INSTALLER_IP=<ip>\033[0m')
451 start_time = time.time()
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")
461 glance_client = os_utils.get_glance_client()
462 neutron_client = os_utils.get_neutron_client()
463 nova_client = os_utils.get_nova_client()
465 controller_clients = get_ssh_clients("controller")
466 compute_clients = get_ssh_clients("compute")
468 image_id = setup_glance(glance_client)
469 network_id = setup_neutron(neutron_client)
470 sg_id = setup_security_groups(neutron_client)
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)
477 subprocess.call(TACKER_SCRIPT, shell=True)
479 # Start measuring the time it takes to implement the classification rules
481 thread.start_new_thread(capture_time_log, (compute_clients,))
483 logger.error("Unable to start the thread that counts time %s" % e)
485 server_ip, client_ip, sf1, sf2 = get_floating_ips(
486 nova_client, neutron_client)
488 if not check_ssh([sf1, sf2]):
489 logger.error("Cannot establish SSH connection to the SFs")
492 logger.info("Starting HTTP server on %s" % server_ip)
493 if not start_http_server(server_ip):
495 '\033[91mFailed to start HTTP server on %s\033[0m' % server_ip)
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")
503 logger.info("Wait for ODL to update the classification rules in OVS")
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")
511 error = ('\033[91mTEST 1 [FAILED] ==> SSH NOT BLOCKED\033[0m')
513 capture_err_logs(controller_clients, compute_clients, error)
514 update_json_results("Test 1: SSH Blocked", "Failed")
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")
521 error = ('\033[91mTEST 2 [FAILED] ==> HTTP BLOCKED\033[0m')
523 capture_err_logs(controller_clients, compute_clients, error)
524 update_json_results("Test 2: HTTP works", "Failed")
526 logger.info("Changing the classification")
527 subprocess.call(TACKER_CHANGECLASSI, shell=True)
529 # Start measuring the time it takes to implement the classification rules
531 thread.start_new_thread(capture_time_log, (compute_clients,))
533 logger.error("Unable to start the thread that counts time %s" % e)
535 logger.info("Wait for ODL to update the classification rules in OVS")
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")
543 error = ('\033[91mTEST 3 [FAILED] ==> HTTP WORKS\033[0m')
545 capture_err_logs(controller_clients, compute_clients, error)
546 update_json_results("Test 3: HTTP Blocked", "Failed")
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")
553 error = ('\033[91mTEST 4 [FAILED] ==> SSH BLOCKED\033[0m')
555 capture_err_logs(controller_clients, compute_clients, error)
556 update_json_results("Test 4: SSH Works", "Failed")
558 if json_results["failures"]:
560 logger.error('\033[91mSFC TESTS: %s :( FOUND %s FAIL \033[0m' % (
561 status, json_results["failures"]))
564 stop_time = time.time()
565 logger.debug("Promise Results json: " + str(json_results))
566 ft_utils.push_results_to_db("sfc",
574 logger.info('\033[92mSFC ALL TESTS: %s :)\033[0m' % status)
579 if __name__ == '__main__':