3 # jose.lausuch@ericsson.com
4 # All rights reserved. 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
7 # http://www.apache.org/licenses/LICENSE-2.0
10 import re, json, os, urllib2, shutil, subprocess, sys
13 def check_credentials():
15 Check if the OpenStack credentials (openrc) are sourced
17 #TODO: there must be a short way to do this, doing if os.environ["something"] == "" throws an error
19 os.environ['OS_AUTH_URL']
23 os.environ['OS_USERNAME']
27 os.environ['OS_PASSWORD']
31 os.environ['OS_TENANT_NAME']
37 def get_credentials(service):
38 """Returns a creds dictionary filled with the following keys:
40 * password/api_key (depending on the service)
41 * tenant_name/project_id (depending on the service)
43 :param service: a string indicating the name of the service
44 requesting the credentials.
46 #TODO: get credentials from the openrc file
48 # Unfortunately, each of the OpenStack client will request slightly
49 # different entries in their credentials dict.
50 if service.lower() in ("nova", "cinder"):
55 tenant = "tenant_name"
57 # The most common way to pass these info to the script is to do it through
58 # environment variables.
60 "username": os.environ.get('OS_USERNAME', "admin"), # add your cloud username details
61 password: os.environ.get("OS_PASSWORD", 'admin'), # add password
62 "auth_url": os.environ.get("OS_AUTH_URL","http://192.168.20.71:5000/v2.0"), # Auth URL
63 tenant: os.environ.get("OS_TENANT_NAME", "admin"),
70 def get_instance_status(nova_client,instance):
72 instance = nova_client.servers.get(instance.id)
73 return instance.status
78 def get_instance_by_name(nova_client, instance_name):
80 instance = nova_client.servers.find(name=instance_name)
87 def create_neutron_net(neutron_client, name):
88 json_body = {'network': {'name': name,
89 'admin_state_up': True}}
91 network = neutron_client.create_network(body=json_body)
92 network_dict = network['network']
93 return network_dict['id']
95 print "Error:", sys.exc_info()[0]
98 def delete_neutron_net(neutron_client, network_id):
100 neutron_client.delete_network(network_id)
103 print "Error:", sys.exc_info()[0]
106 def create_neutron_subnet(neutron_client, name, cidr, net_id):
107 json_body = {'subnets': [{'name': name, 'cidr': cidr,
108 'ip_version': 4, 'network_id': net_id}]}
110 subnet = neutron_client.create_subnet(body=json_body)
111 return subnet['subnets'][0]['id']
113 print "Error:", sys.exc_info()[0]
116 def delete_neutron_subnet(neutron_client, subnet_id):
118 neutron_client.delete_subnet(subnet_id)
121 print "Error:", sys.exc_info()[0]
124 def create_neutron_router(neutron_client, name):
125 json_body = {'router': {'name': name, 'admin_state_up': True}}
127 router = neutron_client.create_router(json_body)
128 return router['router']['id']
130 print "Error:", sys.exc_info()[0]
133 def delete_neutron_router(neutron_client, router_id):
134 json_body = {'router': {'id': router_id}}
136 neutron_client.delete_router(router=router_id)
139 print "Error:", sys.exc_info()[0]
143 def add_interface_router(neutron_client, router_id, subnet_id):
144 json_body = {"subnet_id": subnet_id}
146 neutron_client.add_interface_router(router=router_id, body=json_body)
149 print "Error:", sys.exc_info()[0]
153 def remove_interface_router(neutron_client, router_id, subnet_id):
154 json_body = {"subnet_id": subnet_id}
156 neutron_client.remove_interface_router(router=router_id, body=json_body)
159 print "Error:", sys.exc_info()[0]
162 def create_neutron_port(neutron_client, name, network_id, ip):
163 json_body = {'port': {
164 'admin_state_up': True,
166 'network_id': network_id,
167 'fixed_ips': [{"ip_address": ip}]
170 port = neutron_client.create_port(body=json_body)
171 return port['port']['id']
173 print "Error:", sys.exc_info()[0]
177 def get_network_id(neutron_client, network_name):
178 networks = neutron_client.list_networks()['networks']
181 if n['name'] == network_name:
186 def check_neutron_net(neutron_client, net_name):
187 for network in neutron_client.list_networks()['networks']:
188 if network['name'] == net_name :
189 for subnet in network['subnets']:
195 def check_internet_connectivity(url='http://www.opnfv.org/'):
197 Check if there is access to the internet
200 urllib2.urlopen(url, timeout=5)
202 except urllib.URLError:
206 def download_url(url, dest_path):
208 Download a file to a destination path given a URL
210 name = url.rsplit('/')[-1]
211 dest = dest_path + name
213 response = urllib2.urlopen(url)
214 except (urllib2.HTTPError, urllib2.URLError):
217 with open(dest, 'wb') as f:
218 f.write(response.read())
222 def execute_command(cmd, logger=None):
224 Execute Linux command
227 logger.debug('Executing command : {}'.format(cmd))
228 output_file = "output.txt"
229 f = open(output_file, 'w+')
230 p = subprocess.call(cmd,shell=True, stdout=f, stderr=subprocess.STDOUT)
232 f = open(output_file, 'r')
234 if result != "" and logger:
240 logger.error("Error when executing command %s" %cmd)