3 # jose.lausuch@ericsson.com
4 # valentin.boucher@orange.com
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
21 # ############ CREDENTIALS OPENSTACK #############
22 def check_credentials():
24 Check if the OpenStack credentials (openrc) are sourced
26 env_vars = ['OS_AUTH_URL','OS_USERNAME','OS_PASSWORD','OS_TENANT_NAME']
27 return all(map(lambda v: v in os.environ and os.environ[v], env_vars))
30 def get_credentials(service):
31 """Returns a creds dictionary filled with the following keys:
33 * password/api_key (depending on the service)
34 * tenant_name/project_id (depending on the service)
36 :param service: a string indicating the name of the service
37 requesting the credentials.
40 # Unfortunately, each of the OpenStack client will request slightly
41 # different entries in their credentials dict.
42 if service.lower() in ("nova", "cinder"):
47 tenant = "tenant_name"
49 # The most common way to pass these info to the script is to do it through
50 # environment variables.
52 "username": os.environ.get('OS_USERNAME', "admin"),
53 password: os.environ.get("OS_PASSWORD", 'admin'),
54 "auth_url": os.environ.get("OS_AUTH_URL",
55 "http://192.168.20.71:5000/v2.0"),
56 tenant: os.environ.get("OS_TENANT_NAME", "admin"),
62 # ################ NOVA #################
63 def get_instance_status(nova_client, instance):
65 instance = nova_client.servers.get(instance.id)
66 return instance.status
71 def get_instance_by_name(nova_client, instance_name):
73 instance = nova_client.servers.find(name=instance_name)
79 def get_flavor_id(nova_client, flavor_name):
80 flavors = nova_client.flavors.list(detailed=True)
83 if f.name == flavor_name:
89 def get_flavor_id_by_ram_range(nova_client, min_ram, max_ram):
90 flavors = nova_client.flavors.list(detailed=True)
93 if min_ram <= f.ram and f.ram <= max_ram:
99 # ################ NEUTRON #################
100 def create_neutron_net(neutron_client, name):
101 json_body = {'network': {'name': name,
102 'admin_state_up': True}}
104 network = neutron_client.create_network(body=json_body)
105 network_dict = network['network']
106 return network_dict['id']
108 print "Error:", sys.exc_info()[0]
112 def delete_neutron_net(neutron_client, network_id):
114 neutron_client.delete_network(network_id)
117 print "Error:", sys.exc_info()[0]
121 def create_neutron_subnet(neutron_client, name, cidr, net_id):
122 json_body = {'subnets': [{'name': name, 'cidr': cidr,
123 'ip_version': 4, 'network_id': net_id}]}
125 subnet = neutron_client.create_subnet(body=json_body)
126 return subnet['subnets'][0]['id']
128 print "Error:", sys.exc_info()[0]
132 def delete_neutron_subnet(neutron_client, subnet_id):
134 neutron_client.delete_subnet(subnet_id)
137 print "Error:", sys.exc_info()[0]
141 def create_neutron_router(neutron_client, name):
142 json_body = {'router': {'name': name, 'admin_state_up': True}}
144 router = neutron_client.create_router(json_body)
145 return router['router']['id']
147 print "Error:", sys.exc_info()[0]
151 def delete_neutron_router(neutron_client, router_id):
152 json_body = {'router': {'id': router_id}}
154 neutron_client.delete_router(router=router_id)
157 print "Error:", sys.exc_info()[0]
161 def add_interface_router(neutron_client, router_id, subnet_id):
162 json_body = {"subnet_id": subnet_id}
164 neutron_client.add_interface_router(router=router_id, body=json_body)
167 print "Error:", sys.exc_info()[0]
171 def remove_interface_router(neutron_client, router_id, subnet_id):
172 json_body = {"subnet_id": subnet_id}
174 neutron_client.remove_interface_router(router=router_id,
178 print "Error:", sys.exc_info()[0]
182 def create_neutron_port(neutron_client, name, network_id, ip):
183 json_body = {'port': {
184 'admin_state_up': True,
186 'network_id': network_id,
187 'fixed_ips': [{"ip_address": ip}]
190 port = neutron_client.create_port(body=json_body)
191 return port['port']['id']
193 print "Error:", sys.exc_info()[0]
197 def delete_neutron_port(neutron_client, port_id):
199 neutron_client.delete_port(port_id)
202 print "Error:", sys.exc_info()[0]
206 def get_network_id(neutron_client, network_name):
207 networks = neutron_client.list_networks()['networks']
210 if n['name'] == network_name:
216 def check_neutron_net(neutron_client, net_name):
217 for network in neutron_client.list_networks()['networks']:
218 if network['name'] == net_name:
219 for subnet in network['subnets']:
224 def get_network_list(neutron_client):
225 network_list = neutron_client.list_networks()['networks']
226 if len(network_list) == 0:
232 def get_external_net(neutron_client):
233 for network in neutron_client.list_networks()['networks']:
234 if network['router:external']:
235 return network['name']
239 def update_sg_quota(neutron_client, tenant_id, sg_quota, sg_rule_quota):
240 json_body = {"quota": {
241 "security_group": sg_quota,
242 "security_group_rule": sg_rule_quota
246 quota = neutron_client.update_quota(tenant_id=tenant_id,
250 print "Error:", sys.exc_info()[0]
253 # ################ GLANCE #################
256 def get_image_id(glance_client, image_name):
257 images = glance_client.images.list()
260 if i.name == image_name:
266 def create_glance_image(glance_client, image_name, file_path, is_public=True):
268 with open(file_path) as fimage:
269 image = glance_client.images.create(name=image_name,
272 container_format="bare",
279 # ################ KEYSTONE #################
280 def get_tenant_id(keystone_client, tenant_name):
281 tenants = keystone_client.tenants.list()
284 if t.name == tenant_name:
290 def get_role_id(keystone_client, role_name):
291 roles = keystone_client.roles.list()
294 if r.name == role_name:
300 def get_user_id(keystone_client, user_name):
301 users = keystone_client.users.list()
304 if u.name == user_name:
310 def create_tenant(keystone_client, tenant_name, tenant_description):
312 tenant = keystone_client.tenants.create(tenant_name,
317 print "Error:", sys.exc_info()[0]
321 def delete_tenant(keystone_client, tenant_id):
323 tenant = keystone_client.tenants.delete(tenant_id)
326 print "Error:", sys.exc_info()[0]
330 def create_user(keystone_client, user_name, user_password,
331 user_email, tenant_id):
333 user = keystone_client.users.create(user_name, user_password,
334 user_email, tenant_id,
338 print "Error:", sys.exc_info()[0]
342 def delete_user(keystone_client, user_id):
344 tenant = keystone_client.users.delete(user_id)
347 print "Error:", sys.exc_info()[0]
351 def add_role_user(keystone_client, user_id, role_id, tenant_id):
353 keystone_client.roles.add_user_role(user_id, role_id, tenant_id)
356 print "Error:", sys.exc_info()[0]
360 # ################ UTILS #################
361 def check_internet_connectivity(url='http://www.opnfv.org/'):
363 Check if there is access to the internet
366 urllib2.urlopen(url, timeout=5)
368 except urllib2.URLError:
372 def download_url(url, dest_path):
374 Download a file to a destination path given a URL
376 name = url.rsplit('/')[-1]
377 dest = dest_path + "/" + name
379 response = urllib2.urlopen(url)
380 except (urllib2.HTTPError, urllib2.URLError):
383 with open(dest, 'wb') as f:
384 f.write(response.read())
388 def execute_command(cmd, logger=None):
390 Execute Linux command
393 logger.debug('Executing command : {}'.format(cmd))
394 output_file = "output.txt"
395 f = open(output_file, 'w+')
396 p = subprocess.call(cmd, shell=True, stdout=f, stderr=subprocess.STDOUT)
398 f = open(output_file, 'r')
400 if result != "" and logger:
406 logger.error("Error when executing command %s" % cmd)
410 def get_git_branch(repo_path):
414 repo = Repo(repo_path)
415 branch = repo.active_branch
419 def get_installer_type(logger=None):
421 Get installer type (fuel, foreman, apex, joid, compass)
424 installer = os.environ['INSTALLER_TYPE']
427 logger.error("Impossible to retrieve the installer type")
433 def get_pod_name(logger=None):
435 Get PoD Name from env variable NODE_NAME
438 return os.environ['NODE_NAME']
441 logger.error("Unable to retrieve the POD name from environment.Using pod name 'unknown-pod'")
445 def push_results_to_db(db_url, case_name, logger, pod_name, git_version, payload):
446 url = db_url + "/results"
447 installer = get_installer_type(logger)
448 params = {"project_name": "functest", "case_name": case_name,
449 "pod_name": pod_name, "installer": installer,
450 "version": git_version, "details": payload}
452 headers = {'Content-Type': 'application/json'}
454 r = requests.post(url, data=json.dumps(params), headers=headers)
458 print "Error:", sys.exc_info()[0]