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
11 import re, json, os, urllib2, shutil, subprocess, sys
13 ############# CREDENTIALS OPENSTACK #############
14 def check_credentials():
16 Check if the OpenStack credentials (openrc) are sourced
18 #TODO: there must be a short way to do this, doing if os.environ["something"] == "" throws an error
20 os.environ['OS_AUTH_URL']
24 os.environ['OS_USERNAME']
28 os.environ['OS_PASSWORD']
32 os.environ['OS_TENANT_NAME']
38 def get_credentials(service):
39 """Returns a creds dictionary filled with the following keys:
41 * password/api_key (depending on the service)
42 * tenant_name/project_id (depending on the service)
44 :param service: a string indicating the name of the service
45 requesting the credentials.
47 #TODO: get credentials from the openrc file
49 # Unfortunately, each of the OpenStack client will request slightly
50 # different entries in their credentials dict.
51 if service.lower() in ("nova", "cinder"):
56 tenant = "tenant_name"
58 # The most common way to pass these info to the script is to do it through
59 # environment variables.
61 "username": os.environ.get('OS_USERNAME', "admin"), # add your cloud username details
62 password: os.environ.get("OS_PASSWORD", 'admin'), # add password
63 "auth_url": os.environ.get("OS_AUTH_URL","http://192.168.20.71:5000/v2.0"), # Auth URL
64 tenant: os.environ.get("OS_TENANT_NAME", "admin"),
70 ################# NOVA #################
71 def get_instance_status(nova_client,instance):
73 instance = nova_client.servers.get(instance.id)
74 return instance.status
79 def get_instance_by_name(nova_client, instance_name):
81 instance = nova_client.servers.find(name=instance_name)
87 def get_flavor_id(nova_client, flavor_name):
88 flavors = nova_client.flavors.list(detailed=True)
91 if f.name == flavor_name:
97 def get_flavor_id_by_ram_range(nova_client, min_ram, max_ram):
98 flavors = nova_client.flavors.list(detailed=True)
101 if min_ram <= f.ram and f.ram <= max_ram:
107 ################# NEUTRON #################
108 def create_neutron_net(neutron_client, name):
109 json_body = {'network': {'name': name,
110 'admin_state_up': True}}
112 network = neutron_client.create_network(body=json_body)
113 network_dict = network['network']
114 return network_dict['id']
116 print "Error:", sys.exc_info()[0]
119 def delete_neutron_net(neutron_client, network_id):
121 neutron_client.delete_network(network_id)
124 print "Error:", sys.exc_info()[0]
127 def create_neutron_subnet(neutron_client, name, cidr, net_id):
128 json_body = {'subnets': [{'name': name, 'cidr': cidr,
129 'ip_version': 4, 'network_id': net_id}]}
131 subnet = neutron_client.create_subnet(body=json_body)
132 return subnet['subnets'][0]['id']
134 print "Error:", sys.exc_info()[0]
137 def delete_neutron_subnet(neutron_client, subnet_id):
139 neutron_client.delete_subnet(subnet_id)
142 print "Error:", sys.exc_info()[0]
145 def create_neutron_router(neutron_client, name):
146 json_body = {'router': {'name': name, 'admin_state_up': True}}
148 router = neutron_client.create_router(json_body)
149 return router['router']['id']
151 print "Error:", sys.exc_info()[0]
154 def delete_neutron_router(neutron_client, router_id):
155 json_body = {'router': {'id': router_id}}
157 neutron_client.delete_router(router=router_id)
160 print "Error:", sys.exc_info()[0]
164 def add_interface_router(neutron_client, router_id, subnet_id):
165 json_body = {"subnet_id": subnet_id}
167 neutron_client.add_interface_router(router=router_id, body=json_body)
170 print "Error:", sys.exc_info()[0]
174 def remove_interface_router(neutron_client, router_id, subnet_id):
175 json_body = {"subnet_id": subnet_id}
177 neutron_client.remove_interface_router(router=router_id, body=json_body)
180 print "Error:", sys.exc_info()[0]
183 def create_neutron_port(neutron_client, name, network_id, ip):
184 json_body = {'port': {
185 'admin_state_up': True,
187 'network_id': network_id,
188 'fixed_ips': [{"ip_address": ip}]
191 port = neutron_client.create_port(body=json_body)
192 return port['port']['id']
194 print "Error:", sys.exc_info()[0]
198 def get_network_id(neutron_client, network_name):
199 networks = neutron_client.list_networks()['networks']
202 if n['name'] == network_name:
207 def check_neutron_net(neutron_client, net_name):
208 for network in neutron_client.list_networks()['networks']:
209 if network['name'] == net_name :
210 for subnet in network['subnets']:
214 def get_network_list(neutron_client):
215 network_list = neutron_client.list_networks()['networks']
216 if len(network_list) == 0 :
221 def get_external_net(neutron_client):
222 for network in neutron_client.list_networks()['networks']:
223 if network['router:external']:
224 return network['name']
227 def update_sg_quota(neutron_client, tenant_id, sg_quota, sg_rule_quota):
228 json_body = {"quota": {
229 "security_group": sg_quota,
230 "security_group_rule": sg_rule_quota
234 quota = neutron_client.update_quota(tenant_id=tenant_id, body=json_body)
237 print "Error:", sys.exc_info()[0]
240 ################# GLANCE #################
242 def get_image_id(glance_client, image_name):
243 images = glance_client.images.list()
246 if i.name == image_name:
251 def create_glance_image(glance_client, image_name, file_path, is_public=True):
253 with open(file_path) as fimage:
254 image = glance_client.images.create(name=image_name, is_public=is_public, disk_format="qcow2",
255 container_format="bare", data=fimage)
261 ################# KEYSTONE #################
262 def get_tenant_id(keystone_client, tenant_name):
263 tenants = keystone_client.tenants.list()
266 if t.name == tenant_name:
271 def get_role_id(keystone_client, role_name):
272 roles = keystone_client.roles.list()
275 if r.name == role_name:
280 def get_user_id(keystone_client, user_name):
281 users = keystone_client.users.list()
284 if u.name == user_name:
289 def create_tenant(keystone_client, tenant_name, tenant_description):
291 tenant = keystone_client.tenants.create(tenant_name, tenant_description, enabled=True)
294 print "Error:", sys.exc_info()[0]
297 def delete_tenant(keystone_client, tenant_id):
299 tenant = keystone_client.tenants.delete(tenant_id)
302 print "Error:", sys.exc_info()[0]
305 def create_user(keystone_client, user_name, user_password, user_email, tenant_id):
307 user = keystone_client.users.create(user_name, user_password, user_email, tenant_id, enabled=True)
310 print "Error:", sys.exc_info()[0]
313 def delete_user(keystone_client, user_id):
315 tenant = keystone_client.users.delete(user_id)
318 print "Error:", sys.exc_info()[0]
321 def add_role_user(keystone_client, user_id, role_id, tenant_id):
323 keystone_client.roles.add_user_role(user_id, role_id, tenant_id)
326 print "Error:", sys.exc_info()[0]
330 ################# UTILS #################
331 def check_internet_connectivity(url='http://www.opnfv.org/'):
333 Check if there is access to the internet
336 urllib2.urlopen(url, timeout=5)
338 except urllib.URLError:
342 def download_url(url, dest_path):
344 Download a file to a destination path given a URL
346 name = url.rsplit('/')[-1]
347 dest = dest_path + name
349 response = urllib2.urlopen(url)
350 except (urllib2.HTTPError, urllib2.URLError):
353 with open(dest, 'wb') as f:
354 f.write(response.read())
358 def execute_command(cmd, logger=None):
360 Execute Linux command
363 logger.debug('Executing command : {}'.format(cmd))
364 output_file = "output.txt"
365 f = open(output_file, 'w+')
366 p = subprocess.call(cmd,shell=True, stdout=f, stderr=subprocess.STDOUT)
368 f = open(output_file, 'r')
370 if result != "" and logger:
376 logger.error("Error when executing command %s" %cmd)