1 # -*- coding: utf-8 -*-
4 # Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U.
5 # This file is part of openmano
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
12 # http://www.apache.org/licenses/LICENSE-2.0
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
20 # For those usages not covered by the Apache License, Version 2.0 please
21 # contact with: nfvlabs@tid.es
25 osconnector implements all the methods to interact with openstack using the python-client.
27 __author__
="Alfonso Tierno, Gerardo Garcia, xFlow Research"
28 __date__
="$24-nov-2016 09:10$"
36 from novaclient
import client
as nClient_v2
, exceptions
as nvExceptions
, api_versions
as APIVersion
37 import keystoneclient
.v2_0
.client
as ksClient_v2
38 from novaclient
.v2
.client
import Client
as nClient
39 import keystoneclient
.v3
.client
as ksClient
40 import keystoneclient
.exceptions
as ksExceptions
41 import glanceclient
.v2
.client
as glClient
42 import glanceclient
.client
as gl1Client
43 import glanceclient
.exc
as gl1Exceptions
44 from httplib
import HTTPException
45 from neutronclient
.neutron
import client
as neClient_v2
46 from neutronclient
.v2_0
import client
as neClient
47 from neutronclient
.common
import exceptions
as neExceptions
48 from requests
.exceptions
import ConnectionError
50 '''contain the openstack virtual machine status to openmano status'''
51 vmStatus2manoFormat
={'ACTIVE':'ACTIVE',
53 'SUSPENDED': 'SUSPENDED',
56 'ERROR':'ERROR','DELETED':'DELETED'
58 netStatus2manoFormat
={'ACTIVE':'ACTIVE','PAUSED':'PAUSED','INACTIVE':'INACTIVE','BUILD':'BUILD','ERROR':'ERROR','DELETED':'DELETED'
61 class vimconnector(vimconn
.vimconnector
):
62 def __init__(self
, uuid
, name
, tenant_id
, tenant_name
, url
, url_admin
=None, user
=None, passwd
=None, log_level
=None, config
={}):
63 '''using common constructor parameters. In this case
64 'url' is the keystone authorization url,
65 'url_admin' is not use
67 self
.osc_api_version
= 'v2.0'
68 if config
.get('APIversion') == 'v3.3':
69 self
.osc_api_version
= 'v3.3'
70 vimconn
.vimconnector
.__init
__(self
, uuid
, name
, tenant_id
, tenant_name
, url
, url_admin
, user
, passwd
, log_level
, config
)
75 raise TypeError, 'url param can not be NoneType'
76 self
.k_creds
['auth_url'] = url
77 self
.n_creds
['auth_url'] = url
79 self
.k_creds
['tenant_name'] = tenant_name
80 self
.n_creds
['project_id'] = tenant_name
82 self
.k_creds
['tenant_id'] = tenant_id
83 self
.n_creds
['tenant_id'] = tenant_id
85 self
.k_creds
['username'] = user
86 self
.n_creds
['username'] = user
88 self
.k_creds
['password'] = passwd
89 self
.n_creds
['api_key'] = passwd
90 if self
.osc_api_version
== 'v3.3':
91 self
.k_creds
['project_name'] = tenant_name
92 self
.k_creds
['project_id'] = tenant_id
93 self
.reload_client
= True
94 self
.logger
= logging
.getLogger('openmano.vim.openstack')
96 self
.logger
.setLevel( getattr(logging
, log_level
) )
98 def __setitem__(self
,index
, value
):
99 '''Set individuals parameters
100 Throw TypeError, KeyError
102 if index
=='tenant_id':
103 self
.reload_client
=True
104 self
.tenant_id
= value
105 if self
.osc_api_version
== 'v3.3':
107 self
.k_creds
['project_id'] = value
108 self
.n_creds
['project_id'] = value
110 del self
.k_creds
['project_id']
111 del self
.n_creds
['project_id']
114 self
.k_creds
['tenant_id'] = value
115 self
.n_creds
['tenant_id'] = value
117 del self
.k_creds
['tenant_id']
118 del self
.n_creds
['tenant_id']
119 elif index
=='tenant_name':
120 self
.reload_client
=True
121 self
.tenant_name
= value
122 if self
.osc_api_version
== 'v3.3':
124 self
.k_creds
['project_name'] = value
125 self
.n_creds
['project_name'] = value
127 del self
.k_creds
['project_name']
128 del self
.n_creds
['project_name']
131 self
.k_creds
['tenant_name'] = value
132 self
.n_creds
['project_id'] = value
134 del self
.k_creds
['tenant_name']
135 del self
.n_creds
['project_id']
137 self
.reload_client
=True
140 self
.k_creds
['username'] = value
141 self
.n_creds
['username'] = value
143 del self
.k_creds
['username']
144 del self
.n_creds
['username']
145 elif index
=='passwd':
146 self
.reload_client
=True
149 self
.k_creds
['password'] = value
150 self
.n_creds
['api_key'] = value
152 del self
.k_creds
['password']
153 del self
.n_creds
['api_key']
155 self
.reload_client
=True
158 self
.k_creds
['auth_url'] = value
159 self
.n_creds
['auth_url'] = value
161 raise TypeError, 'url param can not be NoneType'
163 vimconn
.vimconnector
.__setitem
__(self
,index
, value
)
165 def _reload_connection(self
):
166 '''Called before any operation, it check if credentials has changed
167 Throw keystoneclient.apiclient.exceptions.AuthorizationFailure
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
:
172 if len(self
.n_creds
) <4:
173 raise ksExceptions
.ClientException("Not enough parameters to connect to openstack")
174 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
)
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
)
184 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
186 self
.reload_client
= False
188 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
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":
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
,
208 ConnectionError
, ksExceptions
.ConnectionError
, neExceptions
.ConnectionFailed
210 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
))
219 raise vimconn
.vimconnConnectionException(type(exception
).__name
__ + ": " + str(exception
))
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
227 Returns the tenant list of dictionaries: [{'name':'<name>, 'id':'<id>, ...}, ...]
229 self
.logger
.debug("Getting tenants from VIM filter: '%s'", str(filter_dict
))
231 self
._reload
_connection
()
232 if osc_api_version
== 'v3.3':
233 project_class_list
=self
.keystone
.projects
.findall(**filter_dict
)
235 project_class_list
=self
.keystone
.tenants
.findall(**filter_dict
)
237 for project
in project_class_list
:
238 project_list
.append(project
.to_dict())
240 except (ksExceptions
.ConnectionError
, ksExceptions
.ClientException
, ConnectionError
) as e
:
241 self
._format
_exception
(e
)
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
)
247 self
._reload
_connection
()
248 if self
.osc_api_version
== 'v3.3':
249 project
=self
.keystone
.projects
.create(tenant_name
, tenant_description
)
251 project
=self
.keystone
.tenants
.create(tenant_name
, tenant_description
)
253 except (ksExceptions
.ConnectionError
, ksExceptions
.ClientException
, ConnectionError
) as e
:
254 self
._format
_exception
(e
)
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
)
260 self
._reload
_connection
()
261 if osc_api_version
== 'v3.3':
262 self
.keystone
.projects
.delete(tenant_id
)
264 self
.keystone
.tenants
.delete(tenant_id
)
266 except (ksExceptions
.ConnectionError
, ksExceptions
.ClientException
, ConnectionError
) as e
:
267 self
._format
_exception
(e
)
269 def new_network(self
,net_name
, net_type
, ip_profile
=None, shared
=False, vlan
=None):
270 '''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
)
272 #self.logger.debug(">>>>>>>>>>>>>>>>>> IP profile %s", str(ip_profile))
275 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:
279 raise vimconn
.vimconnConflictException("You must provide a 'dataplane_physical_net' at config value before creating sriov network")
280 network_dict
["provider:physical_network"] = self
.config
['dataplane_physical_net'] #"physnet_sriov" #TODO physical
281 network_dict
["provider:network_type"] = "vlan"
283 network_dict
["provider:network_type"] = vlan
284 network_dict
["shared"]=shared
285 new_net
=self
.neutron
.create_network({'network':network_dict
})
287 #create subnetwork, even if there is no 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"
295 subnet
={"name":net_name
+"-subnet",
296 "network_id": new_net
["network"]["id"],
297 "ip_version": 4 if ip_profile
['ip_version']=="IPv4" else 6,
298 "cidr": ip_profile
['subnet_address']
300 if 'gateway_address' in ip_profile
:
301 subnet
['gateway_ip'] = ip_profile
['gateway_address']
302 if ip_profile
.get('dns_address'):
303 #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']))
316 ip_int
+= ip_profile
['dhcp_count'] - 1
317 ip_str
= str(netaddr
.IPAddress(ip_int
))
318 subnet
['allocation_pools'][0]['end'] = ip_str
319 #self.logger.debug(">>>>>>>>>>>>>>>>>> Subnet: %s", str(subnet))
320 self
.neutron
.create_subnet({"subnet": subnet
} )
321 return new_net
["network"]["id"]
322 except (neExceptions
.ConnectionFailed
, ksExceptions
.ClientException
, neExceptions
.NeutronException
, ConnectionError
) as e
:
324 self
.neutron
.delete_network(new_net
['network']['id'])
325 self
._format
_exception
(e
)
327 def get_network_list(self
, filter_dict
={}):
328 '''Obtain tenant networks of VIM
334 admin_state_up: boolean
336 Returns the network list of dictionaries
338 self
.logger
.debug("Getting network from VIM filter: '%s'", str(filter_dict
))
340 self
._reload
_connection
()
341 if osc_api_version
== 'v3.3' and "tenant_id" in filter_dict
:
342 filter_dict
['project_id'] = filter_dict
.pop('tenant_id')
343 net_dict
=self
.neutron
.list_networks(**filter_dict
)
344 net_list
=net_dict
["networks"]
345 self
.__net
_os
2mano
(net_list
)
347 except (neExceptions
.ConnectionFailed
, ksExceptions
.ClientException
, neExceptions
.NeutronException
, ConnectionError
) as e
:
348 self
._format
_exception
(e
)
350 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
)
354 filter_dict
={"id": net_id
}
355 net_list
= self
.get_network_list(filter_dict
)
357 raise vimconn
.vimconnNotFoundException("Network '{}' not found".format(net_id
))
358 elif len(net_list
)>1:
359 raise vimconn
.vimconnConflictException("Found more than one network with this criteria")
362 for subnet_id
in net
.get("subnets", () ):
364 subnet
= self
.neutron
.show_subnet(subnet_id
)
365 except Exception as e
:
366 self
.logger
.error("osconnector.get_network(): Error getting subnet %s %s" % (net_id
, str(e
)))
367 subnet
= {"id": subnet_id
, "fault": str(e
)}
368 subnets
.append(subnet
)
369 net
["subnets"] = subnets
372 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
)
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']:
381 self
.neutron
.delete_port(p
["id"])
382 except Exception as e
:
383 self
.logger
.error("Error deleting port %s: %s", p
["id"], str(e
))
384 self
.neutron
.delete_network(net_id
)
386 except (neExceptions
.ConnectionFailed
, neExceptions
.NetworkNotFoundClient
, neExceptions
.NeutronException
,
387 ksExceptions
.ClientException
, neExceptions
.NeutronException
, ConnectionError
) as e
:
388 self
._format
_exception
(e
)
390 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)
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)
408 for net_id
in net_list
:
411 net_vim
= self
.get_network(net_id
)
412 if net_vim
['status'] in netStatus2manoFormat
:
413 net
["status"] = netStatus2manoFormat
[ net_vim
['status'] ]
415 net
["status"] = "OTHER"
416 net
["error_msg"] = "VIM status reported " + net_vim
['status']
418 if net
['status'] == "ACTIVE" and not net_vim
['admin_state_up']:
419 net
['status'] = 'DOWN'
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
)
424 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
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
)
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)
444 return flavor
.to_dict()
445 except (nvExceptions
.NotFound
, nvExceptions
.ClientException
, ksExceptions
.ClientException
, ConnectionError
) as e
:
446 self
._format
_exception
(e
)
448 def new_flavor(self
, flavor_data
, change_name_if_used
=True):
449 '''Adds a tenant flavor to openstack VIM
450 if change_name_if_used is True, it will change name in case of conflict, because it is not supported name repetition
451 Returns the flavor identifier
453 self
.logger
.debug("Adding flavor '%s'", str(flavor_data
))
457 name
=flavor_data
['name']
458 while retry
<max_retries
:
461 self
._reload
_connection
()
462 if change_name_if_used
:
465 fl
=self
.nova
.flavors
.list()
467 fl_names
.append(f
.name
)
468 while name
in fl_names
:
470 name
= flavor_data
['name']+"-" + str(name_suffix
)
472 ram
= flavor_data
.get('ram',64)
473 vcpus
= flavor_data
.get('vcpus',1)
476 extended
= flavor_data
.get("extended")
478 numas
=extended
.get("numas")
480 numa_nodes
= len(numas
)
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"
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":
501 raise vimconn
.vimconnException("Passthrough interfaces are not supported for the openstack connector", http_code
=vimconn
.HTTP_Service_Unavailable
)
502 #TODO, add the key 'pci_passthrough:alias"="<label at config>:<number ifaces>"' when a way to connect it is available
505 new_flavor
=self
.nova
.flavors
.create(name
,
508 flavor_data
.get('disk',1),
509 is_public
=flavor_data
.get('is_public', True)
513 new_flavor
.set_keys(numa_properties
)
515 except nvExceptions
.Conflict
as e
:
516 if change_name_if_used
and retry
< max_retries
:
518 self
._format
_exception
(e
)
519 #except nvExceptions.BadRequest as e:
520 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
, ConnectionError
) as e
:
521 self
._format
_exception
(e
)
523 def delete_flavor(self
,flavor_id
):
524 '''Deletes a tenant flavor from openstack VIM. Returns the old flavor_id
527 self
._reload
_connection
()
528 self
.nova
.flavors
.delete(flavor_id
)
530 #except nvExceptions.BadRequest as e:
531 except (nvExceptions
.NotFound
, ksExceptions
.ClientException
, nvExceptions
.ClientException
, ConnectionError
) as e
:
532 self
._format
_exception
(e
)
534 def new_image(self
,image_dict
):
536 Adds a tenant image to VIM. imge_dict is a dictionary with:
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
544 #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
548 while retry
<max_retries
:
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":
558 elif image_dict
['location'][-4:]==".vhd":
560 elif image_dict
['location'][-5:]==".vmdk":
562 elif image_dict
['location'][-4:]==".vdi":
564 elif image_dict
['location'][-4:]==".iso":
566 elif image_dict
['location'][-4:]==".aki":
568 elif image_dict
['location'][-4:]==".ari":
570 elif image_dict
['location'][-4:]==".ami":
574 self
.logger
.debug("new_image: '%s' loading from '%s'", image_dict
['name'], image_dict
['location'])
575 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
)
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')
588 for k
,v
in yaml
.load(metadata_to_load
).iteritems():
589 new_image_nova
.metadata
.setdefault(k
,v
)
591 except (nvExceptions
.Conflict
, ksExceptions
.ClientException
, nvExceptions
.ClientException
) as e
:
592 self
._format
_exception
(e
)
593 except (HTTPException
, gl1Exceptions
.HTTPException
, gl1Exceptions
.CommunicationError
, ConnectionError
) as e
:
594 if retry
==max_retries
:
596 self
._format
_exception
(e
)
597 except IOError as e
: #can not open the file
598 raise vimconn
.vimconnConnectionException(type(e
).__name
__ + ": " + str(e
)+ " for " + image_dict
['location'],
599 http_code
=vimconn
.HTTP_Bad_Request
)
601 def delete_image(self
, image_id
):
602 '''Deletes a tenant image from openstack VIM. Returns the old id
605 self
._reload
_connection
()
606 self
.nova
.images
.delete(image_id
)
608 except (nvExceptions
.NotFound
, ksExceptions
.ClientException
, nvExceptions
.ClientException
, gl1Exceptions
.CommunicationError
, ConnectionError
) as e
: #TODO remove
609 self
._format
_exception
(e
)
611 def get_image_id_from_path(self
, path
):
612 '''Get the image id from image path in the VIM database. Returns the image_id'''
614 self
._reload
_connection
()
615 images
= self
.nova
.images
.list()
617 if image
.metadata
.get("location")==path
:
619 raise vimconn
.vimconnNotFoundException("image with location '{}' not found".format( path
))
620 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
, gl1Exceptions
.CommunicationError
, ConnectionError
) as e
:
621 self
._format
_exception
(e
)
623 def get_image_list(self
, filter_dict
={}):
624 '''Obtain tenant images from VIM
628 checksum: image checksum
629 Returns the image list of dictionaries:
630 [{<the fields at Filter_dict plus some VIM specific>}, ...]
633 self
.logger
.debug("Getting image list from VIM filter: '%s'", str(filter_dict
))
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:
642 #Then we filter by the rest of filter fields: checksum
644 for image
in image_list
:
645 image_dict
=self
.glance
.images
.get(image
.id)
646 if image_dict
['checksum']==filter_dict
.get('checksum'):
647 filtered_list
.append(image
)
649 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
, gl1Exceptions
.CommunicationError
, ConnectionError
) as e
:
650 self
._format
_exception
(e
)
652 def new_vminstance(self
,name
,description
,start
,image_id
,flavor_id
,net_list
,cloud_config
=None):
653 '''Adds a VM instance to VIM
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:
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
667 Returns the instance identifier
669 self
.logger
.debug("Creating VM image '%s' flavor '%s' nics='%s'",image_id
, flavor_id
,str(net_list
))
673 self
._reload
_connection
()
674 metadata_vpci
={} #For a specific neutron plugin
676 if not net
.get("net_id"): #skip non connected iface
678 if net
["type"]=="virtual":
679 net_list_vim
.append({'net-id': net
["net_id"]})
681 metadata_vpci
[ net
["net_id"] ] = [[ net
["vpci"], "" ]]
682 elif net
["type"]=="PF":
683 self
.logger
.warn("new_vminstance: Warning, can not connect a passthrough interface ")
684 #TODO insert this when openstack consider passthrough ports as openstack neutron ports
687 if "VF" not in metadata_vpci
:
688 metadata_vpci
["VF"]=[]
689 metadata_vpci
["VF"].append([ net
["vpci"], "" ])
691 "network_id": net
["net_id"],
692 "name": net
.get("name"),
693 "binding:vnic_type": "direct",
694 "admin_state_up": True
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"]})
709 metadata
= {"pci_assignement": json
.dumps(metadata_vpci
)}
710 if len(metadata
["pci_assignement"]) >255:
711 #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) ")
716 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
))
719 security_groups
= self
.config
.get('security_groups')
720 if type(security_groups
) is str:
721 security_groups
= ( security_groups
, )
722 if isinstance(cloud_config
, dict):
723 userdata
="#cloud-config\nusers:\n"
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
743 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'),
748 ) #, description=description)
751 #print "DONE :-)", server
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"]
760 # if free_floating_ip:
761 # server.add_floating_ip(free_floating_ip)
765 # except nvExceptions.NotFound as e:
766 # error_value=-vimconn.HTTP_Not_Found
767 # error_text= "vm instance %s not found" % vm_id
768 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
, ConnectionError
770 self
._format
_exception
(e
)
771 except TypeError as e
:
772 raise vimconn
.vimconnException(type(e
).__name
__ + ": "+ str(e
), http_code
=vimconn
.HTTP_Bad_Request
)
774 def get_vminstance(self
,vm_id
):
775 '''Returns the VM instance information from VIM'''
776 #self.logger.debug("Getting VM from VIM")
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)
781 return server
.to_dict()
782 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
, nvExceptions
.NotFound
, ConnectionError
) as e
:
783 self
._format
_exception
(e
)
785 def get_vminstance_console(self
,vm_id
, console_type
="vnc"):
787 Get a console for the virtual machine
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
793 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
799 self
.logger
.debug("Getting VM CONSOLE from VIM")
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
)
812 raise vimconn
.vimconnException("console type '{}' not allowed".format(console_type
), http_code
=vimconn
.HTTP_Bad_Request
)
814 console_dict1
= console_dict
.get("console")
816 console_url
= console_dict1
.get("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:]
831 raise vimconn
.vimconnUnexpectedResponse("Unexpected response from VIM")
833 except (nvExceptions
.NotFound
, ksExceptions
.ClientException
, nvExceptions
.ClientException
, nvExceptions
.BadRequest
, ConnectionError
) as e
:
834 self
._format
_exception
(e
)
836 def delete_vminstance(self
, vm_id
):
837 '''Removes a VM instance from VIM. Returns the old identifier
839 #print "osconnector: Getting VM from VIM"
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']:
846 self
.neutron
.delete_port(p
["id"])
847 except Exception as e
:
848 self
.logger
.error("Error deleting port: " + type(e
).__name
__ + ": "+ str(e
))
849 self
.nova
.servers
.delete(vm_id
)
851 except (nvExceptions
.NotFound
, ksExceptions
.ClientException
, nvExceptions
.ClientException
, ConnectionError
) as e
:
852 self
._format
_exception
(e
)
853 #TODO insert exception vimconn.HTTP_Unauthorized
854 #if reaching here is because an exception
856 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
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)
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
880 self
.logger
.debug("refresh_vms status: Getting tenant VM instance information from VIM")
881 for vm_id
in vm_list
:
884 vm_vim
= self
.get_vminstance(vm_id
)
885 if vm_vim
['status'] in vmStatus2manoFormat
:
886 vm
['status'] = vmStatus2manoFormat
[ vm_vim
['status'] ]
888 vm
['status'] = "OTHER"
889 vm
['error_msg'] = "VIM status reported " + vm_vim
['status']
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
)
894 vm
["interfaces"] = []
895 if vm_vim
.get('fault'):
896 vm
['error_msg'] = str(vm_vim
['fault'])
899 self
._reload
_connection
()
900 port_dict
=self
.neutron
.list_ports(device_id
=vm_id
)
901 for port
in port_dict
["ports"]:
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
)
907 interface
["mac_address"] = port
.get("mac_address")
908 interface
["vim_net_id"] = port
["network_id"]
909 interface
["vim_interface_id"] = port
["id"]
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") )
916 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
)
933 def action_vminstance(self
, vm_id
, action_dict
):
934 '''Send and action over a VM instance from VIM
935 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
))
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":
944 if server
.status
=="PAUSED":
946 elif server
.status
=="SUSPENDED":
948 elif server
.status
=="SHUTOFF":
950 elif "pause" in action_dict
:
952 elif "resume" in action_dict
:
954 elif "shutoff" in action_dict
or "shutdown" in action_dict
:
956 elif "forceOff" in action_dict
:
958 elif "terminate" in action_dict
:
960 elif "createImage" in action_dict
:
961 server
.create_image()
963 #"description":description_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
)
983 raise vimconn
.vimconnException("console type '{}' not allowed".format(console_type
),
984 http_code
=vimconn
.HTTP_Bad_Request
)
986 console_url
= console_dict
["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:
992 raise vimconn
.vimconnException("Unexpected response from VIM " + str(console_dict
))
993 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:]
999 except Exception as e
:
1000 raise vimconn
.vimconnException("Unexpected response from VIM " + str(console_dict
))
1003 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
, nvExceptions
.NotFound
, ConnectionError
) as e
:
1004 self
._format
_exception
(e
)
1005 #TODO insert exception vimconn.HTTP_Unauthorized
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"
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"
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")
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)
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
1034 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
1039 self
.logger
.debug("new_user " + error_text
)
1040 return error_value
, error_text
1042 def delete_user(self
, user_id
):
1043 '''Delete a user from openstack VIM'''
1044 '''Returns the user identifier'''
1046 print "osconnector: Deleting a user from VIM"
1048 self
._reload
_connection
()
1049 self
.keystone
.users
.delete(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
1063 print "delete_tenant " + error_text
1064 return error_value
, error_text
1066 def get_hosts_info(self
):
1067 '''Get the information of deployed hosts
1068 Returns the hosts content'''
1070 print "osconnector: Getting Host info from VIM"
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
1087 print "get_hosts_info " + error_text
1088 return error_value
, error_text
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()
1096 hypervisors
= hype_dict
["hosts"]
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']:
1103 hype
['vm'].append(server
.id)
1105 hype
['vm'] = [server
.id]
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
1116 print "get_hosts " + error_text
1117 return error_value
, error_text