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.path.join(os.environ['repos_dir'], 'functest/')
32 IMAGE_NAME = "sf_nsh_colorado"
33 IMAGE_FILENAME = "sf_nsh_colorado.qcow2"
34 IMAGE_FORMAT = "qcow2"
35 IMAGE_DIR = "/home/opnfv/functest/data"
36 IMAGE_PATH = os.path.join(IMAGE_DIR, IMAGE_FILENAME)
37 IMAGE_URL = "http://artifacts.opnfv.org/sfc/demo/" + IMAGE_FILENAME
39 # NEUTRON Private Network parameters
40 NET_NAME = "example-net"
41 SUBNET_NAME = "example-subnet"
42 SUBNET_CIDR = "11.0.0.0/24"
43 ROUTER_NAME = "example-router"
44 SECGROUP_NAME = "example-sg"
45 SECGROUP_DESCR = "Example Security group"
46 SFC_TEST_DIR = os.path.join(REPO_PATH, "functest/opnfv_tests/features/sfc/")
47 TACKER_SCRIPT = SFC_TEST_DIR + "sfc_tacker.bash"
48 TACKER_CHANGECLASSI = SFC_TEST_DIR + "sfc_change_classi.bash"
49 ssh_options = '-q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'
50 json_results = {"tests": 4, "failures": 0}
58 # run given command locally and return commands output if success
61 def run_cmd(cmd, wdir=None, ignore_stderr=False, ignore_no_output=True):
62 pipe = subprocess.Popen(cmd, shell=True,
63 stdin=subprocess.PIPE,
64 stdout=subprocess.PIPE,
65 stderr=subprocess.PIPE, cwd=wdir)
67 (output, errors) = pipe.communicate()
69 output = output.strip()
70 if pipe.returncode < 0:
86 # run given command on OpenStack controller
89 def run_cmd_on_cntlr(cmd):
90 ip_cntlrs = get_openstack_node_ips("controller")
94 ssh_cmd = "ssh %s %s %s" % (ssh_options, ip_cntlrs[0], cmd)
95 return run_cmd_on_fm(ssh_cmd)
97 # run given command on OpenStack Compute node
100 def run_cmd_on_compute(cmd):
101 ip_computes = get_openstack_node_ips("compute")
105 ssh_cmd = "ssh %s %s %s" % (ssh_options, ip_computes[0], cmd)
106 return run_cmd_on_fm(ssh_cmd)
108 # run given command on Fuel Master
111 def run_cmd_on_fm(cmd, username="root", passwd="r00tme"):
112 ip = os.environ.get("INSTALLER_IP")
113 ssh_cmd = "sshpass -p %s ssh %s %s@%s %s" % (
114 passwd, ssh_options, username, ip, cmd)
115 return run_cmd(ssh_cmd)
117 # run given command on Remote Machine, Can be VM
120 def run_cmd_remote(ip, cmd, username="root", passwd="opnfv"):
121 ssh_opt_append = "%s -o ConnectTimeout=50 " % ssh_options
122 ssh_cmd = "sshpass -p %s ssh %s %s@%s %s" % (
123 passwd, ssh_opt_append, username, ip, cmd)
124 return run_cmd(ssh_cmd)
126 # Get OpenStack Nodes IP Address
129 def get_openstack_node_ips(role):
130 fuel_env = os.environ.get("FUEL_ENV")
131 if fuel_env is not None:
132 cmd = "fuel2 node list -f json -e %s" % fuel_env
134 cmd = "fuel2 node list -f json"
136 nodes = run_cmd_on_fm(cmd)
138 nodes = json.loads(nodes)
140 if role in node["roles"]:
141 ips.append(node["ip"])
145 # Configures IPTABLES on OpenStack Controller
148 def configure_iptables():
149 iptable_cmds = ["iptables -P INPUT ACCEPT",
150 "iptables -t nat -P INPUT ACCEPT",
151 "iptables -A INPUT -m state \
152 --state NEW,ESTABLISHED,RELATED -j ACCEPT"]
154 for cmd in iptable_cmds:
155 logger.info("Configuring %s on contoller" % cmd)
156 run_cmd_on_cntlr(cmd)
161 def download_image():
162 if not os.path.isfile(IMAGE_PATH):
163 logger.info("Downloading image")
164 ft_utils.download_url(IMAGE_URL, IMAGE_DIR)
166 logger.info("Using old image")
170 def setup_glance(glance_client):
171 image_id = os_utils.create_glance_image(glance_client,
181 def setup_neutron(neutron_client):
182 n_dict = os_utils.create_network_full(neutron_client,
188 logger.error("failed to create neutron network")
191 network_id = n_dict["net_id"]
195 def setup_ingress_egress_secgroup(neutron_client, protocol,
196 min_port=None, max_port=None):
197 secgroups = os_utils.get_security_groups(neutron_client)
199 os_utils.create_secgroup_rule(neutron_client, sg['id'],
201 port_range_min=min_port,
202 port_range_max=max_port)
203 os_utils.create_secgroup_rule(neutron_client, sg['id'],
205 port_range_min=min_port,
206 port_range_max=max_port)
210 def setup_security_groups(neutron_client):
211 sg_id = os_utils.create_security_group_full(neutron_client,
212 SECGROUP_NAME, SECGROUP_DESCR)
213 setup_ingress_egress_secgroup(neutron_client, "icmp")
214 setup_ingress_egress_secgroup(neutron_client, "udp", 67, 68)
215 setup_ingress_egress_secgroup(neutron_client, "tcp", 22, 22)
216 setup_ingress_egress_secgroup(neutron_client, "tcp", 80, 80)
220 def boot_instance(nova_client, name, flavor, image_id, network_id, sg_id):
221 logger.info("Creating instance '%s'..." % name)
223 "Configuration:\n name=%s \n flavor=%s \n image=%s \n "
224 "network=%s \n" % (name, flavor, image_id, network_id))
226 instance = os_utils.create_instance_and_wait_for_active(flavor,
232 logger.error("Error while booting instance.")
235 instance_ip = instance.networks.get(NET_NAME)[0]
236 logger.debug("Instance '%s' got private ip '%s'." %
239 logger.info("Adding '%s' to security group %s" % (name, SECGROUP_NAME))
240 os_utils.add_secgroup_to_instance(nova_client, instance.id, sg_id)
245 def ping(remote, pkt_cnt=1, iface=None, retries=100, timeout=None):
249 ping_cmd = ping_cmd + ' -w %s' % timeout
251 grep_cmd = "grep -e 'packet loss' -e rtt"
253 if iface is not None:
254 ping_cmd = ping_cmd + ' -I %s' % iface
256 ping_cmd = ping_cmd + ' -i 0 -c %d %s' % (pkt_cnt, remote)
257 cmd = ping_cmd + '|' + grep_cmd
260 output = run_cmd(cmd)
264 match = re.search('(\d*)% packet loss', output)
268 packet_loss = int(match.group(1))
272 retries = retries - 1
277 def get_floating_ips(nova_client, neutron_client):
279 instances = nova_client.servers.list(search_opts={'all_tenants': 1})
280 for instance in instances:
281 floatip_dic = os_utils.create_floating_ip(neutron_client)
282 floatip = floatip_dic['fip_addr']
283 instance.add_floating_ip(floatip)
284 logger.info("Instance name and ip %s:%s " % (instance.name, floatip))
285 logger.info("Waiting for instance %s:%s to come up" %
286 (instance.name, floatip))
287 if not ping(floatip):
288 logger.info("Instance %s:%s didn't come up" %
289 (instance.name, floatip))
292 if instance.name == "server":
293 logger.info("Server:%s is reachable" % floatip)
295 elif instance.name == "client":
296 logger.info("Client:%s is reachable" % floatip)
299 logger.info("SF:%s is reachable" % floatip)
302 return server_ip, client_ip, ips[1], ips[0]
304 # Start http server on a give machine, Can be VM
307 def start_http_server(ip):
308 cmd = "\'python -m SimpleHTTPServer 80"
309 cmd = cmd + " > /dev/null 2>&1 &\'"
310 return run_cmd_remote(ip, cmd)
312 # Set firewall using vxlan_tool.py on a give machine, Can be VM
315 def vxlan_firewall(sf, iface="eth0", port="22", block=True):
316 cmd = "python vxlan_tool.py"
317 cmd = cmd + " -i " + iface + " -d forward -v off"
319 cmd = "python vxlan_tool.py -i eth0 -d forward -v off -b " + port
321 cmd = "sh -c 'cd /root;nohup " + cmd + " > /dev/null 2>&1 &'"
322 run_cmd_remote(sf, cmd)
324 # Run netcat on a give machine, Can be VM
327 def netcat(s_ip, c_ip, port="80", timeout=5):
329 cmd = cmd + " -w %s %s %s" % (timeout, s_ip, port)
331 output = run_cmd_remote(c_ip, cmd)
332 logger.info("%s" % output)
336 def is_ssh_blocked(srv_prv_ip, client_ip):
337 res = netcat(srv_prv_ip, client_ip, port="22")
338 match = re.search("nc:.*timed out:.*", res, re.M)
345 def is_http_blocked(srv_prv_ip, client_ip):
346 res = netcat(srv_prv_ip, client_ip, port="80")
347 match = re.search(".* 80 port.* succeeded!", res, re.M)
354 def capture_err_logs(ovs_logger, controller_clients,
355 compute_clients, error):
356 timestamp = time.strftime("%Y%m%d-%H%M%S")
357 ovs_logger.dump_ovs_logs(controller_clients,
364 def update_json_results(name, result):
365 json_results.update({name: result})
366 if result is not "Passed":
367 json_results["failures"] += 1
372 def get_ssh_clients(role):
374 for ip in get_openstack_node_ips(role):
375 s_client = ssh_utils.get_ssh_client(ip,
378 clients.append(s_client)
382 # Check SSH connectivity to VNFs
385 def check_ssh(ips, retries=100):
386 check = [False, False]
387 logger.info("Checking SSH connectivity to the SFs with ips %s" % str(ips))
388 while retries and not all(check):
389 for index, ip in enumerate(ips):
390 check[index] = run_cmd_remote(ip, "exit")
393 logger.info("SSH connectivity to the SFs established")
401 # Measure the time it takes to update the classification rules
404 def capture_time_log(ovs_logger, compute_clients):
407 start_time = time.time()
409 rsps = ovs_logger.ofctl_time_counter(compute_clients[0])
418 if(first_RSP != rsps[0]):
419 if (rsps[0] == rsps[1]):
420 stop_time = time.time()
421 logger.info("classification rules updated")
422 difference = stop_time - start_time
423 logger.info("It took %s seconds" % difference)
430 installer_type = os.environ.get("INSTALLER_TYPE")
431 if installer_type != "fuel":
433 '\033[91mCurrently supported only Fuel Installer type\033[0m')
436 installer_ip = os.environ.get("INSTALLER_IP")
439 '\033[91minstaller ip is not set\033[0m')
441 '\033[91mexport INSTALLER_IP=<ip>\033[0m')
444 env_list = run_cmd_on_fm("fuel2 env list -f json")
445 fuel_env = os.environ.get("FUEL_ENV")
446 if len(eval(env_list)) > 1 and fuel_env is None:
447 out = run_cmd_on_fm("fuel env")
449 '\033[91mMore than one fuel env found\033[0m\n %s' % out)
451 '\033[91mexport FUEL_ENV=<env-id> to set ENV\033[0m')
454 start_time = time.time()
458 _, custom_flv_id = os_utils.get_or_create_flavor(
459 FLAVOR, 1500, 10, 1, public=True)
460 if not custom_flv_id:
461 logger.error("Failed to create custom flavor")
464 glance_client = os_utils.get_glance_client()
465 neutron_client = os_utils.get_neutron_client()
466 nova_client = os_utils.get_nova_client()
468 controller_clients = get_ssh_clients("controller")
469 compute_clients = get_ssh_clients("compute")
471 ovs_logger = ovs_utils.OVSLogger(
472 os.path.join(os.getcwd(), 'ovs-logs'),
473 FUNCTEST_RESULTS_DIR)
475 image_id = setup_glance(glance_client)
476 network_id = setup_neutron(neutron_client)
477 sg_id = setup_security_groups(neutron_client)
480 nova_client, CLIENT, FLAVOR, image_id, network_id, sg_id)
481 srv_prv_ip = boot_instance(
482 nova_client, SERVER, FLAVOR, image_id, network_id, sg_id)
484 subprocess.call(TACKER_SCRIPT, shell=True)
486 # Start measuring the time it takes to implement the classification rules
488 thread.start_new_thread(capture_time_log,
489 (ovs_logger, compute_clients,))
491 logger.error("Unable to start the thread that counts time %s" % e)
493 server_ip, client_ip, sf1, sf2 = get_floating_ips(
494 nova_client, neutron_client)
496 if not check_ssh([sf1, sf2]):
497 logger.error("Cannot establish SSH connection to the SFs")
500 logger.info("Starting HTTP server on %s" % server_ip)
501 if not start_http_server(server_ip):
503 '\033[91mFailed to start HTTP server on %s\033[0m' % server_ip)
506 logger.info("Starting HTTP firewall on %s" % sf2)
507 vxlan_firewall(sf2, port="80")
508 logger.info("Starting SSH firewall on %s" % sf1)
509 vxlan_firewall(sf1, port="22")
511 logger.info("Wait for ODL to update the classification rules in OVS")
514 logger.info("Test SSH")
515 if is_ssh_blocked(srv_prv_ip, client_ip):
516 logger.info('\033[92mTEST 1 [PASSED] ==> SSH BLOCKED\033[0m')
517 update_json_results("Test 1: SSH Blocked", "Passed")
519 error = ('\033[91mTEST 1 [FAILED] ==> SSH NOT BLOCKED\033[0m')
522 ovs_logger, controller_clients, compute_clients, error)
523 update_json_results("Test 1: SSH Blocked", "Failed")
525 logger.info("Test HTTP")
526 if not is_http_blocked(srv_prv_ip, client_ip):
527 logger.info('\033[92mTEST 2 [PASSED] ==> HTTP WORKS\033[0m')
528 update_json_results("Test 2: HTTP works", "Passed")
530 error = ('\033[91mTEST 2 [FAILED] ==> HTTP BLOCKED\033[0m')
533 ovs_logger, controller_clients, compute_clients, error)
534 update_json_results("Test 2: HTTP works", "Failed")
536 logger.info("Changing the classification")
537 subprocess.call(TACKER_CHANGECLASSI, shell=True)
539 # Start measuring the time it takes to implement the classification rules
541 thread.start_new_thread(capture_time_log,
542 (ovs_logger, compute_clients,))
544 logger.error("Unable to start the thread that counts time %s" % e)
546 logger.info("Wait for ODL to update the classification rules in OVS")
549 logger.info("Test HTTP")
550 if is_http_blocked(srv_prv_ip, client_ip):
551 logger.info('\033[92mTEST 3 [PASSED] ==> HTTP Blocked\033[0m')
552 update_json_results("Test 3: HTTP Blocked", "Passed")
554 error = ('\033[91mTEST 3 [FAILED] ==> HTTP WORKS\033[0m')
556 capture_err_logs(controller_clients, compute_clients, error)
557 update_json_results("Test 3: HTTP Blocked", "Failed")
559 logger.info("Test SSH")
560 if not is_ssh_blocked(srv_prv_ip, client_ip):
561 logger.info('\033[92mTEST 4 [PASSED] ==> SSH Works\033[0m')
562 update_json_results("Test 4: SSH Works", "Passed")
564 error = ('\033[91mTEST 4 [FAILED] ==> SSH BLOCKED\033[0m')
566 capture_err_logs(controller_clients, compute_clients, error)
567 update_json_results("Test 4: SSH Works", "Failed")
569 if json_results["failures"]:
571 logger.error('\033[91mSFC TESTS: %s :( FOUND %s FAIL \033[0m' % (
572 status, json_results["failures"]))
574 ovs_logger.create_artifact_archive()
577 stop_time = time.time()
578 logger.debug("Promise Results json: " + str(json_results))
579 ft_utils.push_results_to_db("sfc",
587 logger.info('\033[92mSFC ALL TESTS: %s :)\033[0m' % status)
592 if __name__ == '__main__':