3 # Copyright (c) 2015 All rights reserved
4 # This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # 0.1: This script boots the VM1 and allocates IP address from Nova
11 # Later, the VM2 boots then execute cloud-init to ping VM1.
12 # After successful ping, both the VMs are deleted.
13 # 0.2: measure test duration and publish results under json format
26 from scp import SCPClient
27 from novaclient import client as novaclient
28 from neutronclient.v2_0 import client as neutronclient
29 from keystoneclient.v2_0 import client as keystoneclient
30 from glanceclient import client as glanceclient
32 pp = pprint.PrettyPrinter(indent=4)
34 parser = argparse.ArgumentParser()
36 parser.add_argument("-d", "--debug", help="Debug mode", action="store_true")
37 parser.add_argument("-r", "--report",
38 help="Create json result file",
41 args = parser.parse_args()
43 """ logging configuration """
45 logger = logging.getLogger('vPing')
46 logger.setLevel(logging.DEBUG)
48 ch = logging.StreamHandler()
51 ch.setLevel(logging.DEBUG)
53 ch.setLevel(logging.INFO)
55 formatter = logging.Formatter('%(asctime)s - %(name)s'
56 '- %(levelname)s - %(message)s')
58 ch.setFormatter(formatter)
61 REPO_PATH = os.environ['repos_dir']+'/functest/'
62 if not os.path.exists(REPO_PATH):
63 logger.error("Functest repository directory not found '%s'" % REPO_PATH)
65 sys.path.append(REPO_PATH + "testcases/")
68 with open("/home/opnfv/functest/conf/config_functest.yaml") as f:
69 functest_yaml = yaml.safe_load(f)
72 HOME = os.environ['HOME'] + "/"
75 VM_DELETE_TIMEOUT = 100
76 PING_TIMEOUT = functest_yaml.get("vping").get("ping_timeout")
77 TEST_DB = functest_yaml.get("results").get("test_db_url")
78 NAME_VM_1 = functest_yaml.get("vping").get("vm_name_1")
79 NAME_VM_2 = functest_yaml.get("vping").get("vm_name_2")
80 IP_1 = functest_yaml.get("vping").get("ip_1")
81 IP_2 = functest_yaml.get("vping").get("ip_2")
82 # GLANCE_IMAGE_NAME = functest_yaml.get("general"). \
83 # get("openstack").get("image_name")
84 GLANCE_IMAGE_NAME = "functest-vping"
85 GLANCE_IMAGE_FILENAME = functest_yaml.get("general"). \
86 get("openstack").get("image_file_name")
87 GLANCE_IMAGE_FORMAT = functest_yaml.get("general"). \
88 get("openstack").get("image_disk_format")
89 GLANCE_IMAGE_PATH = functest_yaml.get("general"). \
90 get("directories").get("dir_functest_data") + "/" + GLANCE_IMAGE_FILENAME
93 FLAVOR = functest_yaml.get("vping").get("vm_flavor")
95 # NEUTRON Private Network parameters
97 NEUTRON_PRIVATE_NET_NAME = functest_yaml.get("vping"). \
98 get("vping_private_net_name")
100 NEUTRON_PRIVATE_SUBNET_NAME = functest_yaml.get("vping"). \
101 get("vping_private_subnet_name")
103 NEUTRON_PRIVATE_SUBNET_CIDR = functest_yaml.get("vping"). \
104 get("vping_private_subnet_cidr")
106 NEUTRON_ROUTER_NAME = functest_yaml.get("vping"). \
107 get("vping_router_name")
112 """pretty printing"""
116 def waitVmActive(nova, vm):
118 # sleep and wait for VM status change
120 count = VM_BOOT_TIMEOUT / sleep_time
122 status = functest_utils.get_instance_status(nova, vm)
123 logger.debug("Status: %s" % status)
124 if status == "ACTIVE":
126 if status == "ERROR" or status == "error":
129 logger.debug("Booting a VM timed out...")
132 time.sleep(sleep_time)
136 def waitVmDeleted(nova, vm):
138 # sleep and wait for VM status change
140 count = VM_DELETE_TIMEOUT / sleep_time
142 status = functest_utils.get_instance_status(nova, vm)
146 logger.debug("Timeout")
151 time.sleep(sleep_time)
155 def create_private_neutron_net(neutron):
157 neutron.format = 'json'
158 logger.info('Creating neutron network %s...' % NEUTRON_PRIVATE_NET_NAME)
159 network_id = functest_utils. \
160 create_neutron_net(neutron, NEUTRON_PRIVATE_NET_NAME)
164 logger.debug("Network '%s' created successfully" % network_id)
165 logger.debug('Creating Subnet....')
166 subnet_id = functest_utils. \
167 create_neutron_subnet(neutron,
168 NEUTRON_PRIVATE_SUBNET_NAME,
169 NEUTRON_PRIVATE_SUBNET_CIDR,
173 logger.debug("Subnet '%s' created successfully" % subnet_id)
174 logger.debug('Creating Router...')
175 router_id = functest_utils. \
176 create_neutron_router(neutron, NEUTRON_ROUTER_NAME)
181 logger.debug("Router '%s' created successfully" % router_id)
182 logger.debug('Adding router to subnet...')
184 if not functest_utils.add_interface_router(neutron, router_id, subnet_id):
186 logger.debug("Interface added successfully.")
188 logger.debug('Adding gateway to router...')
189 if not functest_utils.add_gateway_router(neutron, router_id):
191 logger.debug("Gateway added successfully.")
193 network_dic = {'net_id': network_id,
194 'subnet_id': subnet_id,
195 'router_id': router_id}
199 def cleanup(nova, neutron, image_id, network_dic, port_id1, port_id2):
202 logger.info("Cleaning up...")
203 logger.debug("Deleting image...")
204 if not functest_utils.delete_glance_image(nova, image_id):
205 logger.error("Error deleting the glance image")
207 vm1 = functest_utils.get_instance_by_name(nova, NAME_VM_1)
209 logger.debug("Deleting '%s'..." % NAME_VM_1)
210 nova.servers.delete(vm1)
211 # wait until VMs are deleted
212 if not waitVmDeleted(nova, vm1):
214 "Instance '%s' with cannot be deleted. Status is '%s'" % (
215 NAME_VM_1, functest_utils.get_instance_status(nova, vm1)))
217 logger.debug("Instance %s terminated." % NAME_VM_1)
219 vm2 = functest_utils.get_instance_by_name(nova, NAME_VM_2)
222 logger.debug("Deleting '%s'..." % NAME_VM_2)
223 vm2 = nova.servers.find(name=NAME_VM_2)
224 nova.servers.delete(vm2)
226 if not waitVmDeleted(nova, vm2):
228 "Instance '%s' with cannot be deleted. Status is '%s'" % (
229 NAME_VM_2, functest_utils.get_instance_status(nova, vm2)))
231 logger.debug("Instance %s terminated." % NAME_VM_2)
233 # delete created network
234 logger.info("Deleting network '%s'..." % NEUTRON_PRIVATE_NET_NAME)
235 net_id = network_dic["net_id"]
236 subnet_id = network_dic["subnet_id"]
237 router_id = network_dic["router_id"]
239 if not functest_utils.delete_neutron_port(neutron, port_id1):
240 logger.error("Unable to remove port '%s'" % port_id1)
242 logger.debug("Port '%s' removed successfully" % port_id1)
244 if not functest_utils.delete_neutron_port(neutron, port_id2):
245 logger.error("Unable to remove port '%s'" % port_id2)
247 logger.debug("Port '%s' removed successfully" % port_id2)
249 if not functest_utils.remove_interface_router(neutron, router_id,
251 logger.error("Unable to remove subnet '%s' from router '%s'" % (
252 subnet_id, router_id))
255 logger.debug("Interface removed successfully")
256 if not functest_utils.delete_neutron_router(neutron, router_id):
257 logger.error("Unable to delete router '%s'" % router_id)
260 logger.debug("Router deleted successfully")
262 if not functest_utils.delete_neutron_subnet(neutron, subnet_id):
263 logger.error("Unable to delete subnet '%s'" % subnet_id)
267 "Subnet '%s' deleted successfully" % NEUTRON_PRIVATE_SUBNET_NAME)
269 if not functest_utils.delete_neutron_net(neutron, net_id):
270 logger.error("Unable to delete network '%s'" % net_id)
274 "Network '%s' deleted successfully" % NEUTRON_PRIVATE_NET_NAME)
281 creds_nova = functest_utils.get_credentials("nova")
282 nova_client = novaclient.Client('2', **creds_nova)
283 creds_neutron = functest_utils.get_credentials("neutron")
284 neutron_client = neutronclient.Client(**creds_neutron)
285 creds_keystone = functest_utils.get_credentials("keystone")
286 keystone_client = keystoneclient.Client(**creds_keystone)
287 glance_endpoint = keystone_client.service_catalog.url_for(service_type='image',
288 endpoint_type='publicURL')
289 glance_client = glanceclient.Client(1, glance_endpoint,
290 token=keystone_client.auth_token)
296 logger.debug("Creating image '%s' from '%s'..." % (GLANCE_IMAGE_NAME,
298 image_id = functest_utils.create_glance_image(glance_client,
302 logger.error("Failed to create a Glance image...")
305 # Check if the given image exists
306 image = functest_utils.get_image_id(glance_client, GLANCE_IMAGE_NAME)
308 logger.error("ERROR: Glance image '%s' not found." % GLANCE_IMAGE_NAME)
309 logger.info("Available images are: ")
310 pMsg(nova_client.images.list())
313 network_dic = create_private_neutron_net(neutron_client)
317 "There has been a problem when creating the neutron network")
320 network_id = network_dic["net_id"]
322 # Check if the given flavor exists
325 flavor = nova_client.flavors.find(name=FLAVOR)
326 logger.info("Flavor found '%s'" % FLAVOR)
328 logger.error("Flavor '%s' not found." % FLAVOR)
329 logger.info("Available flavors are: ")
330 pMsg(nova_client.flavor.list())
333 # Deleting instances if they exist
335 servers = nova_client.servers.list()
336 for server in servers:
337 if server.name == NAME_VM_1 or server.name == NAME_VM_2:
338 logger.info("Instance %s found. Deleting..." % server.name)
343 # tune (e.g. flavor, images, network) to your specific
344 # openstack configuration here
345 # we consider start time at VM1 booting
346 start_time_ts = time.time()
347 end_time_ts = start_time_ts
348 logger.info("vPing Start Time:'%s'" % (
349 datetime.datetime.fromtimestamp(start_time_ts).strftime(
350 '%Y-%m-%d %H:%M:%S')))
353 logger.debug("Creating port 'vping-port-1' with IP %s..." % IP_1)
354 port_id1 = functest_utils.create_neutron_port(neutron_client,
355 "vping-port-1", network_id,
358 logger.error("Unable to create port.")
361 logger.info("Creating instance '%s' with IP %s..." % (NAME_VM_1, IP_1))
363 "Configuration:\n name=%s \n flavor=%s \n image=%s \n "
364 "network=%s \n" % (NAME_VM_1, flavor, image, network_id))
365 vm1 = nova_client.servers.create(
369 # nics = [{"net-id": network_id, "v4-fixed-ip": IP_1}]
370 nics=[{"port-id": port_id1}]
373 # wait until VM status is active
374 if not waitVmActive(nova_client, vm1):
376 logger.error("Instance '%s' cannot be booted. Status is '%s'" % (
377 NAME_VM_1, functest_utils.get_instance_status(nova_client, vm1)))
378 cleanup(nova_client, neutron_client, image_id, network_dic, port_id1)
381 logger.info("Instance '%s' is ACTIVE." % NAME_VM_1)
383 # Retrieve IP of first VM
384 # logger.debug("Fetching IP...")
385 # server = functest_utils.get_instance_by_name(nova_client, NAME_VM_1)
386 # theoretically there is only one IP address so we take the
387 # first element of the table
388 # Dangerous! To be improved!
389 # test_ip = server.networks.get(NEUTRON_PRIVATE_NET_NAME)[0]
391 logger.debug("Instance '%s' got %s" % (NAME_VM_1, test_ip))
394 # we will boot then execute a ping script with cloud-init
395 # the long chain corresponds to the ping procedure converted with base 64
396 # tune (e.g. flavor, images, network) to your specific openstack
401 logger.debug("Creating port 'vping-port-2' with IP %s..." % IP_2)
402 port_id2 = functest_utils.create_neutron_port(neutron_client,
403 "vping-port-2", network_id,
407 logger.error("Unable to create port.")
410 logger.info("Creating instance '%s' with IP %s..." % (NAME_VM_2, IP_2))
412 "Configuration:\n name=%s \n flavor=%s \n image=%s \n network=%s "
413 "\n" % (NAME_VM_2, flavor, image, network_id))
414 vm2 = nova_client.servers.create(
418 nics=[{"port-id": port_id2}]
421 if not waitVmActive(nova_client, vm2):
422 logger.error("Instance '%s' cannot be booted. Status is '%s'" % (
423 NAME_VM_2, functest_utils.get_instance_status(nova_client, vm2)))
424 cleanup(nova_client, neutron_client, image_id, network_dic,
428 logger.info("Instance '%s' is ACTIVE." % NAME_VM_2)
430 logger.info("Creating floating IP for the second VM...")
431 floatip = functest_utils.create_floating_ip(neutron_client)
433 logger.error("Cannot create floating IP.")
434 cleanup(nova_client, neutron_client, image_id, network_dic,
437 logger.info("Floating IP created: '%s'" % floatip)
439 logger.info("Associating floating ip: '%s' to VM2 " % floatip)
440 if not functest_utils.add_floating_ip(nova_client, vm2.id, floatip):
441 logger.error("Cannot associate floating IP to VM.")
442 cleanup(nova_client, neutron_client, image_id, network_dic,
446 logger.info("Trying to establish SSH connection to %s..." % floatip)
449 ssh = paramiko.SSHClient()
450 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
455 ssh.connect(floatip, username=username, password=password, timeout=2)
456 logger.debug("SSH connection established to %s." % floatip)
460 logger.debug("Waiting for %s..." % floatip)
464 if timeout == 0: # 300 sec timeout (5 min)
465 logger.error("Cannot establish connection to IP '%s'. Aborting" % floatip)
466 cleanup(nova_client, neutron_client, image_id, network_dic,
470 scp = SCPClient(ssh.get_transport())
472 ping_script = REPO_PATH + "testcases/vPing/CI/libraries/ping.sh"
474 scp.put(ping_script,"~/")
476 logger.error("Cannot SCP the file '%s' to VM '%s'" % (ping_script,floatip))
479 #SSH_OPTS="-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no "+\
480 # "-o LogLevel=quiet"
482 #cmd1 = "sshpass -p 'cubswin:)' scp " + SSH_OPTS + " " + \
483 # ping_script + " cirros@"+floatip+":~/ping.sh"
484 #cmd2 = "sshpass -p 'cubswin:)' ssh " + SSH_OPTS + \
485 # " cirros@"+floatip+" 'chmod 755 ~/ping.sh '"
486 #cmd3 = "sshpass -p 'cubswin:)' ssh " + SSH_OPTS + \
487 # " cirros@"+floatip+" '~/ping.sh "+IP_1+"'"
489 cmd = 'chmod 755 ~/ping.sh'
490 (stdin, stdout, stderr) = ssh.exec_command(cmd)
491 for line in stdout.readlines():
494 logger.info("Waiting for ping...")
498 cmd = '~/ping.sh ' + IP_1
502 # we do the SCP every time in the loop because while testing, I observed
503 # that for some strange reason, the cirros VM was deleting the file if
504 # do the scp only once
505 (stdin, stdout, stderr) = ssh.exec_command(cmd)
506 output = stdout.readlines()
510 # print "--"+console_log
511 # report if the test is failed
513 if "vPing OK" in line:
514 logger.info("vPing detected!")
516 # we consider start time at VM1 booting
517 end_time_ts = time.time()
518 duration = round(end_time_ts - start_time_ts, 1)
519 logger.info("vPing duration:'%s'" % duration)
523 elif sec == PING_TIMEOUT:
524 logger.info("Timeout reached.")
529 logger.debug("Pinging %s. Waiting for response..." % IP_1)
532 cleanup(nova_client, neutron_client, image_id, network_dic,
537 logger.info("vPing OK")
540 logger.error("vPing FAILED")
544 logger.debug("Push result into DB")
545 # TODO check path result for the file
546 scenario = functest_utils.get_scenario(logger)
547 pod_name = functest_utils.get_pod_name(logger)
548 functest_utils.push_results_to_db(TEST_DB,
550 logger, pod_name, scenario,
551 payload={'timestart': start_time_ts,
552 'duration': duration,
553 'status': test_status})
554 # with open("vPing-result.json", "w") as outfile:
555 # json.dump({'timestart': start_time_ts, 'duration': duration,
556 # 'status': test_status}, outfile, indent=4)
558 logger.error("Error pushing results into Database '%s'" % sys.exc_info()[0])
562 if __name__ == '__main__':