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
19 # ############ CREDENTIALS OPENSTACK #############
20 def check_credentials():
22 Check if the OpenStack credentials (openrc) are sourced
24 # TODO: there must be a short way to do this
25 # doing if os.environ["something"] == "" throws an error
27 os.environ['OS_AUTH_URL']
31 os.environ['OS_USERNAME']
35 os.environ['OS_PASSWORD']
39 os.environ['OS_TENANT_NAME']
45 def get_credentials(service):
46 """Returns a creds dictionary filled with the following keys:
48 * password/api_key (depending on the service)
49 * tenant_name/project_id (depending on the service)
51 :param service: a string indicating the name of the service
52 requesting the credentials.
55 # Unfortunately, each of the OpenStack client will request slightly
56 # different entries in their credentials dict.
57 if service.lower() in ("nova", "cinder"):
62 tenant = "tenant_name"
64 # The most common way to pass these info to the script is to do it through
65 # environment variables.
67 "username": os.environ.get('OS_USERNAME', "admin"),
68 password: os.environ.get("OS_PASSWORD", 'admin'),
69 "auth_url": os.environ.get("OS_AUTH_URL",
70 "http://192.168.20.71:5000/v2.0"),
71 tenant: os.environ.get("OS_TENANT_NAME", "admin"),
77 # ################ NOVA #################
78 def get_instance_status(nova_client, instance):
80 instance = nova_client.servers.get(instance.id)
81 return instance.status
86 def get_instance_by_name(nova_client, instance_name):
88 instance = nova_client.servers.find(name=instance_name)
94 def get_flavor_id(nova_client, flavor_name):
95 flavors = nova_client.flavors.list(detailed=True)
98 if f.name == flavor_name:
104 def get_flavor_id_by_ram_range(nova_client, min_ram, max_ram):
105 flavors = nova_client.flavors.list(detailed=True)
108 if min_ram <= f.ram and f.ram <= max_ram:
114 # ################ NEUTRON #################
115 def create_neutron_net(neutron_client, name):
116 json_body = {'network': {'name': name,
117 'admin_state_up': True}}
119 network = neutron_client.create_network(body=json_body)
120 network_dict = network['network']
121 return network_dict['id']
123 print "Error:", sys.exc_info()[0]
127 def delete_neutron_net(neutron_client, network_id):
129 neutron_client.delete_network(network_id)
132 print "Error:", sys.exc_info()[0]
136 def create_neutron_subnet(neutron_client, name, cidr, net_id):
137 json_body = {'subnets': [{'name': name, 'cidr': cidr,
138 'ip_version': 4, 'network_id': net_id}]}
140 subnet = neutron_client.create_subnet(body=json_body)
141 return subnet['subnets'][0]['id']
143 print "Error:", sys.exc_info()[0]
147 def delete_neutron_subnet(neutron_client, subnet_id):
149 neutron_client.delete_subnet(subnet_id)
152 print "Error:", sys.exc_info()[0]
156 def create_neutron_router(neutron_client, name):
157 json_body = {'router': {'name': name, 'admin_state_up': True}}
159 router = neutron_client.create_router(json_body)
160 return router['router']['id']
162 print "Error:", sys.exc_info()[0]
166 def delete_neutron_router(neutron_client, router_id):
167 json_body = {'router': {'id': router_id}}
169 neutron_client.delete_router(router=router_id)
172 print "Error:", sys.exc_info()[0]
176 def add_interface_router(neutron_client, router_id, subnet_id):
177 json_body = {"subnet_id": subnet_id}
179 neutron_client.add_interface_router(router=router_id, body=json_body)
182 print "Error:", sys.exc_info()[0]
186 def remove_interface_router(neutron_client, router_id, subnet_id):
187 json_body = {"subnet_id": subnet_id}
189 neutron_client.remove_interface_router(router=router_id,
193 print "Error:", sys.exc_info()[0]
197 def create_neutron_port(neutron_client, name, network_id, ip):
198 json_body = {'port': {
199 'admin_state_up': True,
201 'network_id': network_id,
202 'fixed_ips': [{"ip_address": ip}]
205 port = neutron_client.create_port(body=json_body)
206 return port['port']['id']
208 print "Error:", sys.exc_info()[0]
212 def get_network_id(neutron_client, network_name):
213 networks = neutron_client.list_networks()['networks']
216 if n['name'] == network_name:
222 def check_neutron_net(neutron_client, net_name):
223 for network in neutron_client.list_networks()['networks']:
224 if network['name'] == net_name:
225 for subnet in network['subnets']:
230 def get_network_list(neutron_client):
231 network_list = neutron_client.list_networks()['networks']
232 if len(network_list) == 0:
238 def get_external_net(neutron_client):
239 for network in neutron_client.list_networks()['networks']:
240 if network['router:external']:
241 return network['name']
245 def update_sg_quota(neutron_client, tenant_id, sg_quota, sg_rule_quota):
246 json_body = {"quota": {
247 "security_group": sg_quota,
248 "security_group_rule": sg_rule_quota
252 quota = neutron_client.update_quota(tenant_id=tenant_id,
256 print "Error:", sys.exc_info()[0]
259 # ################ GLANCE #################
262 def get_image_id(glance_client, image_name):
263 images = glance_client.images.list()
266 if i.name == image_name:
272 def create_glance_image(glance_client, image_name, file_path, is_public=True):
274 with open(file_path) as fimage:
275 image = glance_client.images.create(name=image_name,
278 container_format="bare",
285 # ################ KEYSTONE #################
286 def get_tenant_id(keystone_client, tenant_name):
287 tenants = keystone_client.tenants.list()
290 if t.name == tenant_name:
296 def get_role_id(keystone_client, role_name):
297 roles = keystone_client.roles.list()
300 if r.name == role_name:
306 def get_user_id(keystone_client, user_name):
307 users = keystone_client.users.list()
310 if u.name == user_name:
316 def create_tenant(keystone_client, tenant_name, tenant_description):
318 tenant = keystone_client.tenants.create(tenant_name,
323 print "Error:", sys.exc_info()[0]
327 def delete_tenant(keystone_client, tenant_id):
329 tenant = keystone_client.tenants.delete(tenant_id)
332 print "Error:", sys.exc_info()[0]
336 def create_user(keystone_client, user_name, user_password,
337 user_email, tenant_id):
339 user = keystone_client.users.create(user_name, user_password,
340 user_email, tenant_id,
344 print "Error:", sys.exc_info()[0]
348 def delete_user(keystone_client, user_id):
350 tenant = keystone_client.users.delete(user_id)
353 print "Error:", sys.exc_info()[0]
357 def add_role_user(keystone_client, user_id, role_id, tenant_id):
359 keystone_client.roles.add_user_role(user_id, role_id, tenant_id)
362 print "Error:", sys.exc_info()[0]
366 # ################ UTILS #################
367 def check_internet_connectivity(url='http://www.opnfv.org/'):
369 Check if there is access to the internet
372 urllib2.urlopen(url, timeout=5)
374 except urllib2.URLError:
378 def download_url(url, dest_path):
380 Download a file to a destination path given a URL
382 name = url.rsplit('/')[-1]
383 dest = dest_path + "/" + name
385 response = urllib2.urlopen(url)
386 except (urllib2.HTTPError, urllib2.URLError):
389 with open(dest, 'wb') as f:
390 f.write(response.read())
394 def execute_command(cmd, logger=None):
396 Execute Linux command
399 logger.debug('Executing command : {}'.format(cmd))
400 output_file = "output.txt"
401 f = open(output_file, 'w+')
402 p = subprocess.call(cmd, shell=True, stdout=f, stderr=subprocess.STDOUT)
404 f = open(output_file, 'r')
406 if result != "" and logger:
412 logger.error("Error when executing command %s" % cmd)
416 def get_git_branch(repo_path):
420 repo = Repo(repo_path)
421 branch = repo.active_branch
426 def get_installer_type(logger=None):
428 Get installer type (fuel, foreman, apex, joid, compass)
431 installer = os.environ['INSTALLER_TYPE']
434 logger.error("Impossible to retrieve the installer type")