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()
37 parser.add_argument("-d", "--debug", help="Debug mode", action="store_true")
38 parser.add_argument("-r", "--report",
39 help="Create json result file",
42 args = parser.parse_args()
44 """ logging configuration """
46 logger = logging.getLogger('vPing_ssh')
47 logger.setLevel(logging.DEBUG)
49 ch = logging.StreamHandler()
52 ch.setLevel(logging.DEBUG)
54 ch.setLevel(logging.INFO)
56 formatter = logging.Formatter('%(asctime)s - %(name)s'
57 '- %(levelname)s - %(message)s')
59 ch.setFormatter(formatter)
61 paramiko.util.log_to_file("/var/log/paramiko.log")
63 REPO_PATH = os.environ['repos_dir'] + '/functest/'
64 if not os.path.exists(REPO_PATH):
65 logger.error("Functest repository directory not found '%s'" % REPO_PATH)
67 sys.path.append(REPO_PATH + "testcases/")
69 import openstack_utils
71 with open("/home/opnfv/functest/conf/config_functest.yaml") as f:
72 functest_yaml = yaml.safe_load(f)
75 HOME = os.environ['HOME'] + "/"
78 VM_DELETE_TIMEOUT = 100
79 PING_TIMEOUT = functest_yaml.get("vping").get("ping_timeout")
80 TEST_DB = functest_yaml.get("results").get("test_db_url")
81 NAME_VM_1 = functest_yaml.get("vping").get("vm_name_1")
82 NAME_VM_2 = functest_yaml.get("vping").get("vm_name_2")
83 GLANCE_IMAGE_NAME = functest_yaml.get("vping").get("image_name")
84 GLANCE_IMAGE_FILENAME = functest_yaml.get("general"). \
85 get("openstack").get("image_file_name")
86 GLANCE_IMAGE_FORMAT = functest_yaml.get("general"). \
87 get("openstack").get("image_disk_format")
88 GLANCE_IMAGE_PATH = functest_yaml.get("general"). \
89 get("directories").get("dir_functest_data") + "/" + GLANCE_IMAGE_FILENAME
92 FLAVOR = functest_yaml.get("vping").get("vm_flavor")
94 # NEUTRON Private Network parameters
96 NEUTRON_PRIVATE_NET_NAME = functest_yaml.get("vping"). \
97 get("vping_private_net_name")
98 NEUTRON_PRIVATE_SUBNET_NAME = functest_yaml.get("vping"). \
99 get("vping_private_subnet_name")
100 NEUTRON_PRIVATE_SUBNET_CIDR = functest_yaml.get("vping"). \
101 get("vping_private_subnet_cidr")
102 NEUTRON_ROUTER_NAME = functest_yaml.get("vping"). \
103 get("vping_router_name")
105 SECGROUP_NAME = functest_yaml.get("vping"). \
107 SECGROUP_DESCR = functest_yaml.get("vping"). \
108 get("vping_sg_descr")
113 """pretty printing"""
117 def waitVmActive(nova, vm):
119 # sleep and wait for VM status change
121 count = VM_BOOT_TIMEOUT / sleep_time
123 status = openstack_utils.get_instance_status(nova, vm)
124 logger.debug("Status: %s" % status)
125 if status == "ACTIVE":
127 if status == "ERROR" or status == "error":
130 logger.debug("Booting a VM timed out...")
133 time.sleep(sleep_time)
137 def waitVmDeleted(nova, vm):
139 # sleep and wait for VM status change
141 count = VM_DELETE_TIMEOUT / sleep_time
143 status = openstack_utils.get_instance_status(nova, vm)
147 logger.debug("Timeout")
152 time.sleep(sleep_time)
156 def create_private_neutron_net(neutron):
158 # Check if the network already exists
159 network_id = openstack_utils.get_network_id(neutron,
160 NEUTRON_PRIVATE_NET_NAME)
161 subnet_id = openstack_utils.get_subnet_id(neutron,
162 NEUTRON_PRIVATE_SUBNET_NAME)
163 router_id = openstack_utils.get_router_id(neutron,
166 if network_id != '' and subnet_id != '' and router_id != '':
167 logger.info("Using existing network '%s'..."
168 % NEUTRON_PRIVATE_NET_NAME)
170 neutron.format = 'json'
171 logger.info('Creating neutron network %s...'
172 % NEUTRON_PRIVATE_NET_NAME)
173 network_id = openstack_utils. \
174 create_neutron_net(neutron, NEUTRON_PRIVATE_NET_NAME)
178 logger.debug("Network '%s' created successfully" % network_id)
179 logger.debug('Creating Subnet....')
180 subnet_id = openstack_utils. \
181 create_neutron_subnet(neutron,
182 NEUTRON_PRIVATE_SUBNET_NAME,
183 NEUTRON_PRIVATE_SUBNET_CIDR,
187 logger.debug("Subnet '%s' created successfully" % subnet_id)
188 logger.debug('Creating Router...')
189 router_id = openstack_utils. \
190 create_neutron_router(neutron, NEUTRON_ROUTER_NAME)
195 logger.debug("Router '%s' created successfully" % router_id)
196 logger.debug('Adding router to subnet...')
198 if not openstack_utils.add_interface_router(neutron,
202 logger.debug("Interface added successfully.")
204 logger.debug('Adding gateway to router...')
205 if not openstack_utils.add_gateway_router(neutron, router_id):
207 logger.debug("Gateway added successfully.")
209 network_dic = {'net_id': network_id,
210 'subnet_id': subnet_id,
211 'router_id': router_id}
215 def create_security_group(neutron_client):
216 sg_id = openstack_utils.get_security_group_id(neutron_client,
219 logger.info("Using existing security group '%s'..." % SECGROUP_NAME)
221 logger.info("Creating security group '%s'..." % SECGROUP_NAME)
222 SECGROUP = openstack_utils.create_security_group(neutron_client,
226 logger.error("Failed to create the security group...")
229 sg_id = SECGROUP['id']
231 logger.debug("Security group '%s' with ID=%s created successfully."
232 % (SECGROUP['name'], sg_id))
234 logger.debug("Adding ICMP rules in security group '%s'..."
236 if not openstack_utils.create_secgroup_rule(neutron_client, sg_id,
238 logger.error("Failed to create the security group rule...")
241 logger.debug("Adding SSH rules in security group '%s'..."
243 if not openstack_utils.\
244 create_secgroup_rule(neutron_client, sg_id,
245 'ingress', 'tcp', '22', '22'):
246 logger.error("Failed to create the security group rule...")
249 if not openstack_utils.\
250 create_secgroup_rule(neutron_client, sg_id,
251 'egress', 'tcp', '22', '22'):
252 logger.error("Failed to create the security group rule...")
257 def push_results(start_time_ts, duration, test_status):
259 logger.debug("Pushing result into DB...")
260 scenario = functest_utils.get_scenario(logger)
263 if test_status == "OK":
265 pod_name = functest_utils.get_pod_name(logger)
266 build_tag = functest_utils.get_build_tag(logger)
267 functest_utils.push_results_to_db(TEST_DB,
270 logger, pod_name, version, scenario,
272 payload={'timestart': start_time_ts,
273 'duration': duration,
274 'status': test_status})
276 logger.error("Error pushing results into Database '%s'"
282 creds_nova = openstack_utils.get_credentials("nova")
283 nova_client = novaclient.Client('2', **creds_nova)
284 creds_neutron = openstack_utils.get_credentials("neutron")
285 neutron_client = neutronclient.Client(**creds_neutron)
286 creds_keystone = openstack_utils.get_credentials("keystone")
287 keystone_client = keystoneclient.Client(**creds_keystone)
288 glance_endpoint = keystone_client.\
289 service_catalog.url_for(service_type='image',
290 endpoint_type='publicURL')
291 glance_client = glanceclient.Client(1, glance_endpoint,
292 token=keystone_client.auth_token)
298 # Check if the given image exists
299 image_id = openstack_utils.get_image_id(glance_client, GLANCE_IMAGE_NAME)
301 logger.info("Using existing image '%s'..." % GLANCE_IMAGE_NAME)
305 logger.info("Creating image '%s' from '%s'..." % (GLANCE_IMAGE_NAME,
307 image_id = openstack_utils.create_glance_image(glance_client,
311 logger.error("Failed to create a Glance image...")
313 logger.debug("Image '%s' with ID=%s created successfully."
314 % (GLANCE_IMAGE_NAME, image_id))
316 network_dic = create_private_neutron_net(neutron_client)
319 "There has been a problem when creating the neutron network")
322 network_id = network_dic["net_id"]
324 sg_id = create_security_group(neutron_client)
326 # Check if the given flavor exists
328 flavor = nova_client.flavors.find(name=FLAVOR)
329 logger.info("Using existing Flavor '%s'..." % FLAVOR)
331 logger.error("Flavor '%s' not found." % FLAVOR)
332 logger.info("Available flavors are: ")
333 pMsg(nova_client.flavor.list())
336 # Deleting instances if they exist
337 servers = nova_client.servers.list()
338 for server in servers:
339 if server.name == NAME_VM_1 or server.name == NAME_VM_2:
340 logger.info("Instance %s found. Deleting..." % server.name)
344 start_time_ts = time.time()
345 end_time_ts = start_time_ts
346 logger.info("vPing Start Time:'%s'" % (
347 datetime.datetime.fromtimestamp(start_time_ts).strftime(
348 '%Y-%m-%d %H:%M:%S')))
350 logger.info("Creating instance '%s'..." % NAME_VM_1)
352 "Configuration:\n name=%s \n flavor=%s \n image=%s \n "
353 "network=%s \n" % (NAME_VM_1, flavor, image_id, network_id))
354 vm1 = nova_client.servers.create(
358 nics=[{"net-id": network_id}]
361 # wait until VM status is active
362 if not waitVmActive(nova_client, vm1):
363 logger.error("Instance '%s' cannot be booted. Status is '%s'" % (
364 NAME_VM_1, openstack_utils.get_instance_status(nova_client, vm1)))
367 logger.info("Instance '%s' is ACTIVE." % NAME_VM_1)
369 # Retrieve IP of first VM
370 test_ip = vm1.networks.get(NEUTRON_PRIVATE_NET_NAME)[0]
371 logger.debug("Instance '%s' got private ip '%s'." % (NAME_VM_1, test_ip))
373 logger.info("Adding '%s' to security group '%s'..."
374 % (NAME_VM_1, SECGROUP_NAME))
375 openstack_utils.add_secgroup_to_instance(nova_client, vm1.id, sg_id)
378 logger.info("Creating instance '%s'..." % NAME_VM_2)
380 "Configuration:\n name=%s \n flavor=%s \n image=%s \n "
381 "network=%s \n" % (NAME_VM_2, flavor, image_id, network_id))
382 vm2 = nova_client.servers.create(
386 nics=[{"net-id": network_id}]
389 if not waitVmActive(nova_client, vm2):
390 logger.error("Instance '%s' cannot be booted. Status is '%s'" % (
391 NAME_VM_2, openstack_utils.get_instance_status(nova_client, vm2)))
394 logger.info("Instance '%s' is ACTIVE." % NAME_VM_2)
396 logger.info("Adding '%s' to security group '%s'..." % (NAME_VM_2,
398 openstack_utils.add_secgroup_to_instance(nova_client, vm2.id, sg_id)
400 logger.info("Creating floating IP for VM '%s'..." % NAME_VM_2)
401 floatip_dic = openstack_utils.create_floating_ip(neutron_client)
402 floatip = floatip_dic['fip_addr']
403 # floatip_id = floatip_dic['fip_id']
406 logger.error("Cannot create floating IP.")
408 logger.info("Floating IP created: '%s'" % floatip)
410 logger.info("Associating floating ip: '%s' to VM '%s' "
411 % (floatip, NAME_VM_2))
412 if not openstack_utils.add_floating_ip(nova_client, vm2.id, floatip):
413 logger.error("Cannot associate floating IP to VM.")
416 logger.info("Trying to establish SSH connection to %s..." % floatip)
418 password = 'cubswin:)'
419 ssh = paramiko.SSHClient()
420 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
426 cidr_first_octet = NEUTRON_PRIVATE_SUBNET_CIDR.split('.')[0]
429 ssh.connect(floatip, username=username,
430 password=password, timeout=2)
431 logger.debug("SSH connection established to %s." % floatip)
434 logger.debug("Waiting for %s..." % floatip)
438 console_log = vm2.get_console_output()
440 # print each "Sending discover" captured on the console log
441 if len(re.findall("Sending discover", console_log)) > discover_count \
444 logger.debug("Console-log '%s': Sending discover..."
447 # check if eth0 got an ip,the line looks like this:
448 # "inet addr:192.168."....
449 # if the dhcp agent fails to assing ip, this line will not appear
450 if "inet addr:" + cidr_first_octet in console_log and not got_ip:
452 logger.debug("The instance '%s' succeeded to get the IP "
453 "from the dhcp agent.")
455 # if dhcp doesnt work,it shows "No lease, failing".The test will fail
456 if "No lease, failing" in console_log and not nolease and not got_ip:
458 logger.debug("Console-log '%s': No lease, failing..."
460 logger.info("The instance failed to get an IP from the "
461 "DHCP agent. The test will probably timeout...")
463 if timeout == 0: # 300 sec timeout (5 min)
464 logger.error("Cannot establish connection to IP '%s'. Aborting"
468 scp = SCPClient(ssh.get_transport())
470 ping_script = REPO_PATH + "testcases/vPing/CI/libraries/ping.sh"
472 scp.put(ping_script, "~/")
474 logger.error("Cannot SCP the file '%s' to VM '%s'"
475 % (ping_script, floatip))
477 cmd = 'chmod 755 ~/ping.sh'
478 (stdin, stdout, stderr) = ssh.exec_command(cmd)
479 for line in stdout.readlines():
482 logger.info("Waiting for ping...")
486 cmd = '~/ping.sh ' + test_ip
490 (stdin, stdout, stderr) = ssh.exec_command(cmd)
491 output = stdout.readlines()
494 if "vPing OK" in line:
495 logger.info("vPing detected!")
497 # we consider start time at VM1 booting
498 end_time_ts = time.time()
499 duration = round(end_time_ts - start_time_ts, 1)
500 logger.info("vPing duration:'%s' s." % duration)
504 elif sec == PING_TIMEOUT:
505 logger.info("Timeout reached.")
510 logger.debug("Pinging %s. Waiting for response..." % test_ip)
515 logger.info("vPing OK")
519 logger.error("vPing FAILED")
522 push_results(start_time_ts, duration, test_status)
526 if __name__ == '__main__':