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']
35 os.environ['OS_REGION_NAME']
41 def get_credentials(service):
42 """Returns a creds dictionary filled with the following keys:
44 * password/api_key (depending on the service)
45 * tenant_name/project_id (depending on the service)
47 :param service: a string indicating the name of the service
48 requesting the credentials.
50 #TODO: get credentials from the openrc file
52 # Unfortunately, each of the OpenStack client will request slightly
53 # different entries in their credentials dict.
54 if service.lower() in ("nova", "cinder"):
59 tenant = "tenant_name"
61 # The most common way to pass these info to the script is to do it through
62 # environment variables.
64 "username": os.environ.get('OS_USERNAME', "admin"), # add your cloud username details
65 password: os.environ.get("OS_PASSWORD", 'admin'), # add password
66 "auth_url": os.environ.get("OS_AUTH_URL","http://192.168.20.71:5000/v2.0"), # Auth URL
67 tenant: os.environ.get("OS_TENANT_NAME", "admin"),
74 def get_instance_status(nova_client,instance):
76 instance = nova_client.servers.get(instance.id)
77 return instance.status
82 def get_instance_by_name(nova_client, instance_name):
84 instance = nova_client.servers.find(name=instance_name)
91 def create_neutron_net(neutron_client, name):
92 json_body = {'network': {'name': name,
93 'admin_state_up': True}}
95 network = neutron_client.create_network(body=json_body)
96 network_dict = network['network']
97 return network_dict['id']
99 print "Error:", sys.exc_info()[0]
102 def delete_neutron_net(neutron_client, network_id):
104 neutron_client.delete_network(network_id)
107 print "Error:", sys.exc_info()[0]
110 def create_neutron_subnet(neutron_client, name, cidr, net_id):
111 json_body = {'subnets': [{'name': name, 'cidr': cidr,
112 'ip_version': 4, 'network_id': net_id}]}
114 subnet = neutron_client.create_subnet(body=json_body)
115 return subnet['subnets'][0]['id']
117 print "Error:", sys.exc_info()[0]
120 def delete_neutron_subnet(neutron_client, subnet_id):
122 neutron_client.delete_subnet(subnet_id)
125 print "Error:", sys.exc_info()[0]
128 def create_neutron_router(neutron_client, name):
129 json_body = {'router': {'name': name, 'admin_state_up': True}}
131 router = neutron_client.create_router(json_body)
132 return router['router']['id']
134 print "Error:", sys.exc_info()[0]
137 def delete_neutron_router(neutron_client, router_id):
138 json_body = {'router': {'id': router_id}}
140 neutron_client.delete_router(router=router_id)
143 print "Error:", sys.exc_info()[0]
147 def add_interface_router(neutron_client, router_id, subnet_id):
148 json_body = {"subnet_id": subnet_id}
150 neutron_client.add_interface_router(router=router_id, body=json_body)
153 print "Error:", sys.exc_info()[0]
157 def remove_interface_router(neutron_client, router_id, subnet_id):
158 json_body = {"subnet_id": subnet_id}
160 neutron_client.remove_interface_router(router=router_id, body=json_body)
163 print "Error:", sys.exc_info()[0]
166 def create_neutron_port(neutron_client, name, network_id, ip):
167 json_body = {'port': {
168 'admin_state_up': True,
170 'network_id': network_id,
171 'fixed_ips': [{"ip_address": ip}]
174 port = neutron_client.create_port(body=json_body)
175 return port['port']['id']
177 print "Error:", sys.exc_info()[0]
181 def get_network_id(neutron_client, network_name):
182 networks = neutron_client.list_networks()['networks']
185 if n['name'] == network_name:
190 def check_neutron_net(neutron_client, net_name):
191 for network in neutron_client.list_networks()['networks']:
192 if network['name'] == net_name :
193 for subnet in network['subnets']:
199 def check_internet_connectivity(url='http://www.google.com/'):
201 Check if there is access to the internet
204 urllib2.urlopen(url, timeout=5)
206 except urllib.request.URLError:
210 def download_url(url, dest_path):
212 Download a file to a destination path given a URL
214 name = url.rsplit('/')[-1]
215 dest = dest_path + name
217 response = urllib2.urlopen(url)
218 except (urllib2.HTTPError, urllib2.URLError):
221 with open(dest, 'wb') as f:
222 f.write(response.read())
226 def execute_command(cmd, logger=None):
228 Execute Linux command
231 logger.debug('Executing command : {}'.format(cmd))
232 output_file = "output.txt"
233 f = open(output_file, 'w+')
234 p = subprocess.call(cmd,shell=True, stdout=f, stderr=subprocess.STDOUT)
236 f = open(output_file, 'r')
238 if result != "" and logger:
244 logger.error("Error when executing command %s" %cmd)