blob: 81c6591531ed7578b447c9be3d76b59fd4be0d34 [file] [log] [blame]
tierno7edb6752016-03-21 17:37:52 +01001# -*- coding: utf-8 -*-
2
3##
4# Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U.
5# This file is part of openmano
6# All Rights Reserved.
7#
8# Licensed under the Apache License, Version 2.0 (the "License"); you may
9# not use this file except in compliance with the License. You may obtain
10# a copy of the License at
11#
12# http://www.apache.org/licenses/LICENSE-2.0
13#
14# Unless required by applicable law or agreed to in writing, software
15# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17# License for the specific language governing permissions and limitations
18# under the License.
19#
20# For those usages not covered by the Apache License, Version 2.0 please
21# contact with: nfvlabs@tid.es
22##
23
24'''
25osconnector implements all the methods to interact with openstack using the python-client.
26'''
ahmadsa95baa272016-11-30 09:14:11 +050027__author__="Alfonso Tierno, Gerardo Garcia, xFlow Research"
28__date__ ="$24-nov-2016 09:10$"
tierno7edb6752016-03-21 17:37:52 +010029
30import vimconn
31import json
32import yaml
tiernoae4a8d12016-07-08 12:30:39 +020033import logging
garciadeblas9f8456e2016-09-05 05:02:59 +020034import netaddr
tierno7edb6752016-03-21 17:37:52 +010035
ahmadsa95baa272016-11-30 09:14:11 +050036from novaclient import client as nClient_v2, exceptions as nvExceptions, api_versions as APIVersion
37import keystoneclient.v2_0.client as ksClient_v2
38from novaclient.v2.client import Client as nClient
39import keystoneclient.v3.client as ksClient
tierno7edb6752016-03-21 17:37:52 +010040import keystoneclient.exceptions as ksExceptions
41import glanceclient.v2.client as glClient
42import glanceclient.client as gl1Client
43import glanceclient.exc as gl1Exceptions
44from httplib import HTTPException
ahmadsa95baa272016-11-30 09:14:11 +050045from neutronclient.neutron import client as neClient_v2
46from neutronclient.v2_0 import client as neClient
tierno7edb6752016-03-21 17:37:52 +010047from neutronclient.common import exceptions as neExceptions
48from requests.exceptions import ConnectionError
49
50'''contain the openstack virtual machine status to openmano status'''
51vmStatus2manoFormat={'ACTIVE':'ACTIVE',
52 'PAUSED':'PAUSED',
53 'SUSPENDED': 'SUSPENDED',
54 'SHUTOFF':'INACTIVE',
55 'BUILD':'BUILD',
56 'ERROR':'ERROR','DELETED':'DELETED'
57 }
58netStatus2manoFormat={'ACTIVE':'ACTIVE','PAUSED':'PAUSED','INACTIVE':'INACTIVE','BUILD':'BUILD','ERROR':'ERROR','DELETED':'DELETED'
59 }
60
61class vimconnector(vimconn.vimconnector):
tiernofe789902016-09-29 14:20:44 +000062 def __init__(self, uuid, name, tenant_id, tenant_name, url, url_admin=None, user=None, passwd=None, log_level=None, config={}):
tierno7edb6752016-03-21 17:37:52 +010063 '''using common constructor parameters. In this case
64 'url' is the keystone authorization url,
65 'url_admin' is not use
66 '''
ahmadsa95baa272016-11-30 09:14:11 +050067 self.osc_api_version = 'v2.0'
68 if config.get('APIversion') == 'v3.3':
69 self.osc_api_version = 'v3.3'
tiernoae4a8d12016-07-08 12:30:39 +020070 vimconn.vimconnector.__init__(self, uuid, name, tenant_id, tenant_name, url, url_admin, user, passwd, log_level, config)
tierno7edb6752016-03-21 17:37:52 +010071
72 self.k_creds={}
73 self.n_creds={}
74 if not url:
75 raise TypeError, 'url param can not be NoneType'
76 self.k_creds['auth_url'] = url
77 self.n_creds['auth_url'] = url
tierno392f2852016-05-13 12:28:55 +020078 if tenant_name:
79 self.k_creds['tenant_name'] = tenant_name
80 self.n_creds['project_id'] = tenant_name
81 if tenant_id:
82 self.k_creds['tenant_id'] = tenant_id
83 self.n_creds['tenant_id'] = tenant_id
tierno7edb6752016-03-21 17:37:52 +010084 if user:
85 self.k_creds['username'] = user
86 self.n_creds['username'] = user
87 if passwd:
88 self.k_creds['password'] = passwd
89 self.n_creds['api_key'] = passwd
ahmadsa95baa272016-11-30 09:14:11 +050090 if self.osc_api_version == 'v3.3':
91 self.k_creds['project_name'] = tenant_name
92 self.k_creds['project_id'] = tenant_id
tierno7edb6752016-03-21 17:37:52 +010093 self.reload_client = True
tierno73ad9e42016-09-12 18:11:11 +020094 self.logger = logging.getLogger('openmano.vim.openstack')
tiernofe789902016-09-29 14:20:44 +000095 if log_level:
96 self.logger.setLevel( getattr(logging, log_level) )
tierno7edb6752016-03-21 17:37:52 +010097
98 def __setitem__(self,index, value):
99 '''Set individuals parameters
100 Throw TypeError, KeyError
101 '''
tierno392f2852016-05-13 12:28:55 +0200102 if index=='tenant_id':
tierno7edb6752016-03-21 17:37:52 +0100103 self.reload_client=True
tierno392f2852016-05-13 12:28:55 +0200104 self.tenant_id = value
ahmadsa95baa272016-11-30 09:14:11 +0500105 if self.osc_api_version == 'v3.3':
106 if value:
107 self.k_creds['project_id'] = value
108 self.n_creds['project_id'] = value
109 else:
110 del self.k_creds['project_id']
111 del self.n_creds['project_id']
tierno392f2852016-05-13 12:28:55 +0200112 else:
ahmadsa95baa272016-11-30 09:14:11 +0500113 if value:
114 self.k_creds['tenant_id'] = value
115 self.n_creds['tenant_id'] = value
116 else:
117 del self.k_creds['tenant_id']
118 del self.n_creds['tenant_id']
tierno392f2852016-05-13 12:28:55 +0200119 elif index=='tenant_name':
120 self.reload_client=True
121 self.tenant_name = value
ahmadsa95baa272016-11-30 09:14:11 +0500122 if self.osc_api_version == 'v3.3':
123 if value:
124 self.k_creds['project_name'] = value
125 self.n_creds['project_name'] = value
126 else:
127 del self.k_creds['project_name']
128 del self.n_creds['project_name']
tierno7edb6752016-03-21 17:37:52 +0100129 else:
ahmadsa95baa272016-11-30 09:14:11 +0500130 if value:
131 self.k_creds['tenant_name'] = value
132 self.n_creds['project_id'] = value
133 else:
134 del self.k_creds['tenant_name']
135 del self.n_creds['project_id']
tierno7edb6752016-03-21 17:37:52 +0100136 elif index=='user':
137 self.reload_client=True
138 self.user = value
139 if value:
140 self.k_creds['username'] = value
141 self.n_creds['username'] = value
142 else:
143 del self.k_creds['username']
144 del self.n_creds['username']
145 elif index=='passwd':
146 self.reload_client=True
147 self.passwd = value
148 if value:
149 self.k_creds['password'] = value
150 self.n_creds['api_key'] = value
151 else:
152 del self.k_creds['password']
153 del self.n_creds['api_key']
154 elif index=='url':
155 self.reload_client=True
156 self.url = value
157 if value:
158 self.k_creds['auth_url'] = value
159 self.n_creds['auth_url'] = value
160 else:
161 raise TypeError, 'url param can not be NoneType'
162 else:
163 vimconn.vimconnector.__setitem__(self,index, value)
164
165 def _reload_connection(self):
166 '''Called before any operation, it check if credentials has changed
167 Throw keystoneclient.apiclient.exceptions.AuthorizationFailure
168 '''
169 #TODO control the timing and possible token timeout, but it seams that python client does this task for us :-)
170 if self.reload_client:
171 #test valid params
172 if len(self.n_creds) <4:
173 raise ksExceptions.ClientException("Not enough parameters to connect to openstack")
ahmadsa95baa272016-11-30 09:14:11 +0500174 if self.osc_api_version == 'v3.3':
175 self.nova = nClient(APIVersion(version_str='2'), **self.n_creds)
176 self.keystone = ksClient.Client(**self.k_creds)
177 self.ne_endpoint=self.keystone.service_catalog.url_for(service_type='network', endpoint_type='publicURL')
178 self.neutron = neClient.Client(APIVersion(version_str='2'), endpoint_url=self.ne_endpoint, token=self.keystone.auth_token, **self.k_creds)
179 else:
180 self.nova = nClient_v2.Client('2', **self.n_creds)
181 self.keystone = ksClient_v2.Client(**self.k_creds)
182 self.ne_endpoint=self.keystone.service_catalog.url_for(service_type='network', endpoint_type='publicURL')
183 self.neutron = neClient_v2.Client('2.0', endpoint_url=self.ne_endpoint, token=self.keystone.auth_token, **self.k_creds)
tierno7edb6752016-03-21 17:37:52 +0100184 self.glance_endpoint = self.keystone.service_catalog.url_for(service_type='image', endpoint_type='publicURL')
185 self.glance = glClient.Client(self.glance_endpoint, token=self.keystone.auth_token, **self.k_creds) #TODO check k_creds vs n_creds
tierno7edb6752016-03-21 17:37:52 +0100186 self.reload_client = False
ahmadsa95baa272016-11-30 09:14:11 +0500187
tierno7edb6752016-03-21 17:37:52 +0100188 def __net_os2mano(self, net_list_dict):
189 '''Transform the net openstack format to mano format
190 net_list_dict can be a list of dict or a single dict'''
191 if type(net_list_dict) is dict:
192 net_list_=(net_list_dict,)
193 elif type(net_list_dict) is list:
194 net_list_=net_list_dict
195 else:
196 raise TypeError("param net_list_dict must be a list or a dictionary")
197 for net in net_list_:
198 if net.get('provider:network_type') == "vlan":
199 net['type']='data'
200 else:
201 net['type']='bridge'
tiernoae4a8d12016-07-08 12:30:39 +0200202
203
204
205 def _format_exception(self, exception):
206 '''Transform a keystone, nova, neutron exception into a vimconn exception'''
207 if isinstance(exception, (HTTPException, gl1Exceptions.HTTPException, gl1Exceptions.CommunicationError,
tierno8e995ce2016-09-22 08:13:00 +0000208 ConnectionError, ksExceptions.ConnectionError, neExceptions.ConnectionFailed
209 )):
tiernoae4a8d12016-07-08 12:30:39 +0200210 raise vimconn.vimconnConnectionException(type(exception).__name__ + ": " + str(exception))
211 elif isinstance(exception, (nvExceptions.ClientException, ksExceptions.ClientException,
212 neExceptions.NeutronException, nvExceptions.BadRequest)):
213 raise vimconn.vimconnUnexpectedResponse(type(exception).__name__ + ": " + str(exception))
214 elif isinstance(exception, (neExceptions.NetworkNotFoundClient, nvExceptions.NotFound)):
215 raise vimconn.vimconnNotFoundException(type(exception).__name__ + ": " + str(exception))
216 elif isinstance(exception, nvExceptions.Conflict):
217 raise vimconn.vimconnConflictException(type(exception).__name__ + ": " + str(exception))
218 else: # ()
219 raise vimconn.vimconnConnectionException(type(exception).__name__ + ": " + str(exception))
220
221 def get_tenant_list(self, filter_dict={}):
222 '''Obtain tenants of VIM
223 filter_dict can contain the following keys:
224 name: filter by tenant name
225 id: filter by tenant uuid/id
226 <other VIM specific>
227 Returns the tenant list of dictionaries: [{'name':'<name>, 'id':'<id>, ...}, ...]
228 '''
ahmadsa95baa272016-11-30 09:14:11 +0500229 self.logger.debug("Getting tenants from VIM filter: '%s'", str(filter_dict))
tiernoae4a8d12016-07-08 12:30:39 +0200230 try:
231 self._reload_connection()
ahmadsa95baa272016-11-30 09:14:11 +0500232 if osc_api_version == 'v3.3':
233 project_class_list=self.keystone.projects.findall(**filter_dict)
234 else:
235 project_class_list=self.keystone.tenants.findall(**filter_dict)
236 project_list=[]
237 for project in project_class_list:
238 project_list.append(project.to_dict())
239 return project_list
tierno8e995ce2016-09-22 08:13:00 +0000240 except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200241 self._format_exception(e)
242
243 def new_tenant(self, tenant_name, tenant_description):
244 '''Adds a new tenant to openstack VIM. Returns the tenant identifier'''
245 self.logger.debug("Adding a new tenant name: %s", tenant_name)
246 try:
247 self._reload_connection()
ahmadsa95baa272016-11-30 09:14:11 +0500248 if self.osc_api_version == 'v3.3':
249 project=self.keystone.projects.create(tenant_name, tenant_description)
250 else:
251 project=self.keystone.tenants.create(tenant_name, tenant_description)
252 return project.id
tierno8e995ce2016-09-22 08:13:00 +0000253 except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200254 self._format_exception(e)
255
256 def delete_tenant(self, tenant_id):
257 '''Delete a tenant from openstack VIM. Returns the old tenant identifier'''
258 self.logger.debug("Deleting tenant %s from VIM", tenant_id)
259 try:
260 self._reload_connection()
ahmadsa95baa272016-11-30 09:14:11 +0500261 if osc_api_version == 'v3.3':
262 self.keystone.projects.delete(tenant_id)
263 else:
264 self.keystone.tenants.delete(tenant_id)
tiernoae4a8d12016-07-08 12:30:39 +0200265 return tenant_id
tierno8e995ce2016-09-22 08:13:00 +0000266 except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200267 self._format_exception(e)
ahmadsa95baa272016-11-30 09:14:11 +0500268
garciadeblas9f8456e2016-09-05 05:02:59 +0200269 def new_network(self,net_name, net_type, ip_profile=None, shared=False, vlan=None):
tiernoae4a8d12016-07-08 12:30:39 +0200270 '''Adds a tenant network to VIM. Returns the network identifier'''
271 self.logger.debug("Adding a new network to VIM name '%s', type '%s'", net_name, net_type)
garciadeblasedca7b32016-09-29 14:01:52 +0000272 #self.logger.debug(">>>>>>>>>>>>>>>>>> IP profile %s", str(ip_profile))
tierno7edb6752016-03-21 17:37:52 +0100273 try:
garciadeblasedca7b32016-09-29 14:01:52 +0000274 new_net = None
tierno7edb6752016-03-21 17:37:52 +0100275 self._reload_connection()
276 network_dict = {'name': net_name, 'admin_state_up': True}
277 if net_type=="data" or net_type=="ptp":
278 if self.config.get('dataplane_physical_net') == None:
tiernoae4a8d12016-07-08 12:30:39 +0200279 raise vimconn.vimconnConflictException("You must provide a 'dataplane_physical_net' at config value before creating sriov network")
tierno7edb6752016-03-21 17:37:52 +0100280 network_dict["provider:physical_network"] = self.config['dataplane_physical_net'] #"physnet_sriov" #TODO physical
281 network_dict["provider:network_type"] = "vlan"
282 if vlan!=None:
283 network_dict["provider:network_type"] = vlan
tiernoae4a8d12016-07-08 12:30:39 +0200284 network_dict["shared"]=shared
tierno7edb6752016-03-21 17:37:52 +0100285 new_net=self.neutron.create_network({'network':network_dict})
286 #print new_net
garciadeblas9f8456e2016-09-05 05:02:59 +0200287 #create subnetwork, even if there is no profile
288 if not ip_profile:
289 ip_profile = {}
290 if 'subnet_address' not in ip_profile:
291 #Fake subnet is required
292 ip_profile['subnet_address'] = "192.168.111.0/24"
293 if 'ip_version' not in ip_profile:
294 ip_profile['ip_version'] = "IPv4"
tierno7edb6752016-03-21 17:37:52 +0100295 subnet={"name":net_name+"-subnet",
296 "network_id": new_net["network"]["id"],
garciadeblas9f8456e2016-09-05 05:02:59 +0200297 "ip_version": 4 if ip_profile['ip_version']=="IPv4" else 6,
298 "cidr": ip_profile['subnet_address']
tierno7edb6752016-03-21 17:37:52 +0100299 }
garciadeblas9f8456e2016-09-05 05:02:59 +0200300 if 'gateway_address' in ip_profile:
301 subnet['gateway_ip'] = ip_profile['gateway_address']
garciadeblasedca7b32016-09-29 14:01:52 +0000302 if ip_profile.get('dns_address'):
garciadeblas9f8456e2016-09-05 05:02:59 +0200303 #TODO: manage dns_address as a list of addresses separated by commas
304 subnet['dns_nameservers'] = []
305 subnet['dns_nameservers'].append(ip_profile['dns_address'])
306 if 'dhcp_enabled' in ip_profile:
307 subnet['enable_dhcp'] = False if ip_profile['dhcp_enabled']=="false" else True
308 if 'dhcp_start_address' in ip_profile:
309 subnet['allocation_pools']=[]
310 subnet['allocation_pools'].append(dict())
311 subnet['allocation_pools'][0]['start'] = ip_profile['dhcp_start_address']
312 if 'dhcp_count' in ip_profile:
313 #parts = ip_profile['dhcp_start_address'].split('.')
314 #ip_int = (int(parts[0]) << 24) + (int(parts[1]) << 16) + (int(parts[2]) << 8) + int(parts[3])
315 ip_int = int(netaddr.IPAddress(ip_profile['dhcp_start_address']))
garciadeblas21d795b2016-09-29 17:31:46 +0200316 ip_int += ip_profile['dhcp_count'] - 1
garciadeblas9f8456e2016-09-05 05:02:59 +0200317 ip_str = str(netaddr.IPAddress(ip_int))
318 subnet['allocation_pools'][0]['end'] = ip_str
garciadeblasedca7b32016-09-29 14:01:52 +0000319 #self.logger.debug(">>>>>>>>>>>>>>>>>> Subnet: %s", str(subnet))
tierno7edb6752016-03-21 17:37:52 +0100320 self.neutron.create_subnet({"subnet": subnet} )
tiernoae4a8d12016-07-08 12:30:39 +0200321 return new_net["network"]["id"]
tierno8e995ce2016-09-22 08:13:00 +0000322 except (neExceptions.ConnectionFailed, ksExceptions.ClientException, neExceptions.NeutronException, ConnectionError) as e:
garciadeblasedca7b32016-09-29 14:01:52 +0000323 if new_net:
324 self.neutron.delete_network(new_net['network']['id'])
tiernoae4a8d12016-07-08 12:30:39 +0200325 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100326
327 def get_network_list(self, filter_dict={}):
328 '''Obtain tenant networks of VIM
329 Filter_dict can be:
330 name: network name
331 id: network uuid
332 shared: boolean
333 tenant_id: tenant
334 admin_state_up: boolean
335 status: 'ACTIVE'
336 Returns the network list of dictionaries
337 '''
tiernoae4a8d12016-07-08 12:30:39 +0200338 self.logger.debug("Getting network from VIM filter: '%s'", str(filter_dict))
tierno7edb6752016-03-21 17:37:52 +0100339 try:
340 self._reload_connection()
ahmadsa95baa272016-11-30 09:14:11 +0500341 if osc_api_version == 'v3.3' and "tenant_id" in filter_dict:
342 filter_dict['project_id'] = filter_dict.pop('tenant_id')
tierno7edb6752016-03-21 17:37:52 +0100343 net_dict=self.neutron.list_networks(**filter_dict)
344 net_list=net_dict["networks"]
345 self.__net_os2mano(net_list)
tiernoae4a8d12016-07-08 12:30:39 +0200346 return net_list
tierno8e995ce2016-09-22 08:13:00 +0000347 except (neExceptions.ConnectionFailed, ksExceptions.ClientException, neExceptions.NeutronException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200348 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100349
tiernoae4a8d12016-07-08 12:30:39 +0200350 def get_network(self, net_id):
351 '''Obtain details of network from VIM
352 Returns the network information from a network id'''
353 self.logger.debug(" Getting tenant network %s from VIM", net_id)
tierno7edb6752016-03-21 17:37:52 +0100354 filter_dict={"id": net_id}
tiernoae4a8d12016-07-08 12:30:39 +0200355 net_list = self.get_network_list(filter_dict)
tierno7edb6752016-03-21 17:37:52 +0100356 if len(net_list)==0:
tiernoae4a8d12016-07-08 12:30:39 +0200357 raise vimconn.vimconnNotFoundException("Network '{}' not found".format(net_id))
tierno7edb6752016-03-21 17:37:52 +0100358 elif len(net_list)>1:
tiernoae4a8d12016-07-08 12:30:39 +0200359 raise vimconn.vimconnConflictException("Found more than one network with this criteria")
tierno7edb6752016-03-21 17:37:52 +0100360 net = net_list[0]
361 subnets=[]
362 for subnet_id in net.get("subnets", () ):
363 try:
364 subnet = self.neutron.show_subnet(subnet_id)
365 except Exception as e:
tiernoae4a8d12016-07-08 12:30:39 +0200366 self.logger.error("osconnector.get_network(): Error getting subnet %s %s" % (net_id, str(e)))
367 subnet = {"id": subnet_id, "fault": str(e)}
tierno7edb6752016-03-21 17:37:52 +0100368 subnets.append(subnet)
369 net["subnets"] = subnets
tiernoae4a8d12016-07-08 12:30:39 +0200370 return net
tierno7edb6752016-03-21 17:37:52 +0100371
tiernoae4a8d12016-07-08 12:30:39 +0200372 def delete_network(self, net_id):
373 '''Deletes a tenant network from VIM. Returns the old network identifier'''
374 self.logger.debug("Deleting network '%s' from VIM", net_id)
tierno7edb6752016-03-21 17:37:52 +0100375 try:
376 self._reload_connection()
377 #delete VM ports attached to this networks before the network
378 ports = self.neutron.list_ports(network_id=net_id)
379 for p in ports['ports']:
380 try:
381 self.neutron.delete_port(p["id"])
382 except Exception as e:
tiernoae4a8d12016-07-08 12:30:39 +0200383 self.logger.error("Error deleting port %s: %s", p["id"], str(e))
tierno7edb6752016-03-21 17:37:52 +0100384 self.neutron.delete_network(net_id)
tiernoae4a8d12016-07-08 12:30:39 +0200385 return net_id
386 except (neExceptions.ConnectionFailed, neExceptions.NetworkNotFoundClient, neExceptions.NeutronException,
tierno8e995ce2016-09-22 08:13:00 +0000387 ksExceptions.ClientException, neExceptions.NeutronException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200388 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100389
tiernoae4a8d12016-07-08 12:30:39 +0200390 def refresh_nets_status(self, net_list):
391 '''Get the status of the networks
392 Params: the list of network identifiers
393 Returns a dictionary with:
394 net_id: #VIM id of this network
395 status: #Mandatory. Text with one of:
396 # DELETED (not found at vim)
397 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
398 # OTHER (Vim reported other status not understood)
399 # ERROR (VIM indicates an ERROR status)
400 # ACTIVE, INACTIVE, DOWN (admin down),
401 # BUILD (on building process)
402 #
403 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
404 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
405
406 '''
407 net_dict={}
408 for net_id in net_list:
409 net = {}
410 try:
411 net_vim = self.get_network(net_id)
412 if net_vim['status'] in netStatus2manoFormat:
413 net["status"] = netStatus2manoFormat[ net_vim['status'] ]
414 else:
415 net["status"] = "OTHER"
416 net["error_msg"] = "VIM status reported " + net_vim['status']
417
tierno8e995ce2016-09-22 08:13:00 +0000418 if net['status'] == "ACTIVE" and not net_vim['admin_state_up']:
tiernoae4a8d12016-07-08 12:30:39 +0200419 net['status'] = 'DOWN'
tierno8e995ce2016-09-22 08:13:00 +0000420 try:
421 net['vim_info'] = yaml.safe_dump(net_vim, default_flow_style=True, width=256)
422 except yaml.representer.RepresenterError:
423 net['vim_info'] = str(net_vim)
tiernoae4a8d12016-07-08 12:30:39 +0200424 if net_vim.get('fault'): #TODO
425 net['error_msg'] = str(net_vim['fault'])
426 except vimconn.vimconnNotFoundException as e:
427 self.logger.error("Exception getting net status: %s", str(e))
428 net['status'] = "DELETED"
429 net['error_msg'] = str(e)
430 except vimconn.vimconnException as e:
431 self.logger.error("Exception getting net status: %s", str(e))
432 net['status'] = "VIM_ERROR"
433 net['error_msg'] = str(e)
434 net_dict[net_id] = net
435 return net_dict
436
437 def get_flavor(self, flavor_id):
438 '''Obtain flavor details from the VIM. Returns the flavor dict details'''
439 self.logger.debug("Getting flavor '%s'", flavor_id)
tierno7edb6752016-03-21 17:37:52 +0100440 try:
441 self._reload_connection()
442 flavor = self.nova.flavors.find(id=flavor_id)
443 #TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
tiernoae4a8d12016-07-08 12:30:39 +0200444 return flavor.to_dict()
tierno8e995ce2016-09-22 08:13:00 +0000445 except (nvExceptions.NotFound, nvExceptions.ClientException, ksExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200446 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100447
tiernoae4a8d12016-07-08 12:30:39 +0200448 def new_flavor(self, flavor_data, change_name_if_used=True):
tierno7edb6752016-03-21 17:37:52 +0100449 '''Adds a tenant flavor to openstack VIM
tiernoae4a8d12016-07-08 12:30:39 +0200450 if change_name_if_used is True, it will change name in case of conflict, because it is not supported name repetition
tierno7edb6752016-03-21 17:37:52 +0100451 Returns the flavor identifier
452 '''
tiernoae4a8d12016-07-08 12:30:39 +0200453 self.logger.debug("Adding flavor '%s'", str(flavor_data))
tierno7edb6752016-03-21 17:37:52 +0100454 retry=0
tiernoae4a8d12016-07-08 12:30:39 +0200455 max_retries=3
tierno7edb6752016-03-21 17:37:52 +0100456 name_suffix = 0
tiernoae4a8d12016-07-08 12:30:39 +0200457 name=flavor_data['name']
458 while retry<max_retries:
tierno7edb6752016-03-21 17:37:52 +0100459 retry+=1
460 try:
461 self._reload_connection()
462 if change_name_if_used:
463 #get used names
464 fl_names=[]
465 fl=self.nova.flavors.list()
466 for f in fl:
467 fl_names.append(f.name)
468 while name in fl_names:
469 name_suffix += 1
tiernoae4a8d12016-07-08 12:30:39 +0200470 name = flavor_data['name']+"-" + str(name_suffix)
tierno7edb6752016-03-21 17:37:52 +0100471
tiernoae4a8d12016-07-08 12:30:39 +0200472 ram = flavor_data.get('ram',64)
473 vcpus = flavor_data.get('vcpus',1)
tierno7edb6752016-03-21 17:37:52 +0100474 numa_properties=None
475
tiernoae4a8d12016-07-08 12:30:39 +0200476 extended = flavor_data.get("extended")
tierno7edb6752016-03-21 17:37:52 +0100477 if extended:
478 numas=extended.get("numas")
479 if numas:
480 numa_nodes = len(numas)
481 if numa_nodes > 1:
482 return -1, "Can not add flavor with more than one numa"
483 numa_properties = {"hw:numa_nodes":str(numa_nodes)}
484 numa_properties["hw:mem_page_size"] = "large"
485 numa_properties["hw:cpu_policy"] = "dedicated"
486 numa_properties["hw:numa_mempolicy"] = "strict"
487 for numa in numas:
488 #overwrite ram and vcpus
489 ram = numa['memory']*1024
490 if 'paired-threads' in numa:
491 vcpus = numa['paired-threads']*2
492 numa_properties["hw:cpu_threads_policy"] = "prefer"
493 elif 'cores' in numa:
494 vcpus = numa['cores']
495 #numa_properties["hw:cpu_threads_policy"] = "prefer"
496 elif 'threads' in numa:
497 vcpus = numa['threads']
498 numa_properties["hw:cpu_policy"] = "isolated"
499 for interface in numa.get("interfaces",() ):
500 if interface["dedicated"]=="yes":
tierno809a7802016-07-08 13:31:24 +0200501 raise vimconn.vimconnException("Passthrough interfaces are not supported for the openstack connector", http_code=vimconn.HTTP_Service_Unavailable)
tierno7edb6752016-03-21 17:37:52 +0100502 #TODO, add the key 'pci_passthrough:alias"="<label at config>:<number ifaces>"' when a way to connect it is available
503
504 #create flavor
505 new_flavor=self.nova.flavors.create(name,
506 ram,
507 vcpus,
tiernoae4a8d12016-07-08 12:30:39 +0200508 flavor_data.get('disk',1),
509 is_public=flavor_data.get('is_public', True)
tierno7edb6752016-03-21 17:37:52 +0100510 )
511 #add metadata
512 if numa_properties:
513 new_flavor.set_keys(numa_properties)
tiernoae4a8d12016-07-08 12:30:39 +0200514 return new_flavor.id
tierno7edb6752016-03-21 17:37:52 +0100515 except nvExceptions.Conflict as e:
tiernoae4a8d12016-07-08 12:30:39 +0200516 if change_name_if_used and retry < max_retries:
tierno7edb6752016-03-21 17:37:52 +0100517 continue
tiernoae4a8d12016-07-08 12:30:39 +0200518 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100519 #except nvExceptions.BadRequest as e:
520 except (ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200521 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100522
tiernoae4a8d12016-07-08 12:30:39 +0200523 def delete_flavor(self,flavor_id):
524 '''Deletes a tenant flavor from openstack VIM. Returns the old flavor_id
tierno7edb6752016-03-21 17:37:52 +0100525 '''
tiernoae4a8d12016-07-08 12:30:39 +0200526 try:
527 self._reload_connection()
528 self.nova.flavors.delete(flavor_id)
529 return flavor_id
530 #except nvExceptions.BadRequest as e:
tierno8e995ce2016-09-22 08:13:00 +0000531 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200532 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100533
tiernoae4a8d12016-07-08 12:30:39 +0200534 def new_image(self,image_dict):
tierno7edb6752016-03-21 17:37:52 +0100535 '''
tiernoae4a8d12016-07-08 12:30:39 +0200536 Adds a tenant image to VIM. imge_dict is a dictionary with:
537 name: name
538 disk_format: qcow2, vhd, vmdk, raw (by default), ...
539 location: path or URI
540 public: "yes" or "no"
541 metadata: metadata of the image
542 Returns the image_id
tierno7edb6752016-03-21 17:37:52 +0100543 '''
tierno7edb6752016-03-21 17:37:52 +0100544 #using version 1 of glance client
545 glancev1 = gl1Client.Client('1',self.glance_endpoint, token=self.keystone.auth_token, **self.k_creds) #TODO check k_creds vs n_creds
tiernoae4a8d12016-07-08 12:30:39 +0200546 retry=0
547 max_retries=3
548 while retry<max_retries:
tierno7edb6752016-03-21 17:37:52 +0100549 retry+=1
550 try:
551 self._reload_connection()
552 #determine format http://docs.openstack.org/developer/glance/formats.html
553 if "disk_format" in image_dict:
554 disk_format=image_dict["disk_format"]
555 else: #autodiscover base on extention
556 if image_dict['location'][-6:]==".qcow2":
557 disk_format="qcow2"
558 elif image_dict['location'][-4:]==".vhd":
559 disk_format="vhd"
560 elif image_dict['location'][-5:]==".vmdk":
561 disk_format="vmdk"
562 elif image_dict['location'][-4:]==".vdi":
563 disk_format="vdi"
564 elif image_dict['location'][-4:]==".iso":
565 disk_format="iso"
566 elif image_dict['location'][-4:]==".aki":
567 disk_format="aki"
568 elif image_dict['location'][-4:]==".ari":
569 disk_format="ari"
570 elif image_dict['location'][-4:]==".ami":
571 disk_format="ami"
572 else:
573 disk_format="raw"
tiernoae4a8d12016-07-08 12:30:39 +0200574 self.logger.debug("new_image: '%s' loading from '%s'", image_dict['name'], image_dict['location'])
tierno7edb6752016-03-21 17:37:52 +0100575 if image_dict['location'][0:4]=="http":
576 new_image = glancev1.images.create(name=image_dict['name'], is_public=image_dict.get('public',"yes")=="yes",
577 container_format="bare", location=image_dict['location'], disk_format=disk_format)
578 else: #local path
579 with open(image_dict['location']) as fimage:
580 new_image = glancev1.images.create(name=image_dict['name'], is_public=image_dict.get('public',"yes")=="yes",
581 container_format="bare", data=fimage, disk_format=disk_format)
582 #insert metadata. We cannot use 'new_image.properties.setdefault'
583 #because nova and glance are "INDEPENDENT" and we are using nova for reading metadata
584 new_image_nova=self.nova.images.find(id=new_image.id)
585 new_image_nova.metadata.setdefault('location',image_dict['location'])
586 metadata_to_load = image_dict.get('metadata')
587 if metadata_to_load:
588 for k,v in yaml.load(metadata_to_load).iteritems():
589 new_image_nova.metadata.setdefault(k,v)
tiernoae4a8d12016-07-08 12:30:39 +0200590 return new_image.id
591 except (nvExceptions.Conflict, ksExceptions.ClientException, nvExceptions.ClientException) as e:
592 self._format_exception(e)
tierno8e995ce2016-09-22 08:13:00 +0000593 except (HTTPException, gl1Exceptions.HTTPException, gl1Exceptions.CommunicationError, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200594 if retry==max_retries:
595 continue
596 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100597 except IOError as e: #can not open the file
tiernoae4a8d12016-07-08 12:30:39 +0200598 raise vimconn.vimconnConnectionException(type(e).__name__ + ": " + str(e)+ " for " + image_dict['location'],
599 http_code=vimconn.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100600
tiernoae4a8d12016-07-08 12:30:39 +0200601 def delete_image(self, image_id):
602 '''Deletes a tenant image from openstack VIM. Returns the old id
tierno7edb6752016-03-21 17:37:52 +0100603 '''
tiernoae4a8d12016-07-08 12:30:39 +0200604 try:
605 self._reload_connection()
606 self.nova.images.delete(image_id)
607 return image_id
tierno8e995ce2016-09-22 08:13:00 +0000608 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e: #TODO remove
tiernoae4a8d12016-07-08 12:30:39 +0200609 self._format_exception(e)
610
611 def get_image_id_from_path(self, path):
garciadeblasb69fa9f2016-09-28 12:04:10 +0200612 '''Get the image id from image path in the VIM database. Returns the image_id'''
tiernoae4a8d12016-07-08 12:30:39 +0200613 try:
614 self._reload_connection()
615 images = self.nova.images.list()
616 for image in images:
617 if image.metadata.get("location")==path:
618 return image.id
619 raise vimconn.vimconnNotFoundException("image with location '{}' not found".format( path))
tierno8e995ce2016-09-22 08:13:00 +0000620 except (ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200621 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100622
garciadeblasb69fa9f2016-09-28 12:04:10 +0200623 def get_image_list(self, filter_dict={}):
624 '''Obtain tenant images from VIM
625 Filter_dict can be:
626 id: image id
627 name: image name
628 checksum: image checksum
629 Returns the image list of dictionaries:
630 [{<the fields at Filter_dict plus some VIM specific>}, ...]
631 List can be empty
632 '''
633 self.logger.debug("Getting image list from VIM filter: '%s'", str(filter_dict))
634 try:
635 self._reload_connection()
636 filter_dict_os=filter_dict.copy()
637 #First we filter by the available filter fields: name, id. The others are removed.
638 filter_dict_os.pop('checksum',None)
639 image_list=self.nova.images.findall(**filter_dict_os)
640 if len(image_list)==0:
641 return []
642 #Then we filter by the rest of filter fields: checksum
643 filtered_list = []
644 for image in image_list:
garciadeblasbb6a1ed2016-09-30 14:02:09 +0000645 image_dict=self.glance.images.get(image.id)
garciadeblasb69fa9f2016-09-28 12:04:10 +0200646 if image_dict['checksum']==filter_dict.get('checksum'):
647 filtered_list.append(image)
648 return filtered_list
649 except (ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e:
650 self._format_exception(e)
651
tiernoa4e1a6e2016-08-31 14:19:40 +0200652 def new_vminstance(self,name,description,start,image_id,flavor_id,net_list,cloud_config=None):
tierno7edb6752016-03-21 17:37:52 +0100653 '''Adds a VM instance to VIM
654 Params:
655 start: indicates if VM must start or boot in pause mode. Ignored
656 image_id,flavor_id: iamge and flavor uuid
657 net_list: list of interfaces, each one is a dictionary with:
658 name:
659 net_id: network uuid to connect
660 vpci: virtual vcpi to assign, ignored because openstack lack #TODO
661 model: interface model, ignored #TODO
662 mac_address: used for SR-IOV ifaces #TODO for other types
663 use: 'data', 'bridge', 'mgmt'
664 type: 'virtual', 'PF', 'VF', 'VFnotShared'
665 vim_id: filled/added by this function
666 #TODO ip, security groups
tiernoae4a8d12016-07-08 12:30:39 +0200667 Returns the instance identifier
tierno7edb6752016-03-21 17:37:52 +0100668 '''
tiernoae4a8d12016-07-08 12:30:39 +0200669 self.logger.debug("Creating VM image '%s' flavor '%s' nics='%s'",image_id, flavor_id,str(net_list))
tierno7edb6752016-03-21 17:37:52 +0100670 try:
tierno6e116232016-07-18 13:01:40 +0200671 metadata={}
tierno7edb6752016-03-21 17:37:52 +0100672 net_list_vim=[]
673 self._reload_connection()
tiernoae4a8d12016-07-08 12:30:39 +0200674 metadata_vpci={} #For a specific neutron plugin
tierno7edb6752016-03-21 17:37:52 +0100675 for net in net_list:
676 if not net.get("net_id"): #skip non connected iface
677 continue
678 if net["type"]=="virtual":
679 net_list_vim.append({'net-id': net["net_id"]})
680 if "vpci" in net:
681 metadata_vpci[ net["net_id"] ] = [[ net["vpci"], "" ]]
682 elif net["type"]=="PF":
tiernoae4a8d12016-07-08 12:30:39 +0200683 self.logger.warn("new_vminstance: Warning, can not connect a passthrough interface ")
tierno7edb6752016-03-21 17:37:52 +0100684 #TODO insert this when openstack consider passthrough ports as openstack neutron ports
685 else: #VF
686 if "vpci" in net:
687 if "VF" not in metadata_vpci:
688 metadata_vpci["VF"]=[]
689 metadata_vpci["VF"].append([ net["vpci"], "" ])
690 port_dict={
691 "network_id": net["net_id"],
692 "name": net.get("name"),
693 "binding:vnic_type": "direct",
694 "admin_state_up": True
695 }
696 if not port_dict["name"]:
697 port_dict["name"] = name
698 if net.get("mac_address"):
699 port_dict["mac_address"]=net["mac_address"]
700 #TODO: manage having SRIOV without vlan tag
701 #if net["type"] == "VFnotShared"
702 # port_dict["vlan"]=0
703 new_port = self.neutron.create_port({"port": port_dict })
704 net["mac_adress"] = new_port["port"]["mac_address"]
705 net["vim_id"] = new_port["port"]["id"]
706 net["ip"] = new_port["port"].get("fixed_ips",[{}])[0].get("ip_address")
707 net_list_vim.append({"port-id": new_port["port"]["id"]})
708 if metadata_vpci:
709 metadata = {"pci_assignement": json.dumps(metadata_vpci)}
tiernoafbced42016-07-23 01:43:53 +0200710 if len(metadata["pci_assignement"]) >255:
tierno6e116232016-07-18 13:01:40 +0200711 #limit the metadata size
712 #metadata["pci_assignement"] = metadata["pci_assignement"][0:255]
713 self.logger.warn("Metadata deleted since it exceeds the expected length (255) ")
714 metadata = {}
tierno7edb6752016-03-21 17:37:52 +0100715
tiernoae4a8d12016-07-08 12:30:39 +0200716 self.logger.debug("name '%s' image_id '%s'flavor_id '%s' net_list_vim '%s' description '%s' metadata %s",
717 name, image_id, flavor_id, str(net_list_vim), description, str(metadata))
tierno7edb6752016-03-21 17:37:52 +0100718
719 security_groups = self.config.get('security_groups')
720 if type(security_groups) is str:
721 security_groups = ( security_groups, )
tiernoa4e1a6e2016-08-31 14:19:40 +0200722 if isinstance(cloud_config, dict):
723 userdata="#cloud-config\nusers:\n"
724 #default user
725 if "key-pairs" in cloud_config:
726 userdata += " - default:\n ssh-authorized-keys:\n"
727 for key in cloud_config["key-pairs"]:
728 userdata += " - '{key}'\n".format(key=key)
729 for user in cloud_config.get("users",[]):
730 userdata += " - name: {name}\n sudo: ALL=(ALL) NOPASSWD:ALL\n".format(name=user["name"])
731 if "user-info" in user:
732 userdata += " gecos: {}'\n".format(user["user-info"])
733 if user.get("key-pairs"):
734 userdata += " ssh-authorized-keys:\n"
735 for key in user["key-pairs"]:
736 userdata += " - '{key}'\n".format(key=key)
737 self.logger.debug("userdata: %s", userdata)
738 elif isinstance(cloud_config, str):
739 userdata = cloud_config
740 else:
741 userdata=None
742
tierno7edb6752016-03-21 17:37:52 +0100743 server = self.nova.servers.create(name, image_id, flavor_id, nics=net_list_vim, meta=metadata,
744 security_groups = security_groups,
745 availability_zone = self.config.get('availability_zone'),
746 key_name = self.config.get('keypair'),
tiernoa4e1a6e2016-08-31 14:19:40 +0200747 userdata=userdata
tierno7edb6752016-03-21 17:37:52 +0100748 ) #, description=description)
749
750
tiernoae4a8d12016-07-08 12:30:39 +0200751 #print "DONE :-)", server
tierno7edb6752016-03-21 17:37:52 +0100752
753# #TODO server.add_floating_ip("10.95.87.209")
754# #To look for a free floating_ip
755# free_floating_ip = None
756# for floating_ip in self.neutron.list_floatingips().get("floatingips", () ):
757# if not floating_ip["port_id"]:
758# free_floating_ip = floating_ip["floating_ip_address"]
759# break
760# if free_floating_ip:
761# server.add_floating_ip(free_floating_ip)
762
763
tiernoae4a8d12016-07-08 12:30:39 +0200764 return server.id
tierno7edb6752016-03-21 17:37:52 +0100765# except nvExceptions.NotFound as e:
766# error_value=-vimconn.HTTP_Not_Found
767# error_text= "vm instance %s not found" % vm_id
tierno8e995ce2016-09-22 08:13:00 +0000768 except (ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError
769 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200770 self._format_exception(e)
771 except TypeError as e:
772 raise vimconn.vimconnException(type(e).__name__ + ": "+ str(e), http_code=vimconn.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100773
tiernoae4a8d12016-07-08 12:30:39 +0200774 def get_vminstance(self,vm_id):
tierno7edb6752016-03-21 17:37:52 +0100775 '''Returns the VM instance information from VIM'''
tiernoae4a8d12016-07-08 12:30:39 +0200776 #self.logger.debug("Getting VM from VIM")
tierno7edb6752016-03-21 17:37:52 +0100777 try:
778 self._reload_connection()
779 server = self.nova.servers.find(id=vm_id)
780 #TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
tiernoae4a8d12016-07-08 12:30:39 +0200781 return server.to_dict()
tierno8e995ce2016-09-22 08:13:00 +0000782 except (ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.NotFound, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200783 self._format_exception(e)
784
785 def get_vminstance_console(self,vm_id, console_type="vnc"):
tierno7edb6752016-03-21 17:37:52 +0100786 '''
787 Get a console for the virtual machine
788 Params:
789 vm_id: uuid of the VM
790 console_type, can be:
791 "novnc" (by default), "xvpvnc" for VNC types,
792 "rdp-html5" for RDP types, "spice-html5" for SPICE types
tiernoae4a8d12016-07-08 12:30:39 +0200793 Returns dict with the console parameters:
794 protocol: ssh, ftp, http, https, ...
795 server: usually ip address
796 port: the http, ssh, ... port
797 suffix: extra text, e.g. the http path and query string
tierno7edb6752016-03-21 17:37:52 +0100798 '''
tiernoae4a8d12016-07-08 12:30:39 +0200799 self.logger.debug("Getting VM CONSOLE from VIM")
tierno7edb6752016-03-21 17:37:52 +0100800 try:
801 self._reload_connection()
802 server = self.nova.servers.find(id=vm_id)
803 if console_type == None or console_type == "novnc":
804 console_dict = server.get_vnc_console("novnc")
805 elif console_type == "xvpvnc":
806 console_dict = server.get_vnc_console(console_type)
807 elif console_type == "rdp-html5":
808 console_dict = server.get_rdp_console(console_type)
809 elif console_type == "spice-html5":
810 console_dict = server.get_spice_console(console_type)
811 else:
tiernoae4a8d12016-07-08 12:30:39 +0200812 raise vimconn.vimconnException("console type '{}' not allowed".format(console_type), http_code=vimconn.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100813
814 console_dict1 = console_dict.get("console")
815 if console_dict1:
816 console_url = console_dict1.get("url")
817 if console_url:
818 #parse console_url
819 protocol_index = console_url.find("//")
820 suffix_index = console_url[protocol_index+2:].find("/") + protocol_index+2
821 port_index = console_url[protocol_index+2:suffix_index].find(":") + protocol_index+2
822 if protocol_index < 0 or port_index<0 or suffix_index<0:
823 return -vimconn.HTTP_Internal_Server_Error, "Unexpected response from VIM"
824 console_dict={"protocol": console_url[0:protocol_index],
825 "server": console_url[protocol_index+2:port_index],
826 "port": console_url[port_index:suffix_index],
827 "suffix": console_url[suffix_index+1:]
828 }
829 protocol_index += 2
tiernoae4a8d12016-07-08 12:30:39 +0200830 return console_dict
831 raise vimconn.vimconnUnexpectedResponse("Unexpected response from VIM")
tierno7edb6752016-03-21 17:37:52 +0100832
tierno8e995ce2016-09-22 08:13:00 +0000833 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.BadRequest, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200834 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100835
tiernoae4a8d12016-07-08 12:30:39 +0200836 def delete_vminstance(self, vm_id):
837 '''Removes a VM instance from VIM. Returns the old identifier
tierno7edb6752016-03-21 17:37:52 +0100838 '''
tiernoae4a8d12016-07-08 12:30:39 +0200839 #print "osconnector: Getting VM from VIM"
tierno7edb6752016-03-21 17:37:52 +0100840 try:
841 self._reload_connection()
842 #delete VM ports attached to this networks before the virtual machine
843 ports = self.neutron.list_ports(device_id=vm_id)
844 for p in ports['ports']:
845 try:
846 self.neutron.delete_port(p["id"])
847 except Exception as e:
tiernoae4a8d12016-07-08 12:30:39 +0200848 self.logger.error("Error deleting port: " + type(e).__name__ + ": "+ str(e))
tierno7edb6752016-03-21 17:37:52 +0100849 self.nova.servers.delete(vm_id)
tiernoae4a8d12016-07-08 12:30:39 +0200850 return vm_id
tierno8e995ce2016-09-22 08:13:00 +0000851 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200852 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100853 #TODO insert exception vimconn.HTTP_Unauthorized
854 #if reaching here is because an exception
tierno7edb6752016-03-21 17:37:52 +0100855
tiernoae4a8d12016-07-08 12:30:39 +0200856 def refresh_vms_status(self, vm_list):
857 '''Get the status of the virtual machines and their interfaces/ports
858 Params: the list of VM identifiers
859 Returns a dictionary with:
860 vm_id: #VIM id of this Virtual Machine
861 status: #Mandatory. Text with one of:
862 # DELETED (not found at vim)
863 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
864 # OTHER (Vim reported other status not understood)
865 # ERROR (VIM indicates an ERROR status)
866 # ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running),
867 # CREATING (on building process), ERROR
868 # ACTIVE:NoMgmtIP (Active but any of its interface has an IP address
869 #
870 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
871 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
872 interfaces:
873 - vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
874 mac_address: #Text format XX:XX:XX:XX:XX:XX
875 vim_net_id: #network id where this interface is connected
876 vim_interface_id: #interface/port VIM id
877 ip_address: #null, or text with IPv4, IPv6 address
tierno7edb6752016-03-21 17:37:52 +0100878 '''
tiernoae4a8d12016-07-08 12:30:39 +0200879 vm_dict={}
880 self.logger.debug("refresh_vms status: Getting tenant VM instance information from VIM")
881 for vm_id in vm_list:
882 vm={}
883 try:
884 vm_vim = self.get_vminstance(vm_id)
885 if vm_vim['status'] in vmStatus2manoFormat:
886 vm['status'] = vmStatus2manoFormat[ vm_vim['status'] ]
tierno7edb6752016-03-21 17:37:52 +0100887 else:
tiernoae4a8d12016-07-08 12:30:39 +0200888 vm['status'] = "OTHER"
889 vm['error_msg'] = "VIM status reported " + vm_vim['status']
tierno8e995ce2016-09-22 08:13:00 +0000890 try:
891 vm['vim_info'] = yaml.safe_dump(vm_vim, default_flow_style=True, width=256)
892 except yaml.representer.RepresenterError:
893 vm['vim_info'] = str(vm_vim)
tiernoae4a8d12016-07-08 12:30:39 +0200894 vm["interfaces"] = []
895 if vm_vim.get('fault'):
896 vm['error_msg'] = str(vm_vim['fault'])
897 #get interfaces
tierno7edb6752016-03-21 17:37:52 +0100898 try:
tiernoae4a8d12016-07-08 12:30:39 +0200899 self._reload_connection()
900 port_dict=self.neutron.list_ports(device_id=vm_id)
901 for port in port_dict["ports"]:
902 interface={}
tierno8e995ce2016-09-22 08:13:00 +0000903 try:
904 interface['vim_info'] = yaml.safe_dump(port, default_flow_style=True, width=256)
905 except yaml.representer.RepresenterError:
906 interface['vim_info'] = str(port)
tiernoae4a8d12016-07-08 12:30:39 +0200907 interface["mac_address"] = port.get("mac_address")
908 interface["vim_net_id"] = port["network_id"]
909 interface["vim_interface_id"] = port["id"]
910 ips=[]
911 #look for floating ip address
912 floating_ip_dict = self.neutron.list_floatingips(port_id=port["id"])
913 if floating_ip_dict.get("floatingips"):
914 ips.append(floating_ip_dict["floatingips"][0].get("floating_ip_address") )
tierno7edb6752016-03-21 17:37:52 +0100915
tiernoae4a8d12016-07-08 12:30:39 +0200916 for subnet in port["fixed_ips"]:
917 ips.append(subnet["ip_address"])
918 interface["ip_address"] = ";".join(ips)
919 vm["interfaces"].append(interface)
920 except Exception as e:
921 self.logger.error("Error getting vm interface information " + type(e).__name__ + ": "+ str(e))
922 except vimconn.vimconnNotFoundException as e:
923 self.logger.error("Exception getting vm status: %s", str(e))
924 vm['status'] = "DELETED"
925 vm['error_msg'] = str(e)
926 except vimconn.vimconnException as e:
927 self.logger.error("Exception getting vm status: %s", str(e))
928 vm['status'] = "VIM_ERROR"
929 vm['error_msg'] = str(e)
930 vm_dict[vm_id] = vm
931 return vm_dict
tierno7edb6752016-03-21 17:37:52 +0100932
tiernoae4a8d12016-07-08 12:30:39 +0200933 def action_vminstance(self, vm_id, action_dict):
tierno7edb6752016-03-21 17:37:52 +0100934 '''Send and action over a VM instance from VIM
tiernoae4a8d12016-07-08 12:30:39 +0200935 Returns the vm_id if the action was successfully sent to the VIM'''
936 self.logger.debug("Action over VM '%s': %s", vm_id, str(action_dict))
tierno7edb6752016-03-21 17:37:52 +0100937 try:
938 self._reload_connection()
939 server = self.nova.servers.find(id=vm_id)
940 if "start" in action_dict:
941 if action_dict["start"]=="rebuild":
942 server.rebuild()
943 else:
944 if server.status=="PAUSED":
945 server.unpause()
946 elif server.status=="SUSPENDED":
947 server.resume()
948 elif server.status=="SHUTOFF":
949 server.start()
950 elif "pause" in action_dict:
951 server.pause()
952 elif "resume" in action_dict:
953 server.resume()
954 elif "shutoff" in action_dict or "shutdown" in action_dict:
955 server.stop()
956 elif "forceOff" in action_dict:
957 server.stop() #TODO
958 elif "terminate" in action_dict:
959 server.delete()
960 elif "createImage" in action_dict:
961 server.create_image()
962 #"path":path_schema,
963 #"description":description_schema,
964 #"name":name_schema,
965 #"metadata":metadata_schema,
966 #"imageRef": id_schema,
967 #"disk": {"oneOf":[{"type": "null"}, {"type":"string"}] },
968 elif "rebuild" in action_dict:
969 server.rebuild(server.image['id'])
970 elif "reboot" in action_dict:
971 server.reboot() #reboot_type='SOFT'
972 elif "console" in action_dict:
973 console_type = action_dict["console"]
974 if console_type == None or console_type == "novnc":
975 console_dict = server.get_vnc_console("novnc")
976 elif console_type == "xvpvnc":
977 console_dict = server.get_vnc_console(console_type)
978 elif console_type == "rdp-html5":
979 console_dict = server.get_rdp_console(console_type)
980 elif console_type == "spice-html5":
981 console_dict = server.get_spice_console(console_type)
982 else:
tiernoae4a8d12016-07-08 12:30:39 +0200983 raise vimconn.vimconnException("console type '{}' not allowed".format(console_type),
984 http_code=vimconn.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100985 try:
986 console_url = console_dict["console"]["url"]
987 #parse console_url
988 protocol_index = console_url.find("//")
989 suffix_index = console_url[protocol_index+2:].find("/") + protocol_index+2
990 port_index = console_url[protocol_index+2:suffix_index].find(":") + protocol_index+2
991 if protocol_index < 0 or port_index<0 or suffix_index<0:
tiernoae4a8d12016-07-08 12:30:39 +0200992 raise vimconn.vimconnException("Unexpected response from VIM " + str(console_dict))
tierno7edb6752016-03-21 17:37:52 +0100993 console_dict2={"protocol": console_url[0:protocol_index],
994 "server": console_url[protocol_index+2 : port_index],
995 "port": int(console_url[port_index+1 : suffix_index]),
996 "suffix": console_url[suffix_index+1:]
997 }
tiernoae4a8d12016-07-08 12:30:39 +0200998 return console_dict2
999 except Exception as e:
1000 raise vimconn.vimconnException("Unexpected response from VIM " + str(console_dict))
tierno7edb6752016-03-21 17:37:52 +01001001
tiernoae4a8d12016-07-08 12:30:39 +02001002 return vm_id
tierno8e995ce2016-09-22 08:13:00 +00001003 except (ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.NotFound, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001004 self._format_exception(e)
1005 #TODO insert exception vimconn.HTTP_Unauthorized
1006
1007#NOT USED FUNCTIONS
1008
1009 def new_external_port(self, port_data):
1010 #TODO openstack if needed
1011 '''Adds a external port to VIM'''
1012 '''Returns the port identifier'''
1013 return -vimconn.HTTP_Internal_Server_Error, "osconnector.new_external_port() not implemented"
1014
1015 def connect_port_network(self, port_id, network_id, admin=False):
1016 #TODO openstack if needed
1017 '''Connects a external port to a network'''
1018 '''Returns status code of the VIM response'''
1019 return -vimconn.HTTP_Internal_Server_Error, "osconnector.connect_port_network() not implemented"
1020
1021 def new_user(self, user_name, user_passwd, tenant_id=None):
1022 '''Adds a new user to openstack VIM'''
1023 '''Returns the user identifier'''
1024 self.logger.debug("osconnector: Adding a new user to VIM")
1025 try:
1026 self._reload_connection()
1027 user=self.keystone.users.create(user_name, user_passwd, tenant_id=tenant_id)
1028 #self.keystone.tenants.add_user(self.k_creds["username"], #role)
1029 return user.id
1030 except ksExceptions.ConnectionError as e:
1031 error_value=-vimconn.HTTP_Bad_Request
1032 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1033 except ksExceptions.ClientException as e: #TODO remove
tierno7edb6752016-03-21 17:37:52 +01001034 error_value=-vimconn.HTTP_Bad_Request
1035 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1036 #TODO insert exception vimconn.HTTP_Unauthorized
1037 #if reaching here is because an exception
1038 if self.debug:
tiernoae4a8d12016-07-08 12:30:39 +02001039 self.logger.debug("new_user " + error_text)
tierno7edb6752016-03-21 17:37:52 +01001040 return error_value, error_text
tiernoae4a8d12016-07-08 12:30:39 +02001041
1042 def delete_user(self, user_id):
1043 '''Delete a user from openstack VIM'''
1044 '''Returns the user identifier'''
1045 if self.debug:
1046 print "osconnector: Deleting a user from VIM"
1047 try:
1048 self._reload_connection()
1049 self.keystone.users.delete(user_id)
1050 return 1, user_id
1051 except ksExceptions.ConnectionError as e:
1052 error_value=-vimconn.HTTP_Bad_Request
1053 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1054 except ksExceptions.NotFound as e:
1055 error_value=-vimconn.HTTP_Not_Found
1056 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1057 except ksExceptions.ClientException as e: #TODO remove
1058 error_value=-vimconn.HTTP_Bad_Request
1059 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1060 #TODO insert exception vimconn.HTTP_Unauthorized
1061 #if reaching here is because an exception
1062 if self.debug:
1063 print "delete_tenant " + error_text
1064 return error_value, error_text
1065
tierno7edb6752016-03-21 17:37:52 +01001066 def get_hosts_info(self):
1067 '''Get the information of deployed hosts
1068 Returns the hosts content'''
1069 if self.debug:
1070 print "osconnector: Getting Host info from VIM"
1071 try:
1072 h_list=[]
1073 self._reload_connection()
1074 hypervisors = self.nova.hypervisors.list()
1075 for hype in hypervisors:
1076 h_list.append( hype.to_dict() )
1077 return 1, {"hosts":h_list}
1078 except nvExceptions.NotFound as e:
1079 error_value=-vimconn.HTTP_Not_Found
1080 error_text= (str(e) if len(e.args)==0 else str(e.args[0]))
1081 except (ksExceptions.ClientException, nvExceptions.ClientException) as e:
1082 error_value=-vimconn.HTTP_Bad_Request
1083 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1084 #TODO insert exception vimconn.HTTP_Unauthorized
1085 #if reaching here is because an exception
1086 if self.debug:
1087 print "get_hosts_info " + error_text
1088 return error_value, error_text
1089
1090 def get_hosts(self, vim_tenant):
1091 '''Get the hosts and deployed instances
1092 Returns the hosts content'''
1093 r, hype_dict = self.get_hosts_info()
1094 if r<0:
1095 return r, hype_dict
1096 hypervisors = hype_dict["hosts"]
1097 try:
1098 servers = self.nova.servers.list()
1099 for hype in hypervisors:
1100 for server in servers:
1101 if server.to_dict()['OS-EXT-SRV-ATTR:hypervisor_hostname']==hype['hypervisor_hostname']:
1102 if 'vm' in hype:
1103 hype['vm'].append(server.id)
1104 else:
1105 hype['vm'] = [server.id]
1106 return 1, hype_dict
1107 except nvExceptions.NotFound as e:
1108 error_value=-vimconn.HTTP_Not_Found
1109 error_text= (str(e) if len(e.args)==0 else str(e.args[0]))
1110 except (ksExceptions.ClientException, nvExceptions.ClientException) as e:
1111 error_value=-vimconn.HTTP_Bad_Request
1112 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1113 #TODO insert exception vimconn.HTTP_Unauthorized
1114 #if reaching here is because an exception
1115 if self.debug:
1116 print "get_hosts " + error_text
1117 return error_value, error_text
1118
tierno7edb6752016-03-21 17:37:52 +01001119