blob: 314027d31a5609161e9db8d12d02ccfec8f0a243 [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'''
27__author__="Alfonso Tierno, Gerardo Garcia"
28__date__ ="$22-jun-2014 11:19:29$"
29
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
36from novaclient import client as nClient, exceptions as nvExceptions
37import keystoneclient.v2_0.client as ksClient
38import keystoneclient.exceptions as ksExceptions
39import glanceclient.v2.client as glClient
40import glanceclient.client as gl1Client
41import glanceclient.exc as gl1Exceptions
42from httplib import HTTPException
43from neutronclient.neutron import client as neClient
44from neutronclient.common import exceptions as neExceptions
45from requests.exceptions import ConnectionError
46
47'''contain the openstack virtual machine status to openmano status'''
48vmStatus2manoFormat={'ACTIVE':'ACTIVE',
49 'PAUSED':'PAUSED',
50 'SUSPENDED': 'SUSPENDED',
51 'SHUTOFF':'INACTIVE',
52 'BUILD':'BUILD',
53 'ERROR':'ERROR','DELETED':'DELETED'
54 }
55netStatus2manoFormat={'ACTIVE':'ACTIVE','PAUSED':'PAUSED','INACTIVE':'INACTIVE','BUILD':'BUILD','ERROR':'ERROR','DELETED':'DELETED'
56 }
57
58class vimconnector(vimconn.vimconnector):
tiernoae4a8d12016-07-08 12:30:39 +020059 def __init__(self, uuid, name, tenant_id, tenant_name, url, url_admin=None, user=None, passwd=None, log_level="DEBUG", config={}):
tierno7edb6752016-03-21 17:37:52 +010060 '''using common constructor parameters. In this case
61 'url' is the keystone authorization url,
62 'url_admin' is not use
63 '''
tiernoae4a8d12016-07-08 12:30:39 +020064 vimconn.vimconnector.__init__(self, uuid, name, tenant_id, tenant_name, url, url_admin, user, passwd, log_level, config)
tierno7edb6752016-03-21 17:37:52 +010065
66 self.k_creds={}
67 self.n_creds={}
68 if not url:
69 raise TypeError, 'url param can not be NoneType'
70 self.k_creds['auth_url'] = url
71 self.n_creds['auth_url'] = url
tierno392f2852016-05-13 12:28:55 +020072 if tenant_name:
73 self.k_creds['tenant_name'] = tenant_name
74 self.n_creds['project_id'] = tenant_name
75 if tenant_id:
76 self.k_creds['tenant_id'] = tenant_id
77 self.n_creds['tenant_id'] = tenant_id
tierno7edb6752016-03-21 17:37:52 +010078 if user:
79 self.k_creds['username'] = user
80 self.n_creds['username'] = user
81 if passwd:
82 self.k_creds['password'] = passwd
83 self.n_creds['api_key'] = passwd
84 self.reload_client = True
tiernoae4a8d12016-07-08 12:30:39 +020085 self.logger = logging.getLogger('mano.vim.openstack')
tierno7edb6752016-03-21 17:37:52 +010086
87 def __setitem__(self,index, value):
88 '''Set individuals parameters
89 Throw TypeError, KeyError
90 '''
tierno392f2852016-05-13 12:28:55 +020091 if index=='tenant_id':
tierno7edb6752016-03-21 17:37:52 +010092 self.reload_client=True
tierno392f2852016-05-13 12:28:55 +020093 self.tenant_id = value
94 if value:
95 self.k_creds['tenant_id'] = value
96 self.n_creds['tenant_id'] = value
97 else:
98 del self.k_creds['tenant_name']
99 del self.n_creds['project_id']
100 elif index=='tenant_name':
101 self.reload_client=True
102 self.tenant_name = value
tierno7edb6752016-03-21 17:37:52 +0100103 if value:
104 self.k_creds['tenant_name'] = value
105 self.n_creds['project_id'] = value
106 else:
107 del self.k_creds['tenant_name']
108 del self.n_creds['project_id']
109 elif index=='user':
110 self.reload_client=True
111 self.user = value
112 if value:
113 self.k_creds['username'] = value
114 self.n_creds['username'] = value
115 else:
116 del self.k_creds['username']
117 del self.n_creds['username']
118 elif index=='passwd':
119 self.reload_client=True
120 self.passwd = value
121 if value:
122 self.k_creds['password'] = value
123 self.n_creds['api_key'] = value
124 else:
125 del self.k_creds['password']
126 del self.n_creds['api_key']
127 elif index=='url':
128 self.reload_client=True
129 self.url = value
130 if value:
131 self.k_creds['auth_url'] = value
132 self.n_creds['auth_url'] = value
133 else:
134 raise TypeError, 'url param can not be NoneType'
135 else:
136 vimconn.vimconnector.__setitem__(self,index, value)
137
138 def _reload_connection(self):
139 '''Called before any operation, it check if credentials has changed
140 Throw keystoneclient.apiclient.exceptions.AuthorizationFailure
141 '''
142 #TODO control the timing and possible token timeout, but it seams that python client does this task for us :-)
143 if self.reload_client:
144 #test valid params
145 if len(self.n_creds) <4:
146 raise ksExceptions.ClientException("Not enough parameters to connect to openstack")
147 self.nova = nClient.Client(2, **self.n_creds)
148 self.keystone = ksClient.Client(**self.k_creds)
149 self.glance_endpoint = self.keystone.service_catalog.url_for(service_type='image', endpoint_type='publicURL')
150 self.glance = glClient.Client(self.glance_endpoint, token=self.keystone.auth_token, **self.k_creds) #TODO check k_creds vs n_creds
151 self.ne_endpoint=self.keystone.service_catalog.url_for(service_type='network', endpoint_type='publicURL')
152 self.neutron = neClient.Client('2.0', endpoint_url=self.ne_endpoint, token=self.keystone.auth_token, **self.k_creds)
153 self.reload_client = False
tierno7edb6752016-03-21 17:37:52 +0100154
tierno7edb6752016-03-21 17:37:52 +0100155 def __net_os2mano(self, net_list_dict):
156 '''Transform the net openstack format to mano format
157 net_list_dict can be a list of dict or a single dict'''
158 if type(net_list_dict) is dict:
159 net_list_=(net_list_dict,)
160 elif type(net_list_dict) is list:
161 net_list_=net_list_dict
162 else:
163 raise TypeError("param net_list_dict must be a list or a dictionary")
164 for net in net_list_:
165 if net.get('provider:network_type') == "vlan":
166 net['type']='data'
167 else:
168 net['type']='bridge'
tiernoae4a8d12016-07-08 12:30:39 +0200169
170
171
172 def _format_exception(self, exception):
173 '''Transform a keystone, nova, neutron exception into a vimconn exception'''
174 if isinstance(exception, (HTTPException, gl1Exceptions.HTTPException, gl1Exceptions.CommunicationError,
175 ConnectionError, ksExceptions.ConnectionError, neExceptions.ConnectionFailed,
176 neClient.exceptions.ConnectionFailed)):
177 raise vimconn.vimconnConnectionException(type(exception).__name__ + ": " + str(exception))
178 elif isinstance(exception, (nvExceptions.ClientException, ksExceptions.ClientException,
179 neExceptions.NeutronException, nvExceptions.BadRequest)):
180 raise vimconn.vimconnUnexpectedResponse(type(exception).__name__ + ": " + str(exception))
181 elif isinstance(exception, (neExceptions.NetworkNotFoundClient, nvExceptions.NotFound)):
182 raise vimconn.vimconnNotFoundException(type(exception).__name__ + ": " + str(exception))
183 elif isinstance(exception, nvExceptions.Conflict):
184 raise vimconn.vimconnConflictException(type(exception).__name__ + ": " + str(exception))
185 else: # ()
186 raise vimconn.vimconnConnectionException(type(exception).__name__ + ": " + str(exception))
187
188 def get_tenant_list(self, filter_dict={}):
189 '''Obtain tenants of VIM
190 filter_dict can contain the following keys:
191 name: filter by tenant name
192 id: filter by tenant uuid/id
193 <other VIM specific>
194 Returns the tenant list of dictionaries: [{'name':'<name>, 'id':'<id>, ...}, ...]
195 '''
196 self.logger.debug("Getting tenant from VIM filter: '%s'", str(filter_dict))
197 try:
198 self._reload_connection()
199 tenant_class_list=self.keystone.tenants.findall(**filter_dict)
200 tenant_list=[]
201 for tenant in tenant_class_list:
202 tenant_list.append(tenant.to_dict())
203 return tenant_list
204 except (ksExceptions.ConnectionError, ksExceptions.ClientException) as e:
205 self._format_exception(e)
206
207 def new_tenant(self, tenant_name, tenant_description):
208 '''Adds a new tenant to openstack VIM. Returns the tenant identifier'''
209 self.logger.debug("Adding a new tenant name: %s", tenant_name)
210 try:
211 self._reload_connection()
212 tenant=self.keystone.tenants.create(tenant_name, tenant_description)
213 return tenant.id
214 except (ksExceptions.ConnectionError, ksExceptions.ClientException) as e:
215 self._format_exception(e)
216
217 def delete_tenant(self, tenant_id):
218 '''Delete a tenant from openstack VIM. Returns the old tenant identifier'''
219 self.logger.debug("Deleting tenant %s from VIM", tenant_id)
220 try:
221 self._reload_connection()
222 self.keystone.tenants.delete(tenant_id)
223 return tenant_id
224 except (ksExceptions.ConnectionError, ksExceptions.ClientException) as e:
225 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100226
garciadeblas9f8456e2016-09-05 05:02:59 +0200227 def new_network(self,net_name, net_type, ip_profile=None, shared=False, vlan=None):
tiernoae4a8d12016-07-08 12:30:39 +0200228 '''Adds a tenant network to VIM. Returns the network identifier'''
229 self.logger.debug("Adding a new network to VIM name '%s', type '%s'", net_name, net_type)
tierno7edb6752016-03-21 17:37:52 +0100230 try:
231 self._reload_connection()
232 network_dict = {'name': net_name, 'admin_state_up': True}
233 if net_type=="data" or net_type=="ptp":
234 if self.config.get('dataplane_physical_net') == None:
tiernoae4a8d12016-07-08 12:30:39 +0200235 raise vimconn.vimconnConflictException("You must provide a 'dataplane_physical_net' at config value before creating sriov network")
tierno7edb6752016-03-21 17:37:52 +0100236 network_dict["provider:physical_network"] = self.config['dataplane_physical_net'] #"physnet_sriov" #TODO physical
237 network_dict["provider:network_type"] = "vlan"
238 if vlan!=None:
239 network_dict["provider:network_type"] = vlan
tiernoae4a8d12016-07-08 12:30:39 +0200240 network_dict["shared"]=shared
tierno7edb6752016-03-21 17:37:52 +0100241 new_net=self.neutron.create_network({'network':network_dict})
242 #print new_net
garciadeblas9f8456e2016-09-05 05:02:59 +0200243 #create subnetwork, even if there is no profile
244 if not ip_profile:
245 ip_profile = {}
246 if 'subnet_address' not in ip_profile:
247 #Fake subnet is required
248 ip_profile['subnet_address'] = "192.168.111.0/24"
249 if 'ip_version' not in ip_profile:
250 ip_profile['ip_version'] = "IPv4"
tierno7edb6752016-03-21 17:37:52 +0100251 subnet={"name":net_name+"-subnet",
252 "network_id": new_net["network"]["id"],
garciadeblas9f8456e2016-09-05 05:02:59 +0200253 "ip_version": 4 if ip_profile['ip_version']=="IPv4" else 6,
254 "cidr": ip_profile['subnet_address']
tierno7edb6752016-03-21 17:37:52 +0100255 }
garciadeblas9f8456e2016-09-05 05:02:59 +0200256 if 'gateway_address' in ip_profile:
257 subnet['gateway_ip'] = ip_profile['gateway_address']
258 if 'dns_address' in ip_profile:
259 #TODO: manage dns_address as a list of addresses separated by commas
260 subnet['dns_nameservers'] = []
261 subnet['dns_nameservers'].append(ip_profile['dns_address'])
262 if 'dhcp_enabled' in ip_profile:
263 subnet['enable_dhcp'] = False if ip_profile['dhcp_enabled']=="false" else True
264 if 'dhcp_start_address' in ip_profile:
265 subnet['allocation_pools']=[]
266 subnet['allocation_pools'].append(dict())
267 subnet['allocation_pools'][0]['start'] = ip_profile['dhcp_start_address']
268 if 'dhcp_count' in ip_profile:
269 #parts = ip_profile['dhcp_start_address'].split('.')
270 #ip_int = (int(parts[0]) << 24) + (int(parts[1]) << 16) + (int(parts[2]) << 8) + int(parts[3])
271 ip_int = int(netaddr.IPAddress(ip_profile['dhcp_start_address']))
272 ip_int += ip_profile['dhcp_count']
273 ip_str = str(netaddr.IPAddress(ip_int))
274 subnet['allocation_pools'][0]['end'] = ip_str
tierno7edb6752016-03-21 17:37:52 +0100275 self.neutron.create_subnet({"subnet": subnet} )
tiernoae4a8d12016-07-08 12:30:39 +0200276 return new_net["network"]["id"]
277 except (neExceptions.ConnectionFailed, ksExceptions.ClientException, neExceptions.NeutronException) as e:
278 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100279
280 def get_network_list(self, filter_dict={}):
281 '''Obtain tenant networks of VIM
282 Filter_dict can be:
283 name: network name
284 id: network uuid
285 shared: boolean
286 tenant_id: tenant
287 admin_state_up: boolean
288 status: 'ACTIVE'
289 Returns the network list of dictionaries
290 '''
tiernoae4a8d12016-07-08 12:30:39 +0200291 self.logger.debug("Getting network from VIM filter: '%s'", str(filter_dict))
tierno7edb6752016-03-21 17:37:52 +0100292 try:
293 self._reload_connection()
294 net_dict=self.neutron.list_networks(**filter_dict)
295 net_list=net_dict["networks"]
296 self.__net_os2mano(net_list)
tiernoae4a8d12016-07-08 12:30:39 +0200297 return net_list
298 except (neExceptions.ConnectionFailed, neClient.exceptions.ConnectionFailed, ksExceptions.ClientException, neExceptions.NeutronException) as e:
299 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100300
tiernoae4a8d12016-07-08 12:30:39 +0200301 def get_network(self, net_id):
302 '''Obtain details of network from VIM
303 Returns the network information from a network id'''
304 self.logger.debug(" Getting tenant network %s from VIM", net_id)
tierno7edb6752016-03-21 17:37:52 +0100305 filter_dict={"id": net_id}
tiernoae4a8d12016-07-08 12:30:39 +0200306 net_list = self.get_network_list(filter_dict)
tierno7edb6752016-03-21 17:37:52 +0100307 if len(net_list)==0:
tiernoae4a8d12016-07-08 12:30:39 +0200308 raise vimconn.vimconnNotFoundException("Network '{}' not found".format(net_id))
tierno7edb6752016-03-21 17:37:52 +0100309 elif len(net_list)>1:
tiernoae4a8d12016-07-08 12:30:39 +0200310 raise vimconn.vimconnConflictException("Found more than one network with this criteria")
tierno7edb6752016-03-21 17:37:52 +0100311 net = net_list[0]
312 subnets=[]
313 for subnet_id in net.get("subnets", () ):
314 try:
315 subnet = self.neutron.show_subnet(subnet_id)
316 except Exception as e:
tiernoae4a8d12016-07-08 12:30:39 +0200317 self.logger.error("osconnector.get_network(): Error getting subnet %s %s" % (net_id, str(e)))
318 subnet = {"id": subnet_id, "fault": str(e)}
tierno7edb6752016-03-21 17:37:52 +0100319 subnets.append(subnet)
320 net["subnets"] = subnets
tiernoae4a8d12016-07-08 12:30:39 +0200321 return net
tierno7edb6752016-03-21 17:37:52 +0100322
tiernoae4a8d12016-07-08 12:30:39 +0200323 def delete_network(self, net_id):
324 '''Deletes a tenant network from VIM. Returns the old network identifier'''
325 self.logger.debug("Deleting network '%s' from VIM", net_id)
tierno7edb6752016-03-21 17:37:52 +0100326 try:
327 self._reload_connection()
328 #delete VM ports attached to this networks before the network
329 ports = self.neutron.list_ports(network_id=net_id)
330 for p in ports['ports']:
331 try:
332 self.neutron.delete_port(p["id"])
333 except Exception as e:
tiernoae4a8d12016-07-08 12:30:39 +0200334 self.logger.error("Error deleting port %s: %s", p["id"], str(e))
tierno7edb6752016-03-21 17:37:52 +0100335 self.neutron.delete_network(net_id)
tiernoae4a8d12016-07-08 12:30:39 +0200336 return net_id
337 except (neExceptions.ConnectionFailed, neExceptions.NetworkNotFoundClient, neExceptions.NeutronException,
338 neClient.exceptions.ConnectionFailed, ksExceptions.ClientException, neExceptions.NeutronException) as e:
339 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100340
tiernoae4a8d12016-07-08 12:30:39 +0200341 def refresh_nets_status(self, net_list):
342 '''Get the status of the networks
343 Params: the list of network identifiers
344 Returns a dictionary with:
345 net_id: #VIM id of this network
346 status: #Mandatory. Text with one of:
347 # DELETED (not found at vim)
348 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
349 # OTHER (Vim reported other status not understood)
350 # ERROR (VIM indicates an ERROR status)
351 # ACTIVE, INACTIVE, DOWN (admin down),
352 # BUILD (on building process)
353 #
354 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
355 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
356
357 '''
358 net_dict={}
359 for net_id in net_list:
360 net = {}
361 try:
362 net_vim = self.get_network(net_id)
363 if net_vim['status'] in netStatus2manoFormat:
364 net["status"] = netStatus2manoFormat[ net_vim['status'] ]
365 else:
366 net["status"] = "OTHER"
367 net["error_msg"] = "VIM status reported " + net_vim['status']
368
369 if net['status'] == "ACIVE" and not net_vim['admin_state_up']:
370 net['status'] = 'DOWN'
371 net['vim_info'] = yaml.safe_dump(net_vim)
372 if net_vim.get('fault'): #TODO
373 net['error_msg'] = str(net_vim['fault'])
374 except vimconn.vimconnNotFoundException as e:
375 self.logger.error("Exception getting net status: %s", str(e))
376 net['status'] = "DELETED"
377 net['error_msg'] = str(e)
378 except vimconn.vimconnException as e:
379 self.logger.error("Exception getting net status: %s", str(e))
380 net['status'] = "VIM_ERROR"
381 net['error_msg'] = str(e)
382 net_dict[net_id] = net
383 return net_dict
384
385 def get_flavor(self, flavor_id):
386 '''Obtain flavor details from the VIM. Returns the flavor dict details'''
387 self.logger.debug("Getting flavor '%s'", flavor_id)
tierno7edb6752016-03-21 17:37:52 +0100388 try:
389 self._reload_connection()
390 flavor = self.nova.flavors.find(id=flavor_id)
391 #TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
tiernoae4a8d12016-07-08 12:30:39 +0200392 return flavor.to_dict()
393 except (nvExceptions.NotFound, nvExceptions.ClientException, ksExceptions.ClientException) as e:
394 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100395
tiernoae4a8d12016-07-08 12:30:39 +0200396 def new_flavor(self, flavor_data, change_name_if_used=True):
tierno7edb6752016-03-21 17:37:52 +0100397 '''Adds a tenant flavor to openstack VIM
tiernoae4a8d12016-07-08 12:30:39 +0200398 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 +0100399 Returns the flavor identifier
400 '''
tiernoae4a8d12016-07-08 12:30:39 +0200401 self.logger.debug("Adding flavor '%s'", str(flavor_data))
tierno7edb6752016-03-21 17:37:52 +0100402 retry=0
tiernoae4a8d12016-07-08 12:30:39 +0200403 max_retries=3
tierno7edb6752016-03-21 17:37:52 +0100404 name_suffix = 0
tiernoae4a8d12016-07-08 12:30:39 +0200405 name=flavor_data['name']
406 while retry<max_retries:
tierno7edb6752016-03-21 17:37:52 +0100407 retry+=1
408 try:
409 self._reload_connection()
410 if change_name_if_used:
411 #get used names
412 fl_names=[]
413 fl=self.nova.flavors.list()
414 for f in fl:
415 fl_names.append(f.name)
416 while name in fl_names:
417 name_suffix += 1
tiernoae4a8d12016-07-08 12:30:39 +0200418 name = flavor_data['name']+"-" + str(name_suffix)
tierno7edb6752016-03-21 17:37:52 +0100419
tiernoae4a8d12016-07-08 12:30:39 +0200420 ram = flavor_data.get('ram',64)
421 vcpus = flavor_data.get('vcpus',1)
tierno7edb6752016-03-21 17:37:52 +0100422 numa_properties=None
423
tiernoae4a8d12016-07-08 12:30:39 +0200424 extended = flavor_data.get("extended")
tierno7edb6752016-03-21 17:37:52 +0100425 if extended:
426 numas=extended.get("numas")
427 if numas:
428 numa_nodes = len(numas)
429 if numa_nodes > 1:
430 return -1, "Can not add flavor with more than one numa"
431 numa_properties = {"hw:numa_nodes":str(numa_nodes)}
432 numa_properties["hw:mem_page_size"] = "large"
433 numa_properties["hw:cpu_policy"] = "dedicated"
434 numa_properties["hw:numa_mempolicy"] = "strict"
435 for numa in numas:
436 #overwrite ram and vcpus
437 ram = numa['memory']*1024
438 if 'paired-threads' in numa:
439 vcpus = numa['paired-threads']*2
440 numa_properties["hw:cpu_threads_policy"] = "prefer"
441 elif 'cores' in numa:
442 vcpus = numa['cores']
443 #numa_properties["hw:cpu_threads_policy"] = "prefer"
444 elif 'threads' in numa:
445 vcpus = numa['threads']
446 numa_properties["hw:cpu_policy"] = "isolated"
447 for interface in numa.get("interfaces",() ):
448 if interface["dedicated"]=="yes":
tierno809a7802016-07-08 13:31:24 +0200449 raise vimconn.vimconnException("Passthrough interfaces are not supported for the openstack connector", http_code=vimconn.HTTP_Service_Unavailable)
tierno7edb6752016-03-21 17:37:52 +0100450 #TODO, add the key 'pci_passthrough:alias"="<label at config>:<number ifaces>"' when a way to connect it is available
451
452 #create flavor
453 new_flavor=self.nova.flavors.create(name,
454 ram,
455 vcpus,
tiernoae4a8d12016-07-08 12:30:39 +0200456 flavor_data.get('disk',1),
457 is_public=flavor_data.get('is_public', True)
tierno7edb6752016-03-21 17:37:52 +0100458 )
459 #add metadata
460 if numa_properties:
461 new_flavor.set_keys(numa_properties)
tiernoae4a8d12016-07-08 12:30:39 +0200462 return new_flavor.id
tierno7edb6752016-03-21 17:37:52 +0100463 except nvExceptions.Conflict as e:
tiernoae4a8d12016-07-08 12:30:39 +0200464 if change_name_if_used and retry < max_retries:
tierno7edb6752016-03-21 17:37:52 +0100465 continue
tiernoae4a8d12016-07-08 12:30:39 +0200466 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100467 #except nvExceptions.BadRequest as e:
468 except (ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200469 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100470
tiernoae4a8d12016-07-08 12:30:39 +0200471 def delete_flavor(self,flavor_id):
472 '''Deletes a tenant flavor from openstack VIM. Returns the old flavor_id
tierno7edb6752016-03-21 17:37:52 +0100473 '''
tiernoae4a8d12016-07-08 12:30:39 +0200474 try:
475 self._reload_connection()
476 self.nova.flavors.delete(flavor_id)
477 return flavor_id
478 #except nvExceptions.BadRequest as e:
479 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException) as e:
480 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100481
tiernoae4a8d12016-07-08 12:30:39 +0200482 def new_image(self,image_dict):
tierno7edb6752016-03-21 17:37:52 +0100483 '''
tiernoae4a8d12016-07-08 12:30:39 +0200484 Adds a tenant image to VIM. imge_dict is a dictionary with:
485 name: name
486 disk_format: qcow2, vhd, vmdk, raw (by default), ...
487 location: path or URI
488 public: "yes" or "no"
489 metadata: metadata of the image
490 Returns the image_id
tierno7edb6752016-03-21 17:37:52 +0100491 '''
tierno7edb6752016-03-21 17:37:52 +0100492 #using version 1 of glance client
493 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 +0200494 retry=0
495 max_retries=3
496 while retry<max_retries:
tierno7edb6752016-03-21 17:37:52 +0100497 retry+=1
498 try:
499 self._reload_connection()
500 #determine format http://docs.openstack.org/developer/glance/formats.html
501 if "disk_format" in image_dict:
502 disk_format=image_dict["disk_format"]
503 else: #autodiscover base on extention
504 if image_dict['location'][-6:]==".qcow2":
505 disk_format="qcow2"
506 elif image_dict['location'][-4:]==".vhd":
507 disk_format="vhd"
508 elif image_dict['location'][-5:]==".vmdk":
509 disk_format="vmdk"
510 elif image_dict['location'][-4:]==".vdi":
511 disk_format="vdi"
512 elif image_dict['location'][-4:]==".iso":
513 disk_format="iso"
514 elif image_dict['location'][-4:]==".aki":
515 disk_format="aki"
516 elif image_dict['location'][-4:]==".ari":
517 disk_format="ari"
518 elif image_dict['location'][-4:]==".ami":
519 disk_format="ami"
520 else:
521 disk_format="raw"
tiernoae4a8d12016-07-08 12:30:39 +0200522 self.logger.debug("new_image: '%s' loading from '%s'", image_dict['name'], image_dict['location'])
tierno7edb6752016-03-21 17:37:52 +0100523 if image_dict['location'][0:4]=="http":
524 new_image = glancev1.images.create(name=image_dict['name'], is_public=image_dict.get('public',"yes")=="yes",
525 container_format="bare", location=image_dict['location'], disk_format=disk_format)
526 else: #local path
527 with open(image_dict['location']) as fimage:
528 new_image = glancev1.images.create(name=image_dict['name'], is_public=image_dict.get('public',"yes")=="yes",
529 container_format="bare", data=fimage, disk_format=disk_format)
530 #insert metadata. We cannot use 'new_image.properties.setdefault'
531 #because nova and glance are "INDEPENDENT" and we are using nova for reading metadata
532 new_image_nova=self.nova.images.find(id=new_image.id)
533 new_image_nova.metadata.setdefault('location',image_dict['location'])
534 metadata_to_load = image_dict.get('metadata')
535 if metadata_to_load:
536 for k,v in yaml.load(metadata_to_load).iteritems():
537 new_image_nova.metadata.setdefault(k,v)
tiernoae4a8d12016-07-08 12:30:39 +0200538 return new_image.id
539 except (nvExceptions.Conflict, ksExceptions.ClientException, nvExceptions.ClientException) as e:
540 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100541 except (HTTPException, gl1Exceptions.HTTPException, gl1Exceptions.CommunicationError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200542 if retry==max_retries:
543 continue
544 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100545 except IOError as e: #can not open the file
tiernoae4a8d12016-07-08 12:30:39 +0200546 raise vimconn.vimconnConnectionException(type(e).__name__ + ": " + str(e)+ " for " + image_dict['location'],
547 http_code=vimconn.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100548
tiernoae4a8d12016-07-08 12:30:39 +0200549 def delete_image(self, image_id):
550 '''Deletes a tenant image from openstack VIM. Returns the old id
tierno7edb6752016-03-21 17:37:52 +0100551 '''
tiernoae4a8d12016-07-08 12:30:39 +0200552 try:
553 self._reload_connection()
554 self.nova.images.delete(image_id)
555 return image_id
556 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError) as e: #TODO remove
557 self._format_exception(e)
558
559 def get_image_id_from_path(self, path):
560 '''Get the image id from image path in the VIM database. Returns the image_id
561 '''
562 try:
563 self._reload_connection()
564 images = self.nova.images.list()
565 for image in images:
566 if image.metadata.get("location")==path:
567 return image.id
568 raise vimconn.vimconnNotFoundException("image with location '{}' not found".format( path))
569 except (ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError) as e:
570 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100571
tiernoa4e1a6e2016-08-31 14:19:40 +0200572 def new_vminstance(self,name,description,start,image_id,flavor_id,net_list,cloud_config=None):
tierno7edb6752016-03-21 17:37:52 +0100573 '''Adds a VM instance to VIM
574 Params:
575 start: indicates if VM must start or boot in pause mode. Ignored
576 image_id,flavor_id: iamge and flavor uuid
577 net_list: list of interfaces, each one is a dictionary with:
578 name:
579 net_id: network uuid to connect
580 vpci: virtual vcpi to assign, ignored because openstack lack #TODO
581 model: interface model, ignored #TODO
582 mac_address: used for SR-IOV ifaces #TODO for other types
583 use: 'data', 'bridge', 'mgmt'
584 type: 'virtual', 'PF', 'VF', 'VFnotShared'
585 vim_id: filled/added by this function
586 #TODO ip, security groups
tiernoae4a8d12016-07-08 12:30:39 +0200587 Returns the instance identifier
tierno7edb6752016-03-21 17:37:52 +0100588 '''
tiernoae4a8d12016-07-08 12:30:39 +0200589 self.logger.debug("Creating VM image '%s' flavor '%s' nics='%s'",image_id, flavor_id,str(net_list))
tierno7edb6752016-03-21 17:37:52 +0100590 try:
tierno6e116232016-07-18 13:01:40 +0200591 metadata={}
tierno7edb6752016-03-21 17:37:52 +0100592 net_list_vim=[]
593 self._reload_connection()
tiernoae4a8d12016-07-08 12:30:39 +0200594 metadata_vpci={} #For a specific neutron plugin
tierno7edb6752016-03-21 17:37:52 +0100595 for net in net_list:
596 if not net.get("net_id"): #skip non connected iface
597 continue
598 if net["type"]=="virtual":
599 net_list_vim.append({'net-id': net["net_id"]})
600 if "vpci" in net:
601 metadata_vpci[ net["net_id"] ] = [[ net["vpci"], "" ]]
602 elif net["type"]=="PF":
tiernoae4a8d12016-07-08 12:30:39 +0200603 self.logger.warn("new_vminstance: Warning, can not connect a passthrough interface ")
tierno7edb6752016-03-21 17:37:52 +0100604 #TODO insert this when openstack consider passthrough ports as openstack neutron ports
605 else: #VF
606 if "vpci" in net:
607 if "VF" not in metadata_vpci:
608 metadata_vpci["VF"]=[]
609 metadata_vpci["VF"].append([ net["vpci"], "" ])
610 port_dict={
611 "network_id": net["net_id"],
612 "name": net.get("name"),
613 "binding:vnic_type": "direct",
614 "admin_state_up": True
615 }
616 if not port_dict["name"]:
617 port_dict["name"] = name
618 if net.get("mac_address"):
619 port_dict["mac_address"]=net["mac_address"]
620 #TODO: manage having SRIOV without vlan tag
621 #if net["type"] == "VFnotShared"
622 # port_dict["vlan"]=0
623 new_port = self.neutron.create_port({"port": port_dict })
624 net["mac_adress"] = new_port["port"]["mac_address"]
625 net["vim_id"] = new_port["port"]["id"]
626 net["ip"] = new_port["port"].get("fixed_ips",[{}])[0].get("ip_address")
627 net_list_vim.append({"port-id": new_port["port"]["id"]})
628 if metadata_vpci:
629 metadata = {"pci_assignement": json.dumps(metadata_vpci)}
tiernoafbced42016-07-23 01:43:53 +0200630 if len(metadata["pci_assignement"]) >255:
tierno6e116232016-07-18 13:01:40 +0200631 #limit the metadata size
632 #metadata["pci_assignement"] = metadata["pci_assignement"][0:255]
633 self.logger.warn("Metadata deleted since it exceeds the expected length (255) ")
634 metadata = {}
tierno7edb6752016-03-21 17:37:52 +0100635
tiernoae4a8d12016-07-08 12:30:39 +0200636 self.logger.debug("name '%s' image_id '%s'flavor_id '%s' net_list_vim '%s' description '%s' metadata %s",
637 name, image_id, flavor_id, str(net_list_vim), description, str(metadata))
tierno7edb6752016-03-21 17:37:52 +0100638
639 security_groups = self.config.get('security_groups')
640 if type(security_groups) is str:
641 security_groups = ( security_groups, )
tiernoa4e1a6e2016-08-31 14:19:40 +0200642 if isinstance(cloud_config, dict):
643 userdata="#cloud-config\nusers:\n"
644 #default user
645 if "key-pairs" in cloud_config:
646 userdata += " - default:\n ssh-authorized-keys:\n"
647 for key in cloud_config["key-pairs"]:
648 userdata += " - '{key}'\n".format(key=key)
649 for user in cloud_config.get("users",[]):
650 userdata += " - name: {name}\n sudo: ALL=(ALL) NOPASSWD:ALL\n".format(name=user["name"])
651 if "user-info" in user:
652 userdata += " gecos: {}'\n".format(user["user-info"])
653 if user.get("key-pairs"):
654 userdata += " ssh-authorized-keys:\n"
655 for key in user["key-pairs"]:
656 userdata += " - '{key}'\n".format(key=key)
657 self.logger.debug("userdata: %s", userdata)
658 elif isinstance(cloud_config, str):
659 userdata = cloud_config
660 else:
661 userdata=None
662
tierno7edb6752016-03-21 17:37:52 +0100663 server = self.nova.servers.create(name, image_id, flavor_id, nics=net_list_vim, meta=metadata,
664 security_groups = security_groups,
665 availability_zone = self.config.get('availability_zone'),
666 key_name = self.config.get('keypair'),
tiernoa4e1a6e2016-08-31 14:19:40 +0200667 userdata=userdata
tierno7edb6752016-03-21 17:37:52 +0100668 ) #, description=description)
669
670
tiernoae4a8d12016-07-08 12:30:39 +0200671 #print "DONE :-)", server
tierno7edb6752016-03-21 17:37:52 +0100672
673# #TODO server.add_floating_ip("10.95.87.209")
674# #To look for a free floating_ip
675# free_floating_ip = None
676# for floating_ip in self.neutron.list_floatingips().get("floatingips", () ):
677# if not floating_ip["port_id"]:
678# free_floating_ip = floating_ip["floating_ip_address"]
679# break
680# if free_floating_ip:
681# server.add_floating_ip(free_floating_ip)
682
683
tiernoae4a8d12016-07-08 12:30:39 +0200684 return server.id
tierno7edb6752016-03-21 17:37:52 +0100685# except nvExceptions.NotFound as e:
686# error_value=-vimconn.HTTP_Not_Found
687# error_text= "vm instance %s not found" % vm_id
tiernoae4a8d12016-07-08 12:30:39 +0200688 except (ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError,
689 neClient.exceptions.ConnectionFailed) as e:
690 self._format_exception(e)
691 except TypeError as e:
692 raise vimconn.vimconnException(type(e).__name__ + ": "+ str(e), http_code=vimconn.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100693
tiernoae4a8d12016-07-08 12:30:39 +0200694 def get_vminstance(self,vm_id):
tierno7edb6752016-03-21 17:37:52 +0100695 '''Returns the VM instance information from VIM'''
tiernoae4a8d12016-07-08 12:30:39 +0200696 #self.logger.debug("Getting VM from VIM")
tierno7edb6752016-03-21 17:37:52 +0100697 try:
698 self._reload_connection()
699 server = self.nova.servers.find(id=vm_id)
700 #TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
tiernoae4a8d12016-07-08 12:30:39 +0200701 return server.to_dict()
702 except (ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.NotFound) as e:
703 self._format_exception(e)
704
705 def get_vminstance_console(self,vm_id, console_type="vnc"):
tierno7edb6752016-03-21 17:37:52 +0100706 '''
707 Get a console for the virtual machine
708 Params:
709 vm_id: uuid of the VM
710 console_type, can be:
711 "novnc" (by default), "xvpvnc" for VNC types,
712 "rdp-html5" for RDP types, "spice-html5" for SPICE types
tiernoae4a8d12016-07-08 12:30:39 +0200713 Returns dict with the console parameters:
714 protocol: ssh, ftp, http, https, ...
715 server: usually ip address
716 port: the http, ssh, ... port
717 suffix: extra text, e.g. the http path and query string
tierno7edb6752016-03-21 17:37:52 +0100718 '''
tiernoae4a8d12016-07-08 12:30:39 +0200719 self.logger.debug("Getting VM CONSOLE from VIM")
tierno7edb6752016-03-21 17:37:52 +0100720 try:
721 self._reload_connection()
722 server = self.nova.servers.find(id=vm_id)
723 if console_type == None or console_type == "novnc":
724 console_dict = server.get_vnc_console("novnc")
725 elif console_type == "xvpvnc":
726 console_dict = server.get_vnc_console(console_type)
727 elif console_type == "rdp-html5":
728 console_dict = server.get_rdp_console(console_type)
729 elif console_type == "spice-html5":
730 console_dict = server.get_spice_console(console_type)
731 else:
tiernoae4a8d12016-07-08 12:30:39 +0200732 raise vimconn.vimconnException("console type '{}' not allowed".format(console_type), http_code=vimconn.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100733
734 console_dict1 = console_dict.get("console")
735 if console_dict1:
736 console_url = console_dict1.get("url")
737 if console_url:
738 #parse console_url
739 protocol_index = console_url.find("//")
740 suffix_index = console_url[protocol_index+2:].find("/") + protocol_index+2
741 port_index = console_url[protocol_index+2:suffix_index].find(":") + protocol_index+2
742 if protocol_index < 0 or port_index<0 or suffix_index<0:
743 return -vimconn.HTTP_Internal_Server_Error, "Unexpected response from VIM"
744 console_dict={"protocol": console_url[0:protocol_index],
745 "server": console_url[protocol_index+2:port_index],
746 "port": console_url[port_index:suffix_index],
747 "suffix": console_url[suffix_index+1:]
748 }
749 protocol_index += 2
tiernoae4a8d12016-07-08 12:30:39 +0200750 return console_dict
751 raise vimconn.vimconnUnexpectedResponse("Unexpected response from VIM")
tierno7edb6752016-03-21 17:37:52 +0100752
tiernoae4a8d12016-07-08 12:30:39 +0200753 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.BadRequest) as e:
754 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100755
tiernoae4a8d12016-07-08 12:30:39 +0200756 def delete_vminstance(self, vm_id):
757 '''Removes a VM instance from VIM. Returns the old identifier
tierno7edb6752016-03-21 17:37:52 +0100758 '''
tiernoae4a8d12016-07-08 12:30:39 +0200759 #print "osconnector: Getting VM from VIM"
tierno7edb6752016-03-21 17:37:52 +0100760 try:
761 self._reload_connection()
762 #delete VM ports attached to this networks before the virtual machine
763 ports = self.neutron.list_ports(device_id=vm_id)
764 for p in ports['ports']:
765 try:
766 self.neutron.delete_port(p["id"])
767 except Exception as e:
tiernoae4a8d12016-07-08 12:30:39 +0200768 self.logger.error("Error deleting port: " + type(e).__name__ + ": "+ str(e))
tierno7edb6752016-03-21 17:37:52 +0100769 self.nova.servers.delete(vm_id)
tiernoae4a8d12016-07-08 12:30:39 +0200770 return vm_id
771 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException) as e:
772 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100773 #TODO insert exception vimconn.HTTP_Unauthorized
774 #if reaching here is because an exception
tierno7edb6752016-03-21 17:37:52 +0100775
tiernoae4a8d12016-07-08 12:30:39 +0200776 def refresh_vms_status(self, vm_list):
777 '''Get the status of the virtual machines and their interfaces/ports
778 Params: the list of VM identifiers
779 Returns a dictionary with:
780 vm_id: #VIM id of this Virtual Machine
781 status: #Mandatory. Text with one of:
782 # DELETED (not found at vim)
783 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
784 # OTHER (Vim reported other status not understood)
785 # ERROR (VIM indicates an ERROR status)
786 # ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running),
787 # CREATING (on building process), ERROR
788 # ACTIVE:NoMgmtIP (Active but any of its interface has an IP address
789 #
790 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
791 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
792 interfaces:
793 - vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
794 mac_address: #Text format XX:XX:XX:XX:XX:XX
795 vim_net_id: #network id where this interface is connected
796 vim_interface_id: #interface/port VIM id
797 ip_address: #null, or text with IPv4, IPv6 address
tierno7edb6752016-03-21 17:37:52 +0100798 '''
tiernoae4a8d12016-07-08 12:30:39 +0200799 vm_dict={}
800 self.logger.debug("refresh_vms status: Getting tenant VM instance information from VIM")
801 for vm_id in vm_list:
802 vm={}
803 try:
804 vm_vim = self.get_vminstance(vm_id)
805 if vm_vim['status'] in vmStatus2manoFormat:
806 vm['status'] = vmStatus2manoFormat[ vm_vim['status'] ]
tierno7edb6752016-03-21 17:37:52 +0100807 else:
tiernoae4a8d12016-07-08 12:30:39 +0200808 vm['status'] = "OTHER"
809 vm['error_msg'] = "VIM status reported " + vm_vim['status']
810 vm['vim_info'] = yaml.safe_dump(vm_vim)
811 vm["interfaces"] = []
812 if vm_vim.get('fault'):
813 vm['error_msg'] = str(vm_vim['fault'])
814 #get interfaces
tierno7edb6752016-03-21 17:37:52 +0100815 try:
tiernoae4a8d12016-07-08 12:30:39 +0200816 self._reload_connection()
817 port_dict=self.neutron.list_ports(device_id=vm_id)
818 for port in port_dict["ports"]:
819 interface={}
820 interface['vim_info'] = yaml.safe_dump(port)
821 interface["mac_address"] = port.get("mac_address")
822 interface["vim_net_id"] = port["network_id"]
823 interface["vim_interface_id"] = port["id"]
824 ips=[]
825 #look for floating ip address
826 floating_ip_dict = self.neutron.list_floatingips(port_id=port["id"])
827 if floating_ip_dict.get("floatingips"):
828 ips.append(floating_ip_dict["floatingips"][0].get("floating_ip_address") )
tierno7edb6752016-03-21 17:37:52 +0100829
tiernoae4a8d12016-07-08 12:30:39 +0200830 for subnet in port["fixed_ips"]:
831 ips.append(subnet["ip_address"])
832 interface["ip_address"] = ";".join(ips)
833 vm["interfaces"].append(interface)
834 except Exception as e:
835 self.logger.error("Error getting vm interface information " + type(e).__name__ + ": "+ str(e))
836 except vimconn.vimconnNotFoundException as e:
837 self.logger.error("Exception getting vm status: %s", str(e))
838 vm['status'] = "DELETED"
839 vm['error_msg'] = str(e)
840 except vimconn.vimconnException as e:
841 self.logger.error("Exception getting vm status: %s", str(e))
842 vm['status'] = "VIM_ERROR"
843 vm['error_msg'] = str(e)
844 vm_dict[vm_id] = vm
845 return vm_dict
tierno7edb6752016-03-21 17:37:52 +0100846
tiernoae4a8d12016-07-08 12:30:39 +0200847 def action_vminstance(self, vm_id, action_dict):
tierno7edb6752016-03-21 17:37:52 +0100848 '''Send and action over a VM instance from VIM
tiernoae4a8d12016-07-08 12:30:39 +0200849 Returns the vm_id if the action was successfully sent to the VIM'''
850 self.logger.debug("Action over VM '%s': %s", vm_id, str(action_dict))
tierno7edb6752016-03-21 17:37:52 +0100851 try:
852 self._reload_connection()
853 server = self.nova.servers.find(id=vm_id)
854 if "start" in action_dict:
855 if action_dict["start"]=="rebuild":
856 server.rebuild()
857 else:
858 if server.status=="PAUSED":
859 server.unpause()
860 elif server.status=="SUSPENDED":
861 server.resume()
862 elif server.status=="SHUTOFF":
863 server.start()
864 elif "pause" in action_dict:
865 server.pause()
866 elif "resume" in action_dict:
867 server.resume()
868 elif "shutoff" in action_dict or "shutdown" in action_dict:
869 server.stop()
870 elif "forceOff" in action_dict:
871 server.stop() #TODO
872 elif "terminate" in action_dict:
873 server.delete()
874 elif "createImage" in action_dict:
875 server.create_image()
876 #"path":path_schema,
877 #"description":description_schema,
878 #"name":name_schema,
879 #"metadata":metadata_schema,
880 #"imageRef": id_schema,
881 #"disk": {"oneOf":[{"type": "null"}, {"type":"string"}] },
882 elif "rebuild" in action_dict:
883 server.rebuild(server.image['id'])
884 elif "reboot" in action_dict:
885 server.reboot() #reboot_type='SOFT'
886 elif "console" in action_dict:
887 console_type = action_dict["console"]
888 if console_type == None or console_type == "novnc":
889 console_dict = server.get_vnc_console("novnc")
890 elif console_type == "xvpvnc":
891 console_dict = server.get_vnc_console(console_type)
892 elif console_type == "rdp-html5":
893 console_dict = server.get_rdp_console(console_type)
894 elif console_type == "spice-html5":
895 console_dict = server.get_spice_console(console_type)
896 else:
tiernoae4a8d12016-07-08 12:30:39 +0200897 raise vimconn.vimconnException("console type '{}' not allowed".format(console_type),
898 http_code=vimconn.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100899 try:
900 console_url = console_dict["console"]["url"]
901 #parse console_url
902 protocol_index = console_url.find("//")
903 suffix_index = console_url[protocol_index+2:].find("/") + protocol_index+2
904 port_index = console_url[protocol_index+2:suffix_index].find(":") + protocol_index+2
905 if protocol_index < 0 or port_index<0 or suffix_index<0:
tiernoae4a8d12016-07-08 12:30:39 +0200906 raise vimconn.vimconnException("Unexpected response from VIM " + str(console_dict))
tierno7edb6752016-03-21 17:37:52 +0100907 console_dict2={"protocol": console_url[0:protocol_index],
908 "server": console_url[protocol_index+2 : port_index],
909 "port": int(console_url[port_index+1 : suffix_index]),
910 "suffix": console_url[suffix_index+1:]
911 }
tiernoae4a8d12016-07-08 12:30:39 +0200912 return console_dict2
913 except Exception as e:
914 raise vimconn.vimconnException("Unexpected response from VIM " + str(console_dict))
tierno7edb6752016-03-21 17:37:52 +0100915
tiernoae4a8d12016-07-08 12:30:39 +0200916 return vm_id
917 except (ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.NotFound) as e:
918 self._format_exception(e)
919 #TODO insert exception vimconn.HTTP_Unauthorized
920
921#NOT USED FUNCTIONS
922
923 def new_external_port(self, port_data):
924 #TODO openstack if needed
925 '''Adds a external port to VIM'''
926 '''Returns the port identifier'''
927 return -vimconn.HTTP_Internal_Server_Error, "osconnector.new_external_port() not implemented"
928
929 def connect_port_network(self, port_id, network_id, admin=False):
930 #TODO openstack if needed
931 '''Connects a external port to a network'''
932 '''Returns status code of the VIM response'''
933 return -vimconn.HTTP_Internal_Server_Error, "osconnector.connect_port_network() not implemented"
934
935 def new_user(self, user_name, user_passwd, tenant_id=None):
936 '''Adds a new user to openstack VIM'''
937 '''Returns the user identifier'''
938 self.logger.debug("osconnector: Adding a new user to VIM")
939 try:
940 self._reload_connection()
941 user=self.keystone.users.create(user_name, user_passwd, tenant_id=tenant_id)
942 #self.keystone.tenants.add_user(self.k_creds["username"], #role)
943 return user.id
944 except ksExceptions.ConnectionError as e:
945 error_value=-vimconn.HTTP_Bad_Request
946 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
947 except ksExceptions.ClientException as e: #TODO remove
tierno7edb6752016-03-21 17:37:52 +0100948 error_value=-vimconn.HTTP_Bad_Request
949 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
950 #TODO insert exception vimconn.HTTP_Unauthorized
951 #if reaching here is because an exception
952 if self.debug:
tiernoae4a8d12016-07-08 12:30:39 +0200953 self.logger.debug("new_user " + error_text)
tierno7edb6752016-03-21 17:37:52 +0100954 return error_value, error_text
tiernoae4a8d12016-07-08 12:30:39 +0200955
956 def delete_user(self, user_id):
957 '''Delete a user from openstack VIM'''
958 '''Returns the user identifier'''
959 if self.debug:
960 print "osconnector: Deleting a user from VIM"
961 try:
962 self._reload_connection()
963 self.keystone.users.delete(user_id)
964 return 1, user_id
965 except ksExceptions.ConnectionError as e:
966 error_value=-vimconn.HTTP_Bad_Request
967 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
968 except ksExceptions.NotFound as e:
969 error_value=-vimconn.HTTP_Not_Found
970 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
971 except ksExceptions.ClientException as e: #TODO remove
972 error_value=-vimconn.HTTP_Bad_Request
973 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
974 #TODO insert exception vimconn.HTTP_Unauthorized
975 #if reaching here is because an exception
976 if self.debug:
977 print "delete_tenant " + error_text
978 return error_value, error_text
979
tierno7edb6752016-03-21 17:37:52 +0100980 def get_hosts_info(self):
981 '''Get the information of deployed hosts
982 Returns the hosts content'''
983 if self.debug:
984 print "osconnector: Getting Host info from VIM"
985 try:
986 h_list=[]
987 self._reload_connection()
988 hypervisors = self.nova.hypervisors.list()
989 for hype in hypervisors:
990 h_list.append( hype.to_dict() )
991 return 1, {"hosts":h_list}
992 except nvExceptions.NotFound as e:
993 error_value=-vimconn.HTTP_Not_Found
994 error_text= (str(e) if len(e.args)==0 else str(e.args[0]))
995 except (ksExceptions.ClientException, nvExceptions.ClientException) as e:
996 error_value=-vimconn.HTTP_Bad_Request
997 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
998 #TODO insert exception vimconn.HTTP_Unauthorized
999 #if reaching here is because an exception
1000 if self.debug:
1001 print "get_hosts_info " + error_text
1002 return error_value, error_text
1003
1004 def get_hosts(self, vim_tenant):
1005 '''Get the hosts and deployed instances
1006 Returns the hosts content'''
1007 r, hype_dict = self.get_hosts_info()
1008 if r<0:
1009 return r, hype_dict
1010 hypervisors = hype_dict["hosts"]
1011 try:
1012 servers = self.nova.servers.list()
1013 for hype in hypervisors:
1014 for server in servers:
1015 if server.to_dict()['OS-EXT-SRV-ATTR:hypervisor_hostname']==hype['hypervisor_hostname']:
1016 if 'vm' in hype:
1017 hype['vm'].append(server.id)
1018 else:
1019 hype['vm'] = [server.id]
1020 return 1, hype_dict
1021 except nvExceptions.NotFound as e:
1022 error_value=-vimconn.HTTP_Not_Found
1023 error_text= (str(e) if len(e.args)==0 else str(e.args[0]))
1024 except (ksExceptions.ClientException, nvExceptions.ClientException) as e:
1025 error_value=-vimconn.HTTP_Bad_Request
1026 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1027 #TODO insert exception vimconn.HTTP_Unauthorized
1028 #if reaching here is because an exception
1029 if self.debug:
1030 print "get_hosts " + error_text
1031 return error_value, error_text
1032
tierno7edb6752016-03-21 17:37:52 +01001033