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, Pablo Montes, xFlow Research"
28 __date__
="$22-jun-2014 11:19:29$"
38 from novaclient
import client
as nClient_v2
, exceptions
as nvExceptions
39 from novaclient
import api_versions
40 import keystoneclient
.v2_0
.client
as ksClient_v2
41 from novaclient
.v2
.client
import Client
as nClient
42 import keystoneclient
.v3
.client
as ksClient
43 import keystoneclient
.exceptions
as ksExceptions
44 import glanceclient
.v2
.client
as glClient
45 import glanceclient
.client
as gl1Client
46 import glanceclient
.exc
as gl1Exceptions
47 import cinderclient
.v2
.client
as cClient_v2
48 from httplib
import HTTPException
49 from neutronclient
.neutron
import client
as neClient_v2
50 from neutronclient
.v2_0
import client
as neClient
51 from neutronclient
.common
import exceptions
as neExceptions
52 from requests
.exceptions
import ConnectionError
54 '''contain the openstack virtual machine status to openmano status'''
55 vmStatus2manoFormat
={'ACTIVE':'ACTIVE',
57 'SUSPENDED': 'SUSPENDED',
60 'ERROR':'ERROR','DELETED':'DELETED'
62 netStatus2manoFormat
={'ACTIVE':'ACTIVE','PAUSED':'PAUSED','INACTIVE':'INACTIVE','BUILD':'BUILD','ERROR':'ERROR','DELETED':'DELETED'
65 #global var to have a timeout creating and deleting volumes
69 class vimconnector(vimconn
.vimconnector
):
70 def __init__(self
, uuid
, name
, tenant_id
, tenant_name
, url
, url_admin
=None, user
=None, passwd
=None, log_level
=None, config
={}):
71 '''using common constructor parameters. In this case
72 'url' is the keystone authorization url,
73 'url_admin' is not use
75 self
.osc_api_version
= 'v2.0'
76 if config
.get('APIversion') == 'v3.3':
77 self
.osc_api_version
= 'v3.3'
78 vimconn
.vimconnector
.__init
__(self
, uuid
, name
, tenant_id
, tenant_name
, url
, url_admin
, user
, passwd
, log_level
, config
)
83 raise TypeError, 'url param can not be NoneType'
84 self
.k_creds
['auth_url'] = url
85 self
.n_creds
['auth_url'] = url
87 self
.k_creds
['tenant_name'] = tenant_name
88 self
.n_creds
['project_id'] = tenant_name
90 self
.k_creds
['tenant_id'] = tenant_id
91 self
.n_creds
['tenant_id'] = tenant_id
93 self
.k_creds
['username'] = user
94 self
.n_creds
['username'] = user
96 self
.k_creds
['password'] = passwd
97 self
.n_creds
['api_key'] = passwd
98 if self
.osc_api_version
== 'v3.3':
99 self
.k_creds
['project_name'] = tenant_name
100 self
.k_creds
['project_id'] = tenant_id
101 if config
.get('region_name'):
102 self
.k_creds
['region_name'] = config
.get('region_name')
103 self
.n_creds
['region_name'] = config
.get('region_name')
105 self
.reload_client
= True
106 self
.logger
= logging
.getLogger('openmano.vim.openstack')
108 self
.logger
.setLevel( getattr(logging
, log_level
) )
110 def __setitem__(self
,index
, value
):
111 '''Set individuals parameters
112 Throw TypeError, KeyError
114 if index
=='tenant_id':
115 self
.reload_client
=True
116 self
.tenant_id
= value
117 if self
.osc_api_version
== 'v3.3':
119 self
.k_creds
['project_id'] = value
120 self
.n_creds
['project_id'] = value
122 del self
.k_creds
['project_id']
123 del self
.n_creds
['project_id']
126 self
.k_creds
['tenant_id'] = value
127 self
.n_creds
['tenant_id'] = value
129 del self
.k_creds
['tenant_id']
130 del self
.n_creds
['tenant_id']
131 elif index
=='tenant_name':
132 self
.reload_client
=True
133 self
.tenant_name
= value
134 if self
.osc_api_version
== 'v3.3':
136 self
.k_creds
['project_name'] = value
137 self
.n_creds
['project_name'] = value
139 del self
.k_creds
['project_name']
140 del self
.n_creds
['project_name']
143 self
.k_creds
['tenant_name'] = value
144 self
.n_creds
['project_id'] = value
146 del self
.k_creds
['tenant_name']
147 del self
.n_creds
['project_id']
149 self
.reload_client
=True
152 self
.k_creds
['username'] = value
153 self
.n_creds
['username'] = value
155 del self
.k_creds
['username']
156 del self
.n_creds
['username']
157 elif index
=='passwd':
158 self
.reload_client
=True
161 self
.k_creds
['password'] = value
162 self
.n_creds
['api_key'] = value
164 del self
.k_creds
['password']
165 del self
.n_creds
['api_key']
167 self
.reload_client
=True
170 self
.k_creds
['auth_url'] = value
171 self
.n_creds
['auth_url'] = value
173 raise TypeError, 'url param can not be NoneType'
175 vimconn
.vimconnector
.__setitem
__(self
,index
, value
)
177 def _reload_connection(self
):
178 '''Called before any operation, it check if credentials has changed
179 Throw keystoneclient.apiclient.exceptions.AuthorizationFailure
181 #TODO control the timing and possible token timeout, but it seams that python client does this task for us :-)
182 if self
.reload_client
:
184 if len(self
.n_creds
) <4:
185 raise ksExceptions
.ClientException("Not enough parameters to connect to openstack")
186 if self
.osc_api_version
== 'v3.3':
187 self
.nova
= nClient(api_version
=api_versions
.APIVersion(version_str
='2.0'), **self
.n_creds
)
188 #TODO To be updated for v3
189 #self.cinder = cClient.Client(**self.n_creds)
190 self
.keystone
= ksClient
.Client(**self
.k_creds
)
191 self
.ne_endpoint
=self
.keystone
.service_catalog
.url_for(service_type
='network', endpoint_type
='publicURL')
192 self
.neutron
= neClient
.Client(api_version
=api_versions
.APIVersion(version_str
='2.0'), endpoint_url
=self
.ne_endpoint
, token
=self
.keystone
.auth_token
, **self
.k_creds
)
194 self
.nova
= nClient_v2
.Client(version
='2', **self
.n_creds
)
195 self
.cinder
= cClient_v2
.Client(**self
.n_creds
)
196 self
.keystone
= ksClient_v2
.Client(**self
.k_creds
)
197 self
.ne_endpoint
=self
.keystone
.service_catalog
.url_for(service_type
='network', endpoint_type
='publicURL')
198 self
.neutron
= neClient_v2
.Client('2.0', endpoint_url
=self
.ne_endpoint
, token
=self
.keystone
.auth_token
, **self
.k_creds
)
199 self
.glance_endpoint
= self
.keystone
.service_catalog
.url_for(service_type
='image', endpoint_type
='publicURL')
200 self
.glance
= glClient
.Client(self
.glance_endpoint
, token
=self
.keystone
.auth_token
, **self
.k_creds
) #TODO check k_creds vs n_creds
201 self
.reload_client
= False
203 def __net_os2mano(self
, net_list_dict
):
204 '''Transform the net openstack format to mano format
205 net_list_dict can be a list of dict or a single dict'''
206 if type(net_list_dict
) is dict:
207 net_list_
=(net_list_dict
,)
208 elif type(net_list_dict
) is list:
209 net_list_
=net_list_dict
211 raise TypeError("param net_list_dict must be a list or a dictionary")
212 for net
in net_list_
:
213 if net
.get('provider:network_type') == "vlan":
220 def _format_exception(self
, exception
):
221 '''Transform a keystone, nova, neutron exception into a vimconn exception'''
222 if isinstance(exception
, (HTTPException
, gl1Exceptions
.HTTPException
, gl1Exceptions
.CommunicationError
,
223 ConnectionError
, ksExceptions
.ConnectionError
, neExceptions
.ConnectionFailed
225 raise vimconn
.vimconnConnectionException(type(exception
).__name
__ + ": " + str(exception
))
226 elif isinstance(exception
, (nvExceptions
.ClientException
, ksExceptions
.ClientException
,
227 neExceptions
.NeutronException
, nvExceptions
.BadRequest
)):
228 raise vimconn
.vimconnUnexpectedResponse(type(exception
).__name
__ + ": " + str(exception
))
229 elif isinstance(exception
, (neExceptions
.NetworkNotFoundClient
, nvExceptions
.NotFound
)):
230 raise vimconn
.vimconnNotFoundException(type(exception
).__name
__ + ": " + str(exception
))
231 elif isinstance(exception
, nvExceptions
.Conflict
):
232 raise vimconn
.vimconnConflictException(type(exception
).__name
__ + ": " + str(exception
))
234 raise vimconn
.vimconnConnectionException(type(exception
).__name
__ + ": " + str(exception
))
236 def get_tenant_list(self
, filter_dict
={}):
237 '''Obtain tenants of VIM
238 filter_dict can contain the following keys:
239 name: filter by tenant name
240 id: filter by tenant uuid/id
242 Returns the tenant list of dictionaries: [{'name':'<name>, 'id':'<id>, ...}, ...]
244 self
.logger
.debug("Getting tenants from VIM filter: '%s'", str(filter_dict
))
246 self
._reload
_connection
()
247 if self
.osc_api_version
== 'v3.3':
248 project_class_list
=self
.keystone
.projects
.findall(**filter_dict
)
250 project_class_list
=self
.keystone
.tenants
.findall(**filter_dict
)
252 for project
in project_class_list
:
253 project_list
.append(project
.to_dict())
255 except (ksExceptions
.ConnectionError
, ksExceptions
.ClientException
, ConnectionError
) as e
:
256 self
._format
_exception
(e
)
258 def new_tenant(self
, tenant_name
, tenant_description
):
259 '''Adds a new tenant to openstack VIM. Returns the tenant identifier'''
260 self
.logger
.debug("Adding a new tenant name: %s", tenant_name
)
262 self
._reload
_connection
()
263 if self
.osc_api_version
== 'v3.3':
264 project
=self
.keystone
.projects
.create(tenant_name
, tenant_description
)
266 project
=self
.keystone
.tenants
.create(tenant_name
, tenant_description
)
268 except (ksExceptions
.ConnectionError
, ksExceptions
.ClientException
, ConnectionError
) as e
:
269 self
._format
_exception
(e
)
271 def delete_tenant(self
, tenant_id
):
272 '''Delete a tenant from openstack VIM. Returns the old tenant identifier'''
273 self
.logger
.debug("Deleting tenant %s from VIM", tenant_id
)
275 self
._reload
_connection
()
276 if self
.osc_api_version
== 'v3.3':
277 self
.keystone
.projects
.delete(tenant_id
)
279 self
.keystone
.tenants
.delete(tenant_id
)
281 except (ksExceptions
.ConnectionError
, ksExceptions
.ClientException
, ConnectionError
) as e
:
282 self
._format
_exception
(e
)
284 def new_network(self
,net_name
, net_type
, ip_profile
=None, shared
=False, vlan
=None):
285 '''Adds a tenant network to VIM. Returns the network identifier'''
286 self
.logger
.debug("Adding a new network to VIM name '%s', type '%s'", net_name
, net_type
)
287 #self.logger.debug(">>>>>>>>>>>>>>>>>> IP profile %s", str(ip_profile))
290 self
._reload
_connection
()
291 network_dict
= {'name': net_name
, 'admin_state_up': True}
292 if net_type
=="data" or net_type
=="ptp":
293 if self
.config
.get('dataplane_physical_net') == None:
294 raise vimconn
.vimconnConflictException("You must provide a 'dataplane_physical_net' at config value before creating sriov network")
295 network_dict
["provider:physical_network"] = self
.config
['dataplane_physical_net'] #"physnet_sriov" #TODO physical
296 network_dict
["provider:network_type"] = "vlan"
298 network_dict
["provider:network_type"] = vlan
299 network_dict
["shared"]=shared
300 new_net
=self
.neutron
.create_network({'network':network_dict
})
302 #create subnetwork, even if there is no profile
305 if 'subnet_address' not in ip_profile
:
306 #Fake subnet is required
307 ip_profile
['subnet_address'] = "192.168.111.0/24"
308 if 'ip_version' not in ip_profile
:
309 ip_profile
['ip_version'] = "IPv4"
310 subnet
={"name":net_name
+"-subnet",
311 "network_id": new_net
["network"]["id"],
312 "ip_version": 4 if ip_profile
['ip_version']=="IPv4" else 6,
313 "cidr": ip_profile
['subnet_address']
315 if 'gateway_address' in ip_profile
:
316 subnet
['gateway_ip'] = ip_profile
['gateway_address']
317 if ip_profile
.get('dns_address'):
318 #TODO: manage dns_address as a list of addresses separated by commas
319 subnet
['dns_nameservers'] = []
320 subnet
['dns_nameservers'].append(ip_profile
['dns_address'])
321 if 'dhcp_enabled' in ip_profile
:
322 subnet
['enable_dhcp'] = False if ip_profile
['dhcp_enabled']=="false" else True
323 if 'dhcp_start_address' in ip_profile
:
324 subnet
['allocation_pools']=[]
325 subnet
['allocation_pools'].append(dict())
326 subnet
['allocation_pools'][0]['start'] = ip_profile
['dhcp_start_address']
327 if 'dhcp_count' in ip_profile
:
328 #parts = ip_profile['dhcp_start_address'].split('.')
329 #ip_int = (int(parts[0]) << 24) + (int(parts[1]) << 16) + (int(parts[2]) << 8) + int(parts[3])
330 ip_int
= int(netaddr
.IPAddress(ip_profile
['dhcp_start_address']))
331 ip_int
+= ip_profile
['dhcp_count'] - 1
332 ip_str
= str(netaddr
.IPAddress(ip_int
))
333 subnet
['allocation_pools'][0]['end'] = ip_str
334 #self.logger.debug(">>>>>>>>>>>>>>>>>> Subnet: %s", str(subnet))
335 self
.neutron
.create_subnet({"subnet": subnet
} )
336 return new_net
["network"]["id"]
337 except (neExceptions
.ConnectionFailed
, ksExceptions
.ClientException
, neExceptions
.NeutronException
, ConnectionError
) as e
:
339 self
.neutron
.delete_network(new_net
['network']['id'])
340 self
._format
_exception
(e
)
342 def get_network_list(self
, filter_dict
={}):
343 '''Obtain tenant networks of VIM
349 admin_state_up: boolean
351 Returns the network list of dictionaries
353 self
.logger
.debug("Getting network from VIM filter: '%s'", str(filter_dict
))
355 self
._reload
_connection
()
356 if self
.osc_api_version
== 'v3.3' and "tenant_id" in filter_dict
:
357 filter_dict
['project_id'] = filter_dict
.pop('tenant_id')
358 net_dict
=self
.neutron
.list_networks(**filter_dict
)
359 net_list
=net_dict
["networks"]
360 self
.__net
_os
2mano
(net_list
)
362 except (neExceptions
.ConnectionFailed
, ksExceptions
.ClientException
, neExceptions
.NeutronException
, ConnectionError
) as e
:
363 self
._format
_exception
(e
)
365 def get_network(self
, net_id
):
366 '''Obtain details of network from VIM
367 Returns the network information from a network id'''
368 self
.logger
.debug(" Getting tenant network %s from VIM", net_id
)
369 filter_dict
={"id": net_id
}
370 net_list
= self
.get_network_list(filter_dict
)
372 raise vimconn
.vimconnNotFoundException("Network '{}' not found".format(net_id
))
373 elif len(net_list
)>1:
374 raise vimconn
.vimconnConflictException("Found more than one network with this criteria")
377 for subnet_id
in net
.get("subnets", () ):
379 subnet
= self
.neutron
.show_subnet(subnet_id
)
380 except Exception as e
:
381 self
.logger
.error("osconnector.get_network(): Error getting subnet %s %s" % (net_id
, str(e
)))
382 subnet
= {"id": subnet_id
, "fault": str(e
)}
383 subnets
.append(subnet
)
384 net
["subnets"] = subnets
387 def delete_network(self
, net_id
):
388 '''Deletes a tenant network from VIM. Returns the old network identifier'''
389 self
.logger
.debug("Deleting network '%s' from VIM", net_id
)
391 self
._reload
_connection
()
392 #delete VM ports attached to this networks before the network
393 ports
= self
.neutron
.list_ports(network_id
=net_id
)
394 for p
in ports
['ports']:
396 self
.neutron
.delete_port(p
["id"])
397 except Exception as e
:
398 self
.logger
.error("Error deleting port %s: %s", p
["id"], str(e
))
399 self
.neutron
.delete_network(net_id
)
401 except (neExceptions
.ConnectionFailed
, neExceptions
.NetworkNotFoundClient
, neExceptions
.NeutronException
,
402 ksExceptions
.ClientException
, neExceptions
.NeutronException
, ConnectionError
) as e
:
403 self
._format
_exception
(e
)
405 def refresh_nets_status(self
, net_list
):
406 '''Get the status of the networks
407 Params: the list of network identifiers
408 Returns a dictionary with:
409 net_id: #VIM id of this network
410 status: #Mandatory. Text with one of:
411 # DELETED (not found at vim)
412 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
413 # OTHER (Vim reported other status not understood)
414 # ERROR (VIM indicates an ERROR status)
415 # ACTIVE, INACTIVE, DOWN (admin down),
416 # BUILD (on building process)
418 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
419 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
423 for net_id
in net_list
:
426 net_vim
= self
.get_network(net_id
)
427 if net_vim
['status'] in netStatus2manoFormat
:
428 net
["status"] = netStatus2manoFormat
[ net_vim
['status'] ]
430 net
["status"] = "OTHER"
431 net
["error_msg"] = "VIM status reported " + net_vim
['status']
433 if net
['status'] == "ACTIVE" and not net_vim
['admin_state_up']:
434 net
['status'] = 'DOWN'
436 net
['vim_info'] = yaml
.safe_dump(net_vim
, default_flow_style
=True, width
=256)
437 except yaml
.representer
.RepresenterError
:
438 net
['vim_info'] = str(net_vim
)
439 if net_vim
.get('fault'): #TODO
440 net
['error_msg'] = str(net_vim
['fault'])
441 except vimconn
.vimconnNotFoundException
as e
:
442 self
.logger
.error("Exception getting net status: %s", str(e
))
443 net
['status'] = "DELETED"
444 net
['error_msg'] = str(e
)
445 except vimconn
.vimconnException
as e
:
446 self
.logger
.error("Exception getting net status: %s", str(e
))
447 net
['status'] = "VIM_ERROR"
448 net
['error_msg'] = str(e
)
449 net_dict
[net_id
] = net
452 def get_flavor(self
, flavor_id
):
453 '''Obtain flavor details from the VIM. Returns the flavor dict details'''
454 self
.logger
.debug("Getting flavor '%s'", flavor_id
)
456 self
._reload
_connection
()
457 flavor
= self
.nova
.flavors
.find(id=flavor_id
)
458 #TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
459 return flavor
.to_dict()
460 except (nvExceptions
.NotFound
, nvExceptions
.ClientException
, ksExceptions
.ClientException
, ConnectionError
) as e
:
461 self
._format
_exception
(e
)
463 def new_flavor(self
, flavor_data
, change_name_if_used
=True):
464 '''Adds a tenant flavor to openstack VIM
465 if change_name_if_used is True, it will change name in case of conflict, because it is not supported name repetition
466 Returns the flavor identifier
468 self
.logger
.debug("Adding flavor '%s'", str(flavor_data
))
472 name
=flavor_data
['name']
473 while retry
<max_retries
:
476 self
._reload
_connection
()
477 if change_name_if_used
:
480 fl
=self
.nova
.flavors
.list()
482 fl_names
.append(f
.name
)
483 while name
in fl_names
:
485 name
= flavor_data
['name']+"-" + str(name_suffix
)
487 ram
= flavor_data
.get('ram',64)
488 vcpus
= flavor_data
.get('vcpus',1)
491 extended
= flavor_data
.get("extended")
493 numas
=extended
.get("numas")
495 numa_nodes
= len(numas
)
497 return -1, "Can not add flavor with more than one numa"
498 numa_properties
= {"hw:numa_nodes":str(numa_nodes
)}
499 numa_properties
["hw:mem_page_size"] = "large"
500 numa_properties
["hw:cpu_policy"] = "dedicated"
501 numa_properties
["hw:numa_mempolicy"] = "strict"
503 #overwrite ram and vcpus
504 ram
= numa
['memory']*1024
505 if 'paired-threads' in numa
:
506 vcpus
= numa
['paired-threads']*2
507 numa_properties
["hw:cpu_threads_policy"] = "prefer"
508 elif 'cores' in numa
:
509 vcpus
= numa
['cores']
510 #numa_properties["hw:cpu_threads_policy"] = "prefer"
511 elif 'threads' in numa
:
512 vcpus
= numa
['threads']
513 numa_properties
["hw:cpu_policy"] = "isolated"
514 for interface
in numa
.get("interfaces",() ):
515 if interface
["dedicated"]=="yes":
516 raise vimconn
.vimconnException("Passthrough interfaces are not supported for the openstack connector", http_code
=vimconn
.HTTP_Service_Unavailable
)
517 #TODO, add the key 'pci_passthrough:alias"="<label at config>:<number ifaces>"' when a way to connect it is available
520 new_flavor
=self
.nova
.flavors
.create(name
,
523 flavor_data
.get('disk',1),
524 is_public
=flavor_data
.get('is_public', True)
528 new_flavor
.set_keys(numa_properties
)
530 except nvExceptions
.Conflict
as e
:
531 if change_name_if_used
and retry
< max_retries
:
533 self
._format
_exception
(e
)
534 #except nvExceptions.BadRequest as e:
535 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
, ConnectionError
) as e
:
536 self
._format
_exception
(e
)
538 def delete_flavor(self
,flavor_id
):
539 '''Deletes a tenant flavor from openstack VIM. Returns the old flavor_id
542 self
._reload
_connection
()
543 self
.nova
.flavors
.delete(flavor_id
)
545 #except nvExceptions.BadRequest as e:
546 except (nvExceptions
.NotFound
, ksExceptions
.ClientException
, nvExceptions
.ClientException
, ConnectionError
) as e
:
547 self
._format
_exception
(e
)
549 def new_image(self
,image_dict
):
551 Adds a tenant image to VIM. imge_dict is a dictionary with:
553 disk_format: qcow2, vhd, vmdk, raw (by default), ...
554 location: path or URI
555 public: "yes" or "no"
556 metadata: metadata of the image
559 #using version 1 of glance client
560 glancev1
= gl1Client
.Client('1',self
.glance_endpoint
, token
=self
.keystone
.auth_token
, **self
.k_creds
) #TODO check k_creds vs n_creds
563 while retry
<max_retries
:
566 self
._reload
_connection
()
567 #determine format http://docs.openstack.org/developer/glance/formats.html
568 if "disk_format" in image_dict
:
569 disk_format
=image_dict
["disk_format"]
570 else: #autodiscover based on extension
571 if image_dict
['location'][-6:]==".qcow2":
573 elif image_dict
['location'][-4:]==".vhd":
575 elif image_dict
['location'][-5:]==".vmdk":
577 elif image_dict
['location'][-4:]==".vdi":
579 elif image_dict
['location'][-4:]==".iso":
581 elif image_dict
['location'][-4:]==".aki":
583 elif image_dict
['location'][-4:]==".ari":
585 elif image_dict
['location'][-4:]==".ami":
589 self
.logger
.debug("new_image: '%s' loading from '%s'", image_dict
['name'], image_dict
['location'])
590 if image_dict
['location'][0:4]=="http":
591 new_image
= glancev1
.images
.create(name
=image_dict
['name'], is_public
=image_dict
.get('public',"yes")=="yes",
592 container_format
="bare", location
=image_dict
['location'], disk_format
=disk_format
)
594 with
open(image_dict
['location']) as fimage
:
595 new_image
= glancev1
.images
.create(name
=image_dict
['name'], is_public
=image_dict
.get('public',"yes")=="yes",
596 container_format
="bare", data
=fimage
, disk_format
=disk_format
)
597 #insert metadata. We cannot use 'new_image.properties.setdefault'
598 #because nova and glance are "INDEPENDENT" and we are using nova for reading metadata
599 new_image_nova
=self
.nova
.images
.find(id=new_image
.id)
600 new_image_nova
.metadata
.setdefault('location',image_dict
['location'])
601 metadata_to_load
= image_dict
.get('metadata')
603 for k
,v
in yaml
.load(metadata_to_load
).iteritems():
604 new_image_nova
.metadata
.setdefault(k
,v
)
606 except (nvExceptions
.Conflict
, ksExceptions
.ClientException
, nvExceptions
.ClientException
) as e
:
607 self
._format
_exception
(e
)
608 except (HTTPException
, gl1Exceptions
.HTTPException
, gl1Exceptions
.CommunicationError
, ConnectionError
) as e
:
609 if retry
==max_retries
:
611 self
._format
_exception
(e
)
612 except IOError as e
: #can not open the file
613 raise vimconn
.vimconnConnectionException(type(e
).__name
__ + ": " + str(e
)+ " for " + image_dict
['location'],
614 http_code
=vimconn
.HTTP_Bad_Request
)
616 def delete_image(self
, image_id
):
617 '''Deletes a tenant image from openstack VIM. Returns the old id
620 self
._reload
_connection
()
621 self
.nova
.images
.delete(image_id
)
623 except (nvExceptions
.NotFound
, ksExceptions
.ClientException
, nvExceptions
.ClientException
, gl1Exceptions
.CommunicationError
, ConnectionError
) as e
: #TODO remove
624 self
._format
_exception
(e
)
626 def get_image_id_from_path(self
, path
):
627 '''Get the image id from image path in the VIM database. Returns the image_id'''
629 self
._reload
_connection
()
630 images
= self
.nova
.images
.list()
632 if image
.metadata
.get("location")==path
:
634 raise vimconn
.vimconnNotFoundException("image with location '{}' not found".format( path
))
635 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
, gl1Exceptions
.CommunicationError
, ConnectionError
) as e
:
636 self
._format
_exception
(e
)
638 def get_image_list(self
, filter_dict
={}):
639 '''Obtain tenant images from VIM
643 checksum: image checksum
644 Returns the image list of dictionaries:
645 [{<the fields at Filter_dict plus some VIM specific>}, ...]
648 self
.logger
.debug("Getting image list from VIM filter: '%s'", str(filter_dict
))
650 self
._reload
_connection
()
651 filter_dict_os
=filter_dict
.copy()
652 #First we filter by the available filter fields: name, id. The others are removed.
653 filter_dict_os
.pop('checksum',None)
654 image_list
=self
.nova
.images
.findall(**filter_dict_os
)
655 if len(image_list
)==0:
657 #Then we filter by the rest of filter fields: checksum
659 for image
in image_list
:
660 image_dict
=self
.glance
.images
.get(image
.id)
661 if 'checksum' not in filter_dict
or image_dict
['checksum']==filter_dict
.get('checksum'):
662 filtered_list
.append(image_dict
)
664 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
, gl1Exceptions
.CommunicationError
, ConnectionError
) as e
:
665 self
._format
_exception
(e
)
667 def new_vminstance(self
,name
,description
,start
,image_id
,flavor_id
,net_list
,cloud_config
=None,disk_list
=None):
668 '''Adds a VM instance to VIM
670 start: indicates if VM must start or boot in pause mode. Ignored
671 image_id,flavor_id: iamge and flavor uuid
672 net_list: list of interfaces, each one is a dictionary with:
674 net_id: network uuid to connect
675 vpci: virtual vcpi to assign, ignored because openstack lack #TODO
676 model: interface model, ignored #TODO
677 mac_address: used for SR-IOV ifaces #TODO for other types
678 use: 'data', 'bridge', 'mgmt'
679 type: 'virtual', 'PF', 'VF', 'VFnotShared'
680 vim_id: filled/added by this function
681 floating_ip: True/False (or it can be None)
682 #TODO ip, security groups
683 Returns the instance identifier
685 self
.logger
.debug("Creating VM image '%s' flavor '%s' nics='%s'",image_id
, flavor_id
,str(net_list
))
689 external_network
=[] #list of external networks to be connected to instance, later on used to create floating_ip
690 self
._reload
_connection
()
691 metadata_vpci
={} #For a specific neutron plugin
693 if not net
.get("net_id"): #skip non connected iface
695 if net
["type"]=="virtual" or net
["type"]=="VF":
697 "network_id": net
["net_id"],
698 "name": net
.get("name"),
699 "admin_state_up": True
701 if net
["type"]=="virtual":
703 metadata_vpci
[ net
["net_id"] ] = [[ net
["vpci"], "" ]]
706 if "VF" not in metadata_vpci
:
707 metadata_vpci
["VF"]=[]
708 metadata_vpci
["VF"].append([ net
["vpci"], "" ])
709 port_dict
["binding:vnic_type"]="direct"
710 if not port_dict
["name"]:
711 port_dict
["name"]=name
712 if net
.get("mac_address"):
713 port_dict
["mac_address"]=net
["mac_address"]
714 if net
.get("port_security") == False:
715 port_dict
["port_security_enabled"]=net
["port_security"]
716 new_port
= self
.neutron
.create_port({"port": port_dict
})
717 net
["mac_adress"] = new_port
["port"]["mac_address"]
718 net
["vim_id"] = new_port
["port"]["id"]
719 net
["ip"] = new_port
["port"].get("fixed_ips", [{}])[0].get("ip_address")
720 net_list_vim
.append({"port-id": new_port
["port"]["id"]})
722 self
.logger
.warn("new_vminstance: Warning, can not connect a passthrough interface ")
723 #TODO insert this when openstack consider passthrough ports as openstack neutron ports
724 if net
.get('floating_ip', False):
725 external_network
.append(net
)
728 metadata
= {"pci_assignement": json
.dumps(metadata_vpci
)}
729 if len(metadata
["pci_assignement"]) >255:
730 #limit the metadata size
731 #metadata["pci_assignement"] = metadata["pci_assignement"][0:255]
732 self
.logger
.warn("Metadata deleted since it exceeds the expected length (255) ")
735 self
.logger
.debug("name '%s' image_id '%s'flavor_id '%s' net_list_vim '%s' description '%s' metadata %s",
736 name
, image_id
, flavor_id
, str(net_list_vim
), description
, str(metadata
))
738 security_groups
= self
.config
.get('security_groups')
739 if type(security_groups
) is str:
740 security_groups
= ( security_groups
, )
744 if isinstance(cloud_config
, dict):
745 if cloud_config
.get("user-data"):
746 userdata
=cloud_config
["user-data"]
747 if cloud_config
.get("boot-data-drive") != None:
748 config_drive
= cloud_config
["boot-data-drive"]
749 if cloud_config
.get("config-files") or cloud_config
.get("users") or cloud_config
.get("key-pairs"):
751 raise vimconn
.vimconnConflictException("Cloud-config cannot contain both 'userdata' and 'config-files'/'users'/'key-pairs'")
754 if cloud_config
.get("key-pairs"):
755 userdata_dict
["ssh-authorized-keys"] = cloud_config
["key-pairs"]
756 userdata_dict
["users"] = [{"default": None, "ssh-authorized-keys": cloud_config
["key-pairs"] }]
757 if cloud_config
.get("users"):
758 if "users" not in cloud_config
:
759 userdata_dict
["users"] = [ "default" ]
760 for user
in cloud_config
["users"]:
762 "name" : user
["name"],
763 "sudo": "ALL = (ALL)NOPASSWD:ALL"
765 if "user-info" in user
:
766 user_info
["gecos"] = user
["user-info"]
767 if user
.get("key-pairs"):
768 user_info
["ssh-authorized-keys"] = user
["key-pairs"]
769 userdata_dict
["users"].append(user_info
)
771 if cloud_config
.get("config-files"):
772 userdata_dict
["write_files"] = []
773 for file in cloud_config
["config-files"]:
775 "path" : file["dest"],
776 "content": file["content"]
778 if file.get("encoding"):
779 file_info
["encoding"] = file["encoding"]
780 if file.get("permissions"):
781 file_info
["permissions"] = file["permissions"]
782 if file.get("owner"):
783 file_info
["owner"] = file["owner"]
784 userdata_dict
["write_files"].append(file_info
)
785 userdata
= "#cloud-config\n"
786 userdata
+= yaml
.safe_dump(userdata_dict
, indent
=4, default_flow_style
=False)
787 self
.logger
.debug("userdata: %s", userdata
)
788 elif isinstance(cloud_config
, str):
789 userdata
= cloud_config
791 #Create additional volumes in case these are present in disk_list
792 block_device_mapping
= None
793 base_disk_index
= ord('b')
794 if disk_list
!= None:
795 block_device_mapping
= dict()
796 for disk
in disk_list
:
797 if 'image_id' in disk
:
798 volume
= self
.cinder
.volumes
.create(size
= disk
['size'],name
= name
+ '_vd' +
799 chr(base_disk_index
), imageRef
= disk
['image_id'])
801 volume
= self
.cinder
.volumes
.create(size
=disk
['size'], name
=name
+ '_vd' +
802 chr(base_disk_index
))
803 block_device_mapping
['_vd' + chr(base_disk_index
)] = volume
.id
806 #wait until volumes are with status available
809 while keep_waiting
and elapsed_time
< volume_timeout
:
811 for volume_id
in block_device_mapping
.itervalues():
812 if self
.cinder
.volumes
.get(volume_id
).status
!= 'available':
818 #if we exceeded the timeout rollback
819 if elapsed_time
>= volume_timeout
:
820 #delete the volumes we just created
821 for volume_id
in block_device_mapping
.itervalues():
822 self
.cinder
.volumes
.delete(volume_id
)
824 #delete ports we just created
825 for net_item
in net_list_vim
:
826 if 'port-id' in net_item
:
827 self
.neutron
.delete_port(net_item
['port-id'])
829 raise vimconn
.vimconnException('Timeout creating volumes for instance ' + name
,
830 http_code
=vimconn
.HTTP_Request_Timeout
)
832 server
= self
.nova
.servers
.create(name
, image_id
, flavor_id
, nics
=net_list_vim
, meta
=metadata
,
833 security_groups
=security_groups
,
834 availability_zone
=self
.config
.get('availability_zone'),
835 key_name
=self
.config
.get('keypair'),
837 config_drive
= config_drive
,
838 block_device_mapping
= block_device_mapping
839 ) # , description=description)
840 #print "DONE :-)", server
842 floating_ips
= self
.neutron
.list_floatingips().get("floatingips", ())
843 for floating_network
in external_network
:
844 # wait until vm is active
846 while elapsed_time
< server_timeout
:
847 status
= self
.nova
.servers
.get(server
.id).status
848 if status
== 'ACTIVE':
853 #if we exceeded the timeout rollback
854 if elapsed_time
>= server_timeout
:
855 self
.delete_vminstance(server
.id)
856 raise vimconn
.vimconnException('Timeout creating instance ' + name
,
857 http_code
=vimconn
.HTTP_Request_Timeout
)
860 while(assigned
== False):
862 ip
= floating_ips
.pop(0)
863 if not ip
.get("port_id", False) and ip
.get('tenant_id') == server
.tenant_id
:
864 free_floating_ip
= ip
.get("floating_ip_address")
866 fix_ip
= floating_network
.get('ip')
867 server
.add_floating_ip(free_floating_ip
, fix_ip
)
869 except Exception as e
:
870 self
.delete_vminstance(server
.id)
871 raise vimconn
.vimconnException(type(e
).__name
__ + ": Cannot create floating_ip "+ str(e
), http_code
=vimconn
.HTTP_Conflict
)
873 #Find the external network
874 external_nets
= list()
875 for net
in self
.neutron
.list_networks()['networks']:
876 if net
['router:external']:
877 external_nets
.append(net
)
879 if len(external_nets
) == 0:
880 self
.delete_vminstance(server
.id)
881 raise vimconn
.vimconnException("Cannot create floating_ip automatically since no external "
882 "network is present",
883 http_code
=vimconn
.HTTP_Conflict
)
884 if len(external_nets
) > 1:
885 self
.delete_vminstance(server
.id)
886 raise vimconn
.vimconnException("Cannot create floating_ip automatically since multiple "
887 "external networks are present",
888 http_code
=vimconn
.HTTP_Conflict
)
890 pool_id
= external_nets
[0].get('id')
891 param
= {'floatingip': {'floating_network_id': pool_id
, 'tenant_id': server
.tenant_id
}}
893 #self.logger.debug("Creating floating IP")
894 new_floating_ip
= self
.neutron
.create_floatingip(param
)
895 free_floating_ip
= new_floating_ip
['floatingip']['floating_ip_address']
896 fix_ip
= floating_network
.get('ip')
897 server
.add_floating_ip(free_floating_ip
, fix_ip
)
899 except Exception as e
:
900 self
.delete_vminstance(server
.id)
901 raise vimconn
.vimconnException(type(e
).__name
__ + ": Cannot create floating_ip "+ str(e
), http_code
=vimconn
.HTTP_Conflict
)
904 # except nvExceptions.NotFound as e:
905 # error_value=-vimconn.HTTP_Not_Found
906 # error_text= "vm instance %s not found" % vm_id
907 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
, ConnectionError
909 # delete the volumes we just created
910 if block_device_mapping
!= None:
911 for volume_id
in block_device_mapping
.itervalues():
912 self
.cinder
.volumes
.delete(volume_id
)
914 # delete ports we just created
915 for net_item
in net_list_vim
:
916 if 'port-id' in net_item
:
917 self
.neutron
.delete_port(net_item
['port-id'])
918 self
._format
_exception
(e
)
919 except TypeError as e
:
920 raise vimconn
.vimconnException(type(e
).__name
__ + ": "+ str(e
), http_code
=vimconn
.HTTP_Bad_Request
)
922 def get_vminstance(self
,vm_id
):
923 '''Returns the VM instance information from VIM'''
924 #self.logger.debug("Getting VM from VIM")
926 self
._reload
_connection
()
927 server
= self
.nova
.servers
.find(id=vm_id
)
928 #TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
929 return server
.to_dict()
930 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
, nvExceptions
.NotFound
, ConnectionError
) as e
:
931 self
._format
_exception
(e
)
933 def get_vminstance_console(self
,vm_id
, console_type
="vnc"):
935 Get a console for the virtual machine
937 vm_id: uuid of the VM
938 console_type, can be:
939 "novnc" (by default), "xvpvnc" for VNC types,
940 "rdp-html5" for RDP types, "spice-html5" for SPICE types
941 Returns dict with the console parameters:
942 protocol: ssh, ftp, http, https, ...
943 server: usually ip address
944 port: the http, ssh, ... port
945 suffix: extra text, e.g. the http path and query string
947 self
.logger
.debug("Getting VM CONSOLE from VIM")
949 self
._reload
_connection
()
950 server
= self
.nova
.servers
.find(id=vm_id
)
951 if console_type
== None or console_type
== "novnc":
952 console_dict
= server
.get_vnc_console("novnc")
953 elif console_type
== "xvpvnc":
954 console_dict
= server
.get_vnc_console(console_type
)
955 elif console_type
== "rdp-html5":
956 console_dict
= server
.get_rdp_console(console_type
)
957 elif console_type
== "spice-html5":
958 console_dict
= server
.get_spice_console(console_type
)
960 raise vimconn
.vimconnException("console type '{}' not allowed".format(console_type
), http_code
=vimconn
.HTTP_Bad_Request
)
962 console_dict1
= console_dict
.get("console")
964 console_url
= console_dict1
.get("url")
967 protocol_index
= console_url
.find("//")
968 suffix_index
= console_url
[protocol_index
+2:].find("/") + protocol_index
+2
969 port_index
= console_url
[protocol_index
+2:suffix_index
].find(":") + protocol_index
+2
970 if protocol_index
< 0 or port_index
<0 or suffix_index
<0:
971 return -vimconn
.HTTP_Internal_Server_Error
, "Unexpected response from VIM"
972 console_dict
={"protocol": console_url
[0:protocol_index
],
973 "server": console_url
[protocol_index
+2:port_index
],
974 "port": console_url
[port_index
:suffix_index
],
975 "suffix": console_url
[suffix_index
+1:]
979 raise vimconn
.vimconnUnexpectedResponse("Unexpected response from VIM")
981 except (nvExceptions
.NotFound
, ksExceptions
.ClientException
, nvExceptions
.ClientException
, nvExceptions
.BadRequest
, ConnectionError
) as e
:
982 self
._format
_exception
(e
)
984 def delete_vminstance(self
, vm_id
):
985 '''Removes a VM instance from VIM. Returns the old identifier
987 #print "osconnector: Getting VM from VIM"
989 self
._reload
_connection
()
990 #delete VM ports attached to this networks before the virtual machine
991 ports
= self
.neutron
.list_ports(device_id
=vm_id
)
992 for p
in ports
['ports']:
994 self
.neutron
.delete_port(p
["id"])
995 except Exception as e
:
996 self
.logger
.error("Error deleting port: " + type(e
).__name
__ + ": "+ str(e
))
998 #commented because detaching the volumes makes the servers.delete not work properly ?!?
999 #dettach volumes attached
1000 server
= self
.nova
.servers
.get(vm_id
)
1001 volumes_attached_dict
= server
._info
['os-extended-volumes:volumes_attached']
1002 #for volume in volumes_attached_dict:
1003 # self.cinder.volumes.detach(volume['id'])
1005 self
.nova
.servers
.delete(vm_id
)
1008 #Although having detached them should have them in active status
1009 #we ensure in this loop
1012 while keep_waiting
and elapsed_time
< volume_timeout
:
1013 keep_waiting
= False
1014 for volume
in volumes_attached_dict
:
1015 if self
.cinder
.volumes
.get(volume
['id']).status
!= 'available':
1018 self
.cinder
.volumes
.delete(volume
['id'])
1024 except (nvExceptions
.NotFound
, ksExceptions
.ClientException
, nvExceptions
.ClientException
, ConnectionError
) as e
:
1025 self
._format
_exception
(e
)
1026 #TODO insert exception vimconn.HTTP_Unauthorized
1027 #if reaching here is because an exception
1029 def refresh_vms_status(self
, vm_list
):
1030 '''Get the status of the virtual machines and their interfaces/ports
1031 Params: the list of VM identifiers
1032 Returns a dictionary with:
1033 vm_id: #VIM id of this Virtual Machine
1034 status: #Mandatory. Text with one of:
1035 # DELETED (not found at vim)
1036 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
1037 # OTHER (Vim reported other status not understood)
1038 # ERROR (VIM indicates an ERROR status)
1039 # ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running),
1040 # CREATING (on building process), ERROR
1041 # ACTIVE:NoMgmtIP (Active but any of its interface has an IP address
1043 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
1044 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
1046 - vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
1047 mac_address: #Text format XX:XX:XX:XX:XX:XX
1048 vim_net_id: #network id where this interface is connected
1049 vim_interface_id: #interface/port VIM id
1050 ip_address: #null, or text with IPv4, IPv6 address
1053 self
.logger
.debug("refresh_vms status: Getting tenant VM instance information from VIM")
1054 for vm_id
in vm_list
:
1057 vm_vim
= self
.get_vminstance(vm_id
)
1058 if vm_vim
['status'] in vmStatus2manoFormat
:
1059 vm
['status'] = vmStatus2manoFormat
[ vm_vim
['status'] ]
1061 vm
['status'] = "OTHER"
1062 vm
['error_msg'] = "VIM status reported " + vm_vim
['status']
1064 vm
['vim_info'] = yaml
.safe_dump(vm_vim
, default_flow_style
=True, width
=256)
1065 except yaml
.representer
.RepresenterError
:
1066 vm
['vim_info'] = str(vm_vim
)
1067 vm
["interfaces"] = []
1068 if vm_vim
.get('fault'):
1069 vm
['error_msg'] = str(vm_vim
['fault'])
1072 self
._reload
_connection
()
1073 port_dict
=self
.neutron
.list_ports(device_id
=vm_id
)
1074 for port
in port_dict
["ports"]:
1077 interface
['vim_info'] = yaml
.safe_dump(port
, default_flow_style
=True, width
=256)
1078 except yaml
.representer
.RepresenterError
:
1079 interface
['vim_info'] = str(port
)
1080 interface
["mac_address"] = port
.get("mac_address")
1081 interface
["vim_net_id"] = port
["network_id"]
1082 interface
["vim_interface_id"] = port
["id"]
1084 #look for floating ip address
1085 floating_ip_dict
= self
.neutron
.list_floatingips(port_id
=port
["id"])
1086 if floating_ip_dict
.get("floatingips"):
1087 ips
.append(floating_ip_dict
["floatingips"][0].get("floating_ip_address") )
1089 for subnet
in port
["fixed_ips"]:
1090 ips
.append(subnet
["ip_address"])
1091 interface
["ip_address"] = ";".join(ips
)
1092 vm
["interfaces"].append(interface
)
1093 except Exception as e
:
1094 self
.logger
.error("Error getting vm interface information " + type(e
).__name
__ + ": "+ str(e
))
1095 except vimconn
.vimconnNotFoundException
as e
:
1096 self
.logger
.error("Exception getting vm status: %s", str(e
))
1097 vm
['status'] = "DELETED"
1098 vm
['error_msg'] = str(e
)
1099 except vimconn
.vimconnException
as e
:
1100 self
.logger
.error("Exception getting vm status: %s", str(e
))
1101 vm
['status'] = "VIM_ERROR"
1102 vm
['error_msg'] = str(e
)
1106 def action_vminstance(self
, vm_id
, action_dict
):
1107 '''Send and action over a VM instance from VIM
1108 Returns the vm_id if the action was successfully sent to the VIM'''
1109 self
.logger
.debug("Action over VM '%s': %s", vm_id
, str(action_dict
))
1111 self
._reload
_connection
()
1112 server
= self
.nova
.servers
.find(id=vm_id
)
1113 if "start" in action_dict
:
1114 if action_dict
["start"]=="rebuild":
1117 if server
.status
=="PAUSED":
1119 elif server
.status
=="SUSPENDED":
1121 elif server
.status
=="SHUTOFF":
1123 elif "pause" in action_dict
:
1125 elif "resume" in action_dict
:
1127 elif "shutoff" in action_dict
or "shutdown" in action_dict
:
1129 elif "forceOff" in action_dict
:
1131 elif "terminate" in action_dict
:
1133 elif "createImage" in action_dict
:
1134 server
.create_image()
1135 #"path":path_schema,
1136 #"description":description_schema,
1137 #"name":name_schema,
1138 #"metadata":metadata_schema,
1139 #"imageRef": id_schema,
1140 #"disk": {"oneOf":[{"type": "null"}, {"type":"string"}] },
1141 elif "rebuild" in action_dict
:
1142 server
.rebuild(server
.image
['id'])
1143 elif "reboot" in action_dict
:
1144 server
.reboot() #reboot_type='SOFT'
1145 elif "console" in action_dict
:
1146 console_type
= action_dict
["console"]
1147 if console_type
== None or console_type
== "novnc":
1148 console_dict
= server
.get_vnc_console("novnc")
1149 elif console_type
== "xvpvnc":
1150 console_dict
= server
.get_vnc_console(console_type
)
1151 elif console_type
== "rdp-html5":
1152 console_dict
= server
.get_rdp_console(console_type
)
1153 elif console_type
== "spice-html5":
1154 console_dict
= server
.get_spice_console(console_type
)
1156 raise vimconn
.vimconnException("console type '{}' not allowed".format(console_type
),
1157 http_code
=vimconn
.HTTP_Bad_Request
)
1159 console_url
= console_dict
["console"]["url"]
1161 protocol_index
= console_url
.find("//")
1162 suffix_index
= console_url
[protocol_index
+2:].find("/") + protocol_index
+2
1163 port_index
= console_url
[protocol_index
+2:suffix_index
].find(":") + protocol_index
+2
1164 if protocol_index
< 0 or port_index
<0 or suffix_index
<0:
1165 raise vimconn
.vimconnException("Unexpected response from VIM " + str(console_dict
))
1166 console_dict2
={"protocol": console_url
[0:protocol_index
],
1167 "server": console_url
[protocol_index
+2 : port_index
],
1168 "port": int(console_url
[port_index
+1 : suffix_index
]),
1169 "suffix": console_url
[suffix_index
+1:]
1171 return console_dict2
1172 except Exception as e
:
1173 raise vimconn
.vimconnException("Unexpected response from VIM " + str(console_dict
))
1176 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
, nvExceptions
.NotFound
, ConnectionError
) as e
:
1177 self
._format
_exception
(e
)
1178 #TODO insert exception vimconn.HTTP_Unauthorized
1182 def new_external_port(self
, port_data
):
1183 #TODO openstack if needed
1184 '''Adds a external port to VIM'''
1185 '''Returns the port identifier'''
1186 return -vimconn
.HTTP_Internal_Server_Error
, "osconnector.new_external_port() not implemented"
1188 def connect_port_network(self
, port_id
, network_id
, admin
=False):
1189 #TODO openstack if needed
1190 '''Connects a external port to a network'''
1191 '''Returns status code of the VIM response'''
1192 return -vimconn
.HTTP_Internal_Server_Error
, "osconnector.connect_port_network() not implemented"
1194 def new_user(self
, user_name
, user_passwd
, tenant_id
=None):
1195 '''Adds a new user to openstack VIM'''
1196 '''Returns the user identifier'''
1197 self
.logger
.debug("osconnector: Adding a new user to VIM")
1199 self
._reload
_connection
()
1200 user
=self
.keystone
.users
.create(user_name
, user_passwd
, tenant_id
=tenant_id
)
1201 #self.keystone.tenants.add_user(self.k_creds["username"], #role)
1203 except ksExceptions
.ConnectionError
as e
:
1204 error_value
=-vimconn
.HTTP_Bad_Request
1205 error_text
= type(e
).__name
__ + ": "+ (str(e
) if len(e
.args
)==0 else str(e
.args
[0]))
1206 except ksExceptions
.ClientException
as e
: #TODO remove
1207 error_value
=-vimconn
.HTTP_Bad_Request
1208 error_text
= type(e
).__name
__ + ": "+ (str(e
) if len(e
.args
)==0 else str(e
.args
[0]))
1209 #TODO insert exception vimconn.HTTP_Unauthorized
1210 #if reaching here is because an exception
1212 self
.logger
.debug("new_user " + error_text
)
1213 return error_value
, error_text
1215 def delete_user(self
, user_id
):
1216 '''Delete a user from openstack VIM'''
1217 '''Returns the user identifier'''
1219 print "osconnector: Deleting a user from VIM"
1221 self
._reload
_connection
()
1222 self
.keystone
.users
.delete(user_id
)
1224 except ksExceptions
.ConnectionError
as e
:
1225 error_value
=-vimconn
.HTTP_Bad_Request
1226 error_text
= type(e
).__name
__ + ": "+ (str(e
) if len(e
.args
)==0 else str(e
.args
[0]))
1227 except ksExceptions
.NotFound
as e
:
1228 error_value
=-vimconn
.HTTP_Not_Found
1229 error_text
= type(e
).__name
__ + ": "+ (str(e
) if len(e
.args
)==0 else str(e
.args
[0]))
1230 except ksExceptions
.ClientException
as e
: #TODO remove
1231 error_value
=-vimconn
.HTTP_Bad_Request
1232 error_text
= type(e
).__name
__ + ": "+ (str(e
) if len(e
.args
)==0 else str(e
.args
[0]))
1233 #TODO insert exception vimconn.HTTP_Unauthorized
1234 #if reaching here is because an exception
1236 print "delete_tenant " + error_text
1237 return error_value
, error_text
1239 def get_hosts_info(self
):
1240 '''Get the information of deployed hosts
1241 Returns the hosts content'''
1243 print "osconnector: Getting Host info from VIM"
1246 self
._reload
_connection
()
1247 hypervisors
= self
.nova
.hypervisors
.list()
1248 for hype
in hypervisors
:
1249 h_list
.append( hype
.to_dict() )
1250 return 1, {"hosts":h_list
}
1251 except nvExceptions
.NotFound
as e
:
1252 error_value
=-vimconn
.HTTP_Not_Found
1253 error_text
= (str(e
) if len(e
.args
)==0 else str(e
.args
[0]))
1254 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
) as e
:
1255 error_value
=-vimconn
.HTTP_Bad_Request
1256 error_text
= type(e
).__name
__ + ": "+ (str(e
) if len(e
.args
)==0 else str(e
.args
[0]))
1257 #TODO insert exception vimconn.HTTP_Unauthorized
1258 #if reaching here is because an exception
1260 print "get_hosts_info " + error_text
1261 return error_value
, error_text
1263 def get_hosts(self
, vim_tenant
):
1264 '''Get the hosts and deployed instances
1265 Returns the hosts content'''
1266 r
, hype_dict
= self
.get_hosts_info()
1269 hypervisors
= hype_dict
["hosts"]
1271 servers
= self
.nova
.servers
.list()
1272 for hype
in hypervisors
:
1273 for server
in servers
:
1274 if server
.to_dict()['OS-EXT-SRV-ATTR:hypervisor_hostname']==hype
['hypervisor_hostname']:
1276 hype
['vm'].append(server
.id)
1278 hype
['vm'] = [server
.id]
1280 except nvExceptions
.NotFound
as e
:
1281 error_value
=-vimconn
.HTTP_Not_Found
1282 error_text
= (str(e
) if len(e
.args
)==0 else str(e
.args
[0]))
1283 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
) as e
:
1284 error_value
=-vimconn
.HTTP_Bad_Request
1285 error_text
= type(e
).__name
__ + ": "+ (str(e
) if len(e
.args
)==0 else str(e
.args
[0]))
1286 #TODO insert exception vimconn.HTTP_Unauthorized
1287 #if reaching here is because an exception
1289 print "get_hosts " + error_text
1290 return error_value
, error_text