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 # TODO: there must be a short way to do this
27 # doing if os.environ["something"] == "" throws an error
29 os.environ['OS_AUTH_URL']
33 os.environ['OS_USERNAME']
37 os.environ['OS_PASSWORD']
41 os.environ['OS_TENANT_NAME']
47 def get_credentials(service):
48 """Returns a creds dictionary filled with the following keys:
50 * password/api_key (depending on the service)
51 * tenant_name/project_id (depending on the service)
53 :param service: a string indicating the name of the service
54 requesting the credentials.
57 # Unfortunately, each of the OpenStack client will request slightly
58 # different entries in their credentials dict.
59 if service.lower() in ("nova", "cinder"):
64 tenant = "tenant_name"
66 # The most common way to pass these info to the script is to do it through
67 # environment variables.
69 "username": os.environ.get('OS_USERNAME', "admin"),
70 password: os.environ.get("OS_PASSWORD", 'admin'),
71 "auth_url": os.environ.get("OS_AUTH_URL",
72 "http://192.168.20.71:5000/v2.0"),
73 tenant: os.environ.get("OS_TENANT_NAME", "admin"),
79 # ################ NOVA #################
80 def get_instance_status(nova_client, instance):
82 instance = nova_client.servers.get(instance.id)
83 return instance.status
88 def get_instance_by_name(nova_client, instance_name):
90 instance = nova_client.servers.find(name=instance_name)
96 def get_flavor_id(nova_client, flavor_name):
97 flavors = nova_client.flavors.list(detailed=True)
100 if f.name == flavor_name:
106 def get_flavor_id_by_ram_range(nova_client, min_ram, max_ram):
107 flavors = nova_client.flavors.list(detailed=True)
110 if min_ram <= f.ram and f.ram <= max_ram:
116 # ################ NEUTRON #################
117 def create_neutron_net(neutron_client, name):
118 json_body = {'network': {'name': name,
119 'admin_state_up': True}}
121 network = neutron_client.create_network(body=json_body)
122 network_dict = network['network']
123 return network_dict['id']
125 print "Error:", sys.exc_info()[0]
129 def delete_neutron_net(neutron_client, network_id):
131 neutron_client.delete_network(network_id)
134 print "Error:", sys.exc_info()[0]
138 def create_neutron_subnet(neutron_client, name, cidr, net_id):
139 json_body = {'subnets': [{'name': name, 'cidr': cidr,
140 'ip_version': 4, 'network_id': net_id}]}
142 subnet = neutron_client.create_subnet(body=json_body)
143 return subnet['subnets'][0]['id']
145 print "Error:", sys.exc_info()[0]
149 def delete_neutron_subnet(neutron_client, subnet_id):
151 neutron_client.delete_subnet(subnet_id)
154 print "Error:", sys.exc_info()[0]
158 def create_neutron_router(neutron_client, name):
159 json_body = {'router': {'name': name, 'admin_state_up': True}}
161 router = neutron_client.create_router(json_body)
162 return router['router']['id']
164 print "Error:", sys.exc_info()[0]
168 def delete_neutron_router(neutron_client, router_id):
169 json_body = {'router': {'id': router_id}}
171 neutron_client.delete_router(router=router_id)
174 print "Error:", sys.exc_info()[0]
178 def add_interface_router(neutron_client, router_id, subnet_id):
179 json_body = {"subnet_id": subnet_id}
181 neutron_client.add_interface_router(router=router_id, body=json_body)
184 print "Error:", sys.exc_info()[0]
188 def remove_interface_router(neutron_client, router_id, subnet_id):
189 json_body = {"subnet_id": subnet_id}
191 neutron_client.remove_interface_router(router=router_id,
195 print "Error:", sys.exc_info()[0]
199 def create_neutron_port(neutron_client, name, network_id, ip):
200 json_body = {'port': {
201 'admin_state_up': True,
203 'network_id': network_id,
204 'fixed_ips': [{"ip_address": ip}]
207 port = neutron_client.create_port(body=json_body)
208 return port['port']['id']
210 print "Error:", sys.exc_info()[0]
213 def delete_neutron_port(neutron_client, port_id):
215 neutron_client.delete_port(port_id)
218 print "Error:", sys.exc_info()[0]
221 def get_network_id(neutron_client, network_name):
222 networks = neutron_client.list_networks()['networks']
225 if n['name'] == network_name:
231 def check_neutron_net(neutron_client, net_name):
232 for network in neutron_client.list_networks()['networks']:
233 if network['name'] == net_name:
234 for subnet in network['subnets']:
239 def get_network_list(neutron_client):
240 network_list = neutron_client.list_networks()['networks']
241 if len(network_list) == 0:
247 def get_external_net(neutron_client):
248 for network in neutron_client.list_networks()['networks']:
249 if network['router:external']:
250 return network['name']
254 def update_sg_quota(neutron_client, tenant_id, sg_quota, sg_rule_quota):
255 json_body = {"quota": {
256 "security_group": sg_quota,
257 "security_group_rule": sg_rule_quota
261 quota = neutron_client.update_quota(tenant_id=tenant_id,
265 print "Error:", sys.exc_info()[0]
268 # ################ GLANCE #################
271 def get_image_id(glance_client, image_name):
272 images = glance_client.images.list()
275 if i.name == image_name:
281 def create_glance_image(glance_client, image_name, file_path, is_public=True):
283 with open(file_path) as fimage:
284 image = glance_client.images.create(name=image_name,
287 container_format="bare",
294 # ################ KEYSTONE #################
295 def get_tenant_id(keystone_client, tenant_name):
296 tenants = keystone_client.tenants.list()
299 if t.name == tenant_name:
305 def get_role_id(keystone_client, role_name):
306 roles = keystone_client.roles.list()
309 if r.name == role_name:
315 def get_user_id(keystone_client, user_name):
316 users = keystone_client.users.list()
319 if u.name == user_name:
325 def create_tenant(keystone_client, tenant_name, tenant_description):
327 tenant = keystone_client.tenants.create(tenant_name,
332 print "Error:", sys.exc_info()[0]
336 def delete_tenant(keystone_client, tenant_id):
338 tenant = keystone_client.tenants.delete(tenant_id)
341 print "Error:", sys.exc_info()[0]
345 def create_user(keystone_client, user_name, user_password,
346 user_email, tenant_id):
348 user = keystone_client.users.create(user_name, user_password,
349 user_email, tenant_id,
353 print "Error:", sys.exc_info()[0]
357 def delete_user(keystone_client, user_id):
359 tenant = keystone_client.users.delete(user_id)
362 print "Error:", sys.exc_info()[0]
366 def add_role_user(keystone_client, user_id, role_id, tenant_id):
368 keystone_client.roles.add_user_role(user_id, role_id, tenant_id)
371 print "Error:", sys.exc_info()[0]
375 # ################ UTILS #################
376 def check_internet_connectivity(url='http://www.opnfv.org/'):
378 Check if there is access to the internet
381 urllib2.urlopen(url, timeout=5)
383 except urllib2.URLError:
387 def download_url(url, dest_path):
389 Download a file to a destination path given a URL
391 name = url.rsplit('/')[-1]
392 dest = dest_path + "/" + name
394 response = urllib2.urlopen(url)
395 except (urllib2.HTTPError, urllib2.URLError):
398 with open(dest, 'wb') as f:
399 f.write(response.read())
403 def execute_command(cmd, logger=None):
405 Execute Linux command
408 logger.debug('Executing command : {}'.format(cmd))
409 output_file = "output.txt"
410 f = open(output_file, 'w+')
411 p = subprocess.call(cmd, shell=True, stdout=f, stderr=subprocess.STDOUT)
413 f = open(output_file, 'r')
415 if result != "" and logger:
421 logger.error("Error when executing command %s" % cmd)
425 def get_git_branch(repo_path):
429 repo = Repo(repo_path)
430 branch = repo.active_branch
434 def get_installer_type(logger=None):
436 Get installer type (fuel, foreman, apex, joid, compass)
439 installer = os.environ['INSTALLER_TYPE']
442 logger.error("Impossible to retrieve the installer type")
447 def push_results_to_db(db_url, case_name, logger, pod_name, git_version, payload):
448 url = db_url + "/results"
449 installer = get_installer_type(logger)
450 params = {"project_name": "functest", "case_name": case_name,
451 "pod_name": pod_name, "installer": installer,
452 "version": git_version, "details": payload}
454 headers = {'Content-Type': 'application/json'}
456 r = requests.post(url, data=json.dumps(params), headers=headers)
460 print "Error:", sys.exc_info()[0]