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
, api_versions
as APIVersion
39 import keystoneclient
.v2_0
.client
as ksClient_v2
40 from novaclient
.v2
.client
import Client
as nClient
41 import keystoneclient
.v3
.client
as ksClient
42 import keystoneclient
.exceptions
as ksExceptions
43 import glanceclient
.v2
.client
as glClient
44 import glanceclient
.client
as gl1Client
45 import glanceclient
.exc
as gl1Exceptions
46 import cinderclient
.v2
.client
as cClient_v2
47 from httplib
import HTTPException
48 from neutronclient
.neutron
import client
as neClient_v2
49 from neutronclient
.v2_0
import client
as neClient
50 from neutronclient
.common
import exceptions
as neExceptions
51 from requests
.exceptions
import ConnectionError
53 '''contain the openstack virtual machine status to openmano status'''
54 vmStatus2manoFormat
={'ACTIVE':'ACTIVE',
56 'SUSPENDED': 'SUSPENDED',
59 'ERROR':'ERROR','DELETED':'DELETED'
61 netStatus2manoFormat
={'ACTIVE':'ACTIVE','PAUSED':'PAUSED','INACTIVE':'INACTIVE','BUILD':'BUILD','ERROR':'ERROR','DELETED':'DELETED'
64 #global var to have a timeout creating and deleting volumes
68 class vimconnector(vimconn
.vimconnector
):
69 def __init__(self
, uuid
, name
, tenant_id
, tenant_name
, url
, url_admin
=None, user
=None, passwd
=None, log_level
=None, config
={}):
70 '''using common constructor parameters. In this case
71 'url' is the keystone authorization url,
72 'url_admin' is not use
74 self
.osc_api_version
= 'v2.0'
75 if config
.get('APIversion') == 'v3.3':
76 self
.osc_api_version
= 'v3.3'
77 vimconn
.vimconnector
.__init
__(self
, uuid
, name
, tenant_id
, tenant_name
, url
, url_admin
, user
, passwd
, log_level
, config
)
82 raise TypeError, 'url param can not be NoneType'
83 self
.k_creds
['auth_url'] = url
84 self
.n_creds
['auth_url'] = url
86 self
.k_creds
['tenant_name'] = tenant_name
87 self
.n_creds
['project_id'] = tenant_name
89 self
.k_creds
['tenant_id'] = tenant_id
90 self
.n_creds
['tenant_id'] = tenant_id
92 self
.k_creds
['username'] = user
93 self
.n_creds
['username'] = user
95 self
.k_creds
['password'] = passwd
96 self
.n_creds
['api_key'] = passwd
97 if self
.osc_api_version
== 'v3.3':
98 self
.k_creds
['project_name'] = tenant_name
99 self
.k_creds
['project_id'] = tenant_id
100 if config
.get('region_name'):
101 self
.k_creds
['region_name'] = config
.get('region_name')
102 self
.n_creds
['region_name'] = config
.get('region_name')
104 self
.reload_client
= True
105 self
.logger
= logging
.getLogger('openmano.vim.openstack')
107 self
.logger
.setLevel( getattr(logging
, log_level
) )
109 def __setitem__(self
,index
, value
):
110 '''Set individuals parameters
111 Throw TypeError, KeyError
113 if index
=='tenant_id':
114 self
.reload_client
=True
115 self
.tenant_id
= value
116 if self
.osc_api_version
== 'v3.3':
118 self
.k_creds
['project_id'] = value
119 self
.n_creds
['project_id'] = value
121 del self
.k_creds
['project_id']
122 del self
.n_creds
['project_id']
125 self
.k_creds
['tenant_id'] = value
126 self
.n_creds
['tenant_id'] = value
128 del self
.k_creds
['tenant_id']
129 del self
.n_creds
['tenant_id']
130 elif index
=='tenant_name':
131 self
.reload_client
=True
132 self
.tenant_name
= value
133 if self
.osc_api_version
== 'v3.3':
135 self
.k_creds
['project_name'] = value
136 self
.n_creds
['project_name'] = value
138 del self
.k_creds
['project_name']
139 del self
.n_creds
['project_name']
142 self
.k_creds
['tenant_name'] = value
143 self
.n_creds
['project_id'] = value
145 del self
.k_creds
['tenant_name']
146 del self
.n_creds
['project_id']
148 self
.reload_client
=True
151 self
.k_creds
['username'] = value
152 self
.n_creds
['username'] = value
154 del self
.k_creds
['username']
155 del self
.n_creds
['username']
156 elif index
=='passwd':
157 self
.reload_client
=True
160 self
.k_creds
['password'] = value
161 self
.n_creds
['api_key'] = value
163 del self
.k_creds
['password']
164 del self
.n_creds
['api_key']
166 self
.reload_client
=True
169 self
.k_creds
['auth_url'] = value
170 self
.n_creds
['auth_url'] = value
172 raise TypeError, 'url param can not be NoneType'
174 vimconn
.vimconnector
.__setitem
__(self
,index
, value
)
176 def _reload_connection(self
):
177 '''Called before any operation, it check if credentials has changed
178 Throw keystoneclient.apiclient.exceptions.AuthorizationFailure
180 #TODO control the timing and possible token timeout, but it seams that python client does this task for us :-)
181 if self
.reload_client
:
183 if len(self
.n_creds
) <4:
184 raise ksExceptions
.ClientException("Not enough parameters to connect to openstack")
185 if self
.osc_api_version
== 'v3.3':
186 self
.nova
= nClient(APIVersion(version_str
='2'), **self
.n_creds
)
187 #TODO To be updated for v3
188 #self.cinder = cClient.Client(**self.n_creds)
189 self
.keystone
= ksClient
.Client(**self
.k_creds
)
190 self
.ne_endpoint
=self
.keystone
.service_catalog
.url_for(service_type
='network', endpoint_type
='publicURL')
191 self
.neutron
= neClient
.Client(APIVersion(version_str
='2'), endpoint_url
=self
.ne_endpoint
, token
=self
.keystone
.auth_token
, **self
.k_creds
)
193 self
.nova
= nClient_v2
.Client('2', **self
.n_creds
)
194 self
.cinder
= cClient_v2
.Client(**self
.n_creds
)
195 self
.keystone
= ksClient_v2
.Client(**self
.k_creds
)
196 self
.ne_endpoint
=self
.keystone
.service_catalog
.url_for(service_type
='network', endpoint_type
='publicURL')
197 self
.neutron
= neClient_v2
.Client('2.0', endpoint_url
=self
.ne_endpoint
, token
=self
.keystone
.auth_token
, **self
.k_creds
)
198 self
.glance_endpoint
= self
.keystone
.service_catalog
.url_for(service_type
='image', endpoint_type
='publicURL')
199 self
.glance
= glClient
.Client(self
.glance_endpoint
, token
=self
.keystone
.auth_token
, **self
.k_creds
) #TODO check k_creds vs n_creds
200 self
.reload_client
= False
202 def __net_os2mano(self
, net_list_dict
):
203 '''Transform the net openstack format to mano format
204 net_list_dict can be a list of dict or a single dict'''
205 if type(net_list_dict
) is dict:
206 net_list_
=(net_list_dict
,)
207 elif type(net_list_dict
) is list:
208 net_list_
=net_list_dict
210 raise TypeError("param net_list_dict must be a list or a dictionary")
211 for net
in net_list_
:
212 if net
.get('provider:network_type') == "vlan":
219 def _format_exception(self
, exception
):
220 '''Transform a keystone, nova, neutron exception into a vimconn exception'''
221 if isinstance(exception
, (HTTPException
, gl1Exceptions
.HTTPException
, gl1Exceptions
.CommunicationError
,
222 ConnectionError
, ksExceptions
.ConnectionError
, neExceptions
.ConnectionFailed
224 raise vimconn
.vimconnConnectionException(type(exception
).__name
__ + ": " + str(exception
))
225 elif isinstance(exception
, (nvExceptions
.ClientException
, ksExceptions
.ClientException
,
226 neExceptions
.NeutronException
, nvExceptions
.BadRequest
)):
227 raise vimconn
.vimconnUnexpectedResponse(type(exception
).__name
__ + ": " + str(exception
))
228 elif isinstance(exception
, (neExceptions
.NetworkNotFoundClient
, nvExceptions
.NotFound
)):
229 raise vimconn
.vimconnNotFoundException(type(exception
).__name
__ + ": " + str(exception
))
230 elif isinstance(exception
, nvExceptions
.Conflict
):
231 raise vimconn
.vimconnConflictException(type(exception
).__name
__ + ": " + str(exception
))
233 raise vimconn
.vimconnConnectionException(type(exception
).__name
__ + ": " + str(exception
))
235 def get_tenant_list(self
, filter_dict
={}):
236 '''Obtain tenants of VIM
237 filter_dict can contain the following keys:
238 name: filter by tenant name
239 id: filter by tenant uuid/id
241 Returns the tenant list of dictionaries: [{'name':'<name>, 'id':'<id>, ...}, ...]
243 self
.logger
.debug("Getting tenants from VIM filter: '%s'", str(filter_dict
))
245 self
._reload
_connection
()
246 if self
.osc_api_version
== 'v3.3':
247 project_class_list
=self
.keystone
.projects
.findall(**filter_dict
)
249 project_class_list
=self
.keystone
.tenants
.findall(**filter_dict
)
251 for project
in project_class_list
:
252 project_list
.append(project
.to_dict())
254 except (ksExceptions
.ConnectionError
, ksExceptions
.ClientException
, ConnectionError
) as e
:
255 self
._format
_exception
(e
)
257 def new_tenant(self
, tenant_name
, tenant_description
):
258 '''Adds a new tenant to openstack VIM. Returns the tenant identifier'''
259 self
.logger
.debug("Adding a new tenant name: %s", tenant_name
)
261 self
._reload
_connection
()
262 if self
.osc_api_version
== 'v3.3':
263 project
=self
.keystone
.projects
.create(tenant_name
, tenant_description
)
265 project
=self
.keystone
.tenants
.create(tenant_name
, tenant_description
)
267 except (ksExceptions
.ConnectionError
, ksExceptions
.ClientException
, ConnectionError
) as e
:
268 self
._format
_exception
(e
)
270 def delete_tenant(self
, tenant_id
):
271 '''Delete a tenant from openstack VIM. Returns the old tenant identifier'''
272 self
.logger
.debug("Deleting tenant %s from VIM", tenant_id
)
274 self
._reload
_connection
()
275 if self
.osc_api_version
== 'v3.3':
276 self
.keystone
.projects
.delete(tenant_id
)
278 self
.keystone
.tenants
.delete(tenant_id
)
280 except (ksExceptions
.ConnectionError
, ksExceptions
.ClientException
, ConnectionError
) as e
:
281 self
._format
_exception
(e
)
283 def new_network(self
,net_name
, net_type
, ip_profile
=None, shared
=False, vlan
=None):
284 '''Adds a tenant network to VIM. Returns the network identifier'''
285 self
.logger
.debug("Adding a new network to VIM name '%s', type '%s'", net_name
, net_type
)
286 #self.logger.debug(">>>>>>>>>>>>>>>>>> IP profile %s", str(ip_profile))
289 self
._reload
_connection
()
290 network_dict
= {'name': net_name
, 'admin_state_up': True}
291 if net_type
=="data" or net_type
=="ptp":
292 if self
.config
.get('dataplane_physical_net') == None:
293 raise vimconn
.vimconnConflictException("You must provide a 'dataplane_physical_net' at config value before creating sriov network")
294 network_dict
["provider:physical_network"] = self
.config
['dataplane_physical_net'] #"physnet_sriov" #TODO physical
295 network_dict
["provider:network_type"] = "vlan"
297 network_dict
["provider:network_type"] = vlan
298 network_dict
["shared"]=shared
299 new_net
=self
.neutron
.create_network({'network':network_dict
})
301 #create subnetwork, even if there is no profile
304 if 'subnet_address' not in ip_profile
:
305 #Fake subnet is required
306 ip_profile
['subnet_address'] = "192.168.111.0/24"
307 if 'ip_version' not in ip_profile
:
308 ip_profile
['ip_version'] = "IPv4"
309 subnet
={"name":net_name
+"-subnet",
310 "network_id": new_net
["network"]["id"],
311 "ip_version": 4 if ip_profile
['ip_version']=="IPv4" else 6,
312 "cidr": ip_profile
['subnet_address']
314 if 'gateway_address' in ip_profile
:
315 subnet
['gateway_ip'] = ip_profile
['gateway_address']
316 if ip_profile
.get('dns_address'):
317 #TODO: manage dns_address as a list of addresses separated by commas
318 subnet
['dns_nameservers'] = []
319 subnet
['dns_nameservers'].append(ip_profile
['dns_address'])
320 if 'dhcp_enabled' in ip_profile
:
321 subnet
['enable_dhcp'] = False if ip_profile
['dhcp_enabled']=="false" else True
322 if 'dhcp_start_address' in ip_profile
:
323 subnet
['allocation_pools']=[]
324 subnet
['allocation_pools'].append(dict())
325 subnet
['allocation_pools'][0]['start'] = ip_profile
['dhcp_start_address']
326 if 'dhcp_count' in ip_profile
:
327 #parts = ip_profile['dhcp_start_address'].split('.')
328 #ip_int = (int(parts[0]) << 24) + (int(parts[1]) << 16) + (int(parts[2]) << 8) + int(parts[3])
329 ip_int
= int(netaddr
.IPAddress(ip_profile
['dhcp_start_address']))
330 ip_int
+= ip_profile
['dhcp_count'] - 1
331 ip_str
= str(netaddr
.IPAddress(ip_int
))
332 subnet
['allocation_pools'][0]['end'] = ip_str
333 #self.logger.debug(">>>>>>>>>>>>>>>>>> Subnet: %s", str(subnet))
334 self
.neutron
.create_subnet({"subnet": subnet
} )
335 return new_net
["network"]["id"]
336 except (neExceptions
.ConnectionFailed
, ksExceptions
.ClientException
, neExceptions
.NeutronException
, ConnectionError
) as e
:
338 self
.neutron
.delete_network(new_net
['network']['id'])
339 self
._format
_exception
(e
)
341 def get_network_list(self
, filter_dict
={}):
342 '''Obtain tenant networks of VIM
348 admin_state_up: boolean
350 Returns the network list of dictionaries
352 self
.logger
.debug("Getting network from VIM filter: '%s'", str(filter_dict
))
354 self
._reload
_connection
()
355 if self
.osc_api_version
== 'v3.3' and "tenant_id" in filter_dict
:
356 filter_dict
['project_id'] = filter_dict
.pop('tenant_id')
357 net_dict
=self
.neutron
.list_networks(**filter_dict
)
358 net_list
=net_dict
["networks"]
359 self
.__net
_os
2mano
(net_list
)
361 except (neExceptions
.ConnectionFailed
, ksExceptions
.ClientException
, neExceptions
.NeutronException
, ConnectionError
) as e
:
362 self
._format
_exception
(e
)
364 def get_network(self
, net_id
):
365 '''Obtain details of network from VIM
366 Returns the network information from a network id'''
367 self
.logger
.debug(" Getting tenant network %s from VIM", net_id
)
368 filter_dict
={"id": net_id
}
369 net_list
= self
.get_network_list(filter_dict
)
371 raise vimconn
.vimconnNotFoundException("Network '{}' not found".format(net_id
))
372 elif len(net_list
)>1:
373 raise vimconn
.vimconnConflictException("Found more than one network with this criteria")
376 for subnet_id
in net
.get("subnets", () ):
378 subnet
= self
.neutron
.show_subnet(subnet_id
)
379 except Exception as e
:
380 self
.logger
.error("osconnector.get_network(): Error getting subnet %s %s" % (net_id
, str(e
)))
381 subnet
= {"id": subnet_id
, "fault": str(e
)}
382 subnets
.append(subnet
)
383 net
["subnets"] = subnets
386 def delete_network(self
, net_id
):
387 '''Deletes a tenant network from VIM. Returns the old network identifier'''
388 self
.logger
.debug("Deleting network '%s' from VIM", net_id
)
390 self
._reload
_connection
()
391 #delete VM ports attached to this networks before the network
392 ports
= self
.neutron
.list_ports(network_id
=net_id
)
393 for p
in ports
['ports']:
395 self
.neutron
.delete_port(p
["id"])
396 except Exception as e
:
397 self
.logger
.error("Error deleting port %s: %s", p
["id"], str(e
))
398 self
.neutron
.delete_network(net_id
)
400 except (neExceptions
.ConnectionFailed
, neExceptions
.NetworkNotFoundClient
, neExceptions
.NeutronException
,
401 ksExceptions
.ClientException
, neExceptions
.NeutronException
, ConnectionError
) as e
:
402 self
._format
_exception
(e
)
404 def refresh_nets_status(self
, net_list
):
405 '''Get the status of the networks
406 Params: the list of network identifiers
407 Returns a dictionary with:
408 net_id: #VIM id of this network
409 status: #Mandatory. Text with one of:
410 # DELETED (not found at vim)
411 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
412 # OTHER (Vim reported other status not understood)
413 # ERROR (VIM indicates an ERROR status)
414 # ACTIVE, INACTIVE, DOWN (admin down),
415 # BUILD (on building process)
417 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
418 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
422 for net_id
in net_list
:
425 net_vim
= self
.get_network(net_id
)
426 if net_vim
['status'] in netStatus2manoFormat
:
427 net
["status"] = netStatus2manoFormat
[ net_vim
['status'] ]
429 net
["status"] = "OTHER"
430 net
["error_msg"] = "VIM status reported " + net_vim
['status']
432 if net
['status'] == "ACTIVE" and not net_vim
['admin_state_up']:
433 net
['status'] = 'DOWN'
435 net
['vim_info'] = yaml
.safe_dump(net_vim
, default_flow_style
=True, width
=256)
436 except yaml
.representer
.RepresenterError
:
437 net
['vim_info'] = str(net_vim
)
438 if net_vim
.get('fault'): #TODO
439 net
['error_msg'] = str(net_vim
['fault'])
440 except vimconn
.vimconnNotFoundException
as e
:
441 self
.logger
.error("Exception getting net status: %s", str(e
))
442 net
['status'] = "DELETED"
443 net
['error_msg'] = str(e
)
444 except vimconn
.vimconnException
as e
:
445 self
.logger
.error("Exception getting net status: %s", str(e
))
446 net
['status'] = "VIM_ERROR"
447 net
['error_msg'] = str(e
)
448 net_dict
[net_id
] = net
451 def get_flavor(self
, flavor_id
):
452 '''Obtain flavor details from the VIM. Returns the flavor dict details'''
453 self
.logger
.debug("Getting flavor '%s'", flavor_id
)
455 self
._reload
_connection
()
456 flavor
= self
.nova
.flavors
.find(id=flavor_id
)
457 #TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
458 return flavor
.to_dict()
459 except (nvExceptions
.NotFound
, nvExceptions
.ClientException
, ksExceptions
.ClientException
, ConnectionError
) as e
:
460 self
._format
_exception
(e
)
462 def new_flavor(self
, flavor_data
, change_name_if_used
=True):
463 '''Adds a tenant flavor to openstack VIM
464 if change_name_if_used is True, it will change name in case of conflict, because it is not supported name repetition
465 Returns the flavor identifier
467 self
.logger
.debug("Adding flavor '%s'", str(flavor_data
))
471 name
=flavor_data
['name']
472 while retry
<max_retries
:
475 self
._reload
_connection
()
476 if change_name_if_used
:
479 fl
=self
.nova
.flavors
.list()
481 fl_names
.append(f
.name
)
482 while name
in fl_names
:
484 name
= flavor_data
['name']+"-" + str(name_suffix
)
486 ram
= flavor_data
.get('ram',64)
487 vcpus
= flavor_data
.get('vcpus',1)
490 extended
= flavor_data
.get("extended")
492 numas
=extended
.get("numas")
494 numa_nodes
= len(numas
)
496 return -1, "Can not add flavor with more than one numa"
497 numa_properties
= {"hw:numa_nodes":str(numa_nodes
)}
498 numa_properties
["hw:mem_page_size"] = "large"
499 numa_properties
["hw:cpu_policy"] = "dedicated"
500 numa_properties
["hw:numa_mempolicy"] = "strict"
502 #overwrite ram and vcpus
503 ram
= numa
['memory']*1024
504 if 'paired-threads' in numa
:
505 vcpus
= numa
['paired-threads']*2
506 numa_properties
["hw:cpu_threads_policy"] = "prefer"
507 elif 'cores' in numa
:
508 vcpus
= numa
['cores']
509 #numa_properties["hw:cpu_threads_policy"] = "prefer"
510 elif 'threads' in numa
:
511 vcpus
= numa
['threads']
512 numa_properties
["hw:cpu_policy"] = "isolated"
513 for interface
in numa
.get("interfaces",() ):
514 if interface
["dedicated"]=="yes":
515 raise vimconn
.vimconnException("Passthrough interfaces are not supported for the openstack connector", http_code
=vimconn
.HTTP_Service_Unavailable
)
516 #TODO, add the key 'pci_passthrough:alias"="<label at config>:<number ifaces>"' when a way to connect it is available
519 new_flavor
=self
.nova
.flavors
.create(name
,
522 flavor_data
.get('disk',1),
523 is_public
=flavor_data
.get('is_public', True)
527 new_flavor
.set_keys(numa_properties
)
529 except nvExceptions
.Conflict
as e
:
530 if change_name_if_used
and retry
< max_retries
:
532 self
._format
_exception
(e
)
533 #except nvExceptions.BadRequest as e:
534 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
, ConnectionError
) as e
:
535 self
._format
_exception
(e
)
537 def delete_flavor(self
,flavor_id
):
538 '''Deletes a tenant flavor from openstack VIM. Returns the old flavor_id
541 self
._reload
_connection
()
542 self
.nova
.flavors
.delete(flavor_id
)
544 #except nvExceptions.BadRequest as e:
545 except (nvExceptions
.NotFound
, ksExceptions
.ClientException
, nvExceptions
.ClientException
, ConnectionError
) as e
:
546 self
._format
_exception
(e
)
548 def new_image(self
,image_dict
):
550 Adds a tenant image to VIM. imge_dict is a dictionary with:
552 disk_format: qcow2, vhd, vmdk, raw (by default), ...
553 location: path or URI
554 public: "yes" or "no"
555 metadata: metadata of the image
558 #using version 1 of glance client
559 glancev1
= gl1Client
.Client('1',self
.glance_endpoint
, token
=self
.keystone
.auth_token
, **self
.k_creds
) #TODO check k_creds vs n_creds
562 while retry
<max_retries
:
565 self
._reload
_connection
()
566 #determine format http://docs.openstack.org/developer/glance/formats.html
567 if "disk_format" in image_dict
:
568 disk_format
=image_dict
["disk_format"]
569 else: #autodiscover based on extension
570 if image_dict
['location'][-6:]==".qcow2":
572 elif image_dict
['location'][-4:]==".vhd":
574 elif image_dict
['location'][-5:]==".vmdk":
576 elif image_dict
['location'][-4:]==".vdi":
578 elif image_dict
['location'][-4:]==".iso":
580 elif image_dict
['location'][-4:]==".aki":
582 elif image_dict
['location'][-4:]==".ari":
584 elif image_dict
['location'][-4:]==".ami":
588 self
.logger
.debug("new_image: '%s' loading from '%s'", image_dict
['name'], image_dict
['location'])
589 if image_dict
['location'][0:4]=="http":
590 new_image
= glancev1
.images
.create(name
=image_dict
['name'], is_public
=image_dict
.get('public',"yes")=="yes",
591 container_format
="bare", location
=image_dict
['location'], disk_format
=disk_format
)
593 with
open(image_dict
['location']) as fimage
:
594 new_image
= glancev1
.images
.create(name
=image_dict
['name'], is_public
=image_dict
.get('public',"yes")=="yes",
595 container_format
="bare", data
=fimage
, disk_format
=disk_format
)
596 #insert metadata. We cannot use 'new_image.properties.setdefault'
597 #because nova and glance are "INDEPENDENT" and we are using nova for reading metadata
598 new_image_nova
=self
.nova
.images
.find(id=new_image
.id)
599 new_image_nova
.metadata
.setdefault('location',image_dict
['location'])
600 metadata_to_load
= image_dict
.get('metadata')
602 for k
,v
in yaml
.load(metadata_to_load
).iteritems():
603 new_image_nova
.metadata
.setdefault(k
,v
)
605 except (nvExceptions
.Conflict
, ksExceptions
.ClientException
, nvExceptions
.ClientException
) as e
:
606 self
._format
_exception
(e
)
607 except (HTTPException
, gl1Exceptions
.HTTPException
, gl1Exceptions
.CommunicationError
, ConnectionError
) as e
:
608 if retry
==max_retries
:
610 self
._format
_exception
(e
)
611 except IOError as e
: #can not open the file
612 raise vimconn
.vimconnConnectionException(type(e
).__name
__ + ": " + str(e
)+ " for " + image_dict
['location'],
613 http_code
=vimconn
.HTTP_Bad_Request
)
615 def delete_image(self
, image_id
):
616 '''Deletes a tenant image from openstack VIM. Returns the old id
619 self
._reload
_connection
()
620 self
.nova
.images
.delete(image_id
)
622 except (nvExceptions
.NotFound
, ksExceptions
.ClientException
, nvExceptions
.ClientException
, gl1Exceptions
.CommunicationError
, ConnectionError
) as e
: #TODO remove
623 self
._format
_exception
(e
)
625 def get_image_id_from_path(self
, path
):
626 '''Get the image id from image path in the VIM database. Returns the image_id'''
628 self
._reload
_connection
()
629 images
= self
.nova
.images
.list()
631 if image
.metadata
.get("location")==path
:
633 raise vimconn
.vimconnNotFoundException("image with location '{}' not found".format( path
))
634 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
, gl1Exceptions
.CommunicationError
, ConnectionError
) as e
:
635 self
._format
_exception
(e
)
637 def get_image_list(self
, filter_dict
={}):
638 '''Obtain tenant images from VIM
642 checksum: image checksum
643 Returns the image list of dictionaries:
644 [{<the fields at Filter_dict plus some VIM specific>}, ...]
647 self
.logger
.debug("Getting image list from VIM filter: '%s'", str(filter_dict
))
649 self
._reload
_connection
()
650 filter_dict_os
=filter_dict
.copy()
651 #First we filter by the available filter fields: name, id. The others are removed.
652 filter_dict_os
.pop('checksum',None)
653 image_list
=self
.nova
.images
.findall(**filter_dict_os
)
654 if len(image_list
)==0:
656 #Then we filter by the rest of filter fields: checksum
658 for image
in image_list
:
659 image_dict
=self
.glance
.images
.get(image
.id)
660 if 'checksum' not in filter_dict
or image_dict
['checksum']==filter_dict
.get('checksum'):
661 filtered_list
.append(image_dict
)
663 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
, gl1Exceptions
.CommunicationError
, ConnectionError
) as e
:
664 self
._format
_exception
(e
)
666 def new_vminstance(self
,name
,description
,start
,image_id
,flavor_id
,net_list
,cloud_config
=None,disk_list
=None):
667 '''Adds a VM instance to VIM
669 start: indicates if VM must start or boot in pause mode. Ignored
670 image_id,flavor_id: iamge and flavor uuid
671 net_list: list of interfaces, each one is a dictionary with:
673 net_id: network uuid to connect
674 vpci: virtual vcpi to assign, ignored because openstack lack #TODO
675 model: interface model, ignored #TODO
676 mac_address: used for SR-IOV ifaces #TODO for other types
677 use: 'data', 'bridge', 'mgmt'
678 type: 'virtual', 'PF', 'VF', 'VFnotShared'
679 vim_id: filled/added by this function
680 floating_ip: True/False (or it can be None)
681 #TODO ip, security groups
682 Returns the instance identifier
684 self
.logger
.debug("Creating VM image '%s' flavor '%s' nics='%s'",image_id
, flavor_id
,str(net_list
))
688 external_network
=[] #list of external networks to be connected to instance, later on used to create floating_ip
689 self
._reload
_connection
()
690 metadata_vpci
={} #For a specific neutron plugin
692 if not net
.get("net_id"): #skip non connected iface
694 if net
["type"]=="virtual" or net
["type"]=="VF":
696 "network_id": net
["net_id"],
697 "name": net
.get("name"),
698 "admin_state_up": True
700 if net
["type"]=="virtual":
702 metadata_vpci
[ net
["net_id"] ] = [[ net
["vpci"], "" ]]
705 if "VF" not in metadata_vpci
:
706 metadata_vpci
["VF"]=[]
707 metadata_vpci
["VF"].append([ net
["vpci"], "" ])
708 port_dict
["binding:vnic_type"]="direct"
709 if not port_dict
["name"]:
710 port_dict
["name"]=name
711 if net
.get("mac_address"):
712 port_dict
["mac_address"]=net
["mac_address"]
713 if net
.get("port_security") == False:
714 port_dict
["port_security_enabled"]=net
["port_security"]
715 new_port
= self
.neutron
.create_port({"port": port_dict
})
716 net
["mac_adress"] = new_port
["port"]["mac_address"]
717 net
["vim_id"] = new_port
["port"]["id"]
718 net
["ip"] = new_port
["port"].get("fixed_ips", [{}])[0].get("ip_address")
719 net_list_vim
.append({"port-id": new_port
["port"]["id"]})
721 self
.logger
.warn("new_vminstance: Warning, can not connect a passthrough interface ")
722 #TODO insert this when openstack consider passthrough ports as openstack neutron ports
723 if net
.get('floating_ip', False):
724 net
['exit_on_floating_ip_error'] = True
725 external_network
.append(net
)
726 elif net
['use'] == 'mgmt' and self
.config
.get('use_floating_ip'):
727 net
['exit_on_floating_ip_error'] = False
728 external_network
.append(net
)
731 metadata
= {"pci_assignement": json
.dumps(metadata_vpci
)}
732 if len(metadata
["pci_assignement"]) >255:
733 #limit the metadata size
734 #metadata["pci_assignement"] = metadata["pci_assignement"][0:255]
735 self
.logger
.warn("Metadata deleted since it exceeds the expected length (255) ")
738 self
.logger
.debug("name '%s' image_id '%s'flavor_id '%s' net_list_vim '%s' description '%s' metadata %s",
739 name
, image_id
, flavor_id
, str(net_list_vim
), description
, str(metadata
))
741 security_groups
= self
.config
.get('security_groups')
742 if type(security_groups
) is str:
743 security_groups
= ( security_groups
, )
747 if isinstance(cloud_config
, dict):
748 if cloud_config
.get("user-data"):
749 userdata
=cloud_config
["user-data"]
750 if cloud_config
.get("boot-data-drive") != None:
751 config_drive
= cloud_config
["boot-data-drive"]
752 if cloud_config
.get("config-files") or cloud_config
.get("users") or cloud_config
.get("key-pairs"):
754 raise vimconn
.vimconnConflictException("Cloud-config cannot contain both 'userdata' and 'config-files'/'users'/'key-pairs'")
757 if cloud_config
.get("key-pairs"):
758 userdata_dict
["ssh-authorized-keys"] = cloud_config
["key-pairs"]
759 userdata_dict
["users"] = [{"default": None, "ssh-authorized-keys": cloud_config
["key-pairs"] }]
760 if cloud_config
.get("users"):
761 if "users" not in cloud_config
:
762 userdata_dict
["users"] = [ "default" ]
763 for user
in cloud_config
["users"]:
765 "name" : user
["name"],
766 "sudo": "ALL = (ALL)NOPASSWD:ALL"
768 if "user-info" in user
:
769 user_info
["gecos"] = user
["user-info"]
770 if user
.get("key-pairs"):
771 user_info
["ssh-authorized-keys"] = user
["key-pairs"]
772 userdata_dict
["users"].append(user_info
)
774 if cloud_config
.get("config-files"):
775 userdata_dict
["write_files"] = []
776 for file in cloud_config
["config-files"]:
778 "path" : file["dest"],
779 "content": file["content"]
781 if file.get("encoding"):
782 file_info
["encoding"] = file["encoding"]
783 if file.get("permissions"):
784 file_info
["permissions"] = file["permissions"]
785 if file.get("owner"):
786 file_info
["owner"] = file["owner"]
787 userdata_dict
["write_files"].append(file_info
)
788 userdata
= "#cloud-config\n"
789 userdata
+= yaml
.safe_dump(userdata_dict
, indent
=4, default_flow_style
=False)
790 self
.logger
.debug("userdata: %s", userdata
)
791 elif isinstance(cloud_config
, str):
792 userdata
= cloud_config
794 #Create additional volumes in case these are present in disk_list
795 block_device_mapping
= None
796 base_disk_index
= ord('b')
797 if disk_list
!= None:
798 block_device_mapping
= dict()
799 for disk
in disk_list
:
800 if 'image_id' in disk
:
801 volume
= self
.cinder
.volumes
.create(size
= disk
['size'],name
= name
+ '_vd' +
802 chr(base_disk_index
), imageRef
= disk
['image_id'])
804 volume
= self
.cinder
.volumes
.create(size
=disk
['size'], name
=name
+ '_vd' +
805 chr(base_disk_index
))
806 block_device_mapping
['_vd' + chr(base_disk_index
)] = volume
.id
809 #wait until volumes are with status available
812 while keep_waiting
and elapsed_time
< volume_timeout
:
814 for volume_id
in block_device_mapping
.itervalues():
815 if self
.cinder
.volumes
.get(volume_id
).status
!= 'available':
821 #if we exceeded the timeout rollback
822 if elapsed_time
>= volume_timeout
:
823 #delete the volumes we just created
824 for volume_id
in block_device_mapping
.itervalues():
825 self
.cinder
.volumes
.delete(volume_id
)
827 #delete ports we just created
828 for net_item
in net_list_vim
:
829 if 'port-id' in net_item
:
830 self
.neutron
.delete_port(net_item
['port-id'])
832 raise vimconn
.vimconnException('Timeout creating volumes for instance ' + name
,
833 http_code
=vimconn
.HTTP_Request_Timeout
)
835 server
= self
.nova
.servers
.create(name
, image_id
, flavor_id
, nics
=net_list_vim
, meta
=metadata
,
836 security_groups
=security_groups
,
837 availability_zone
=self
.config
.get('availability_zone'),
838 key_name
=self
.config
.get('keypair'),
840 config_drive
= config_drive
,
841 block_device_mapping
= block_device_mapping
842 ) # , description=description)
843 #print "DONE :-)", server
845 floating_ips
= self
.neutron
.list_floatingips().get("floatingips", ())
846 for floating_network
in external_network
:
848 # wait until vm is active
850 while elapsed_time
< server_timeout
:
851 status
= self
.nova
.servers
.get(server
.id).status
852 if status
== 'ACTIVE':
857 #if we exceeded the timeout rollback
858 if elapsed_time
>= server_timeout
:
859 raise vimconn
.vimconnException('Timeout creating instance ' + name
,
860 http_code
=vimconn
.HTTP_Request_Timeout
)
863 while(assigned
== False):
865 ip
= floating_ips
.pop(0)
866 if not ip
.get("port_id", False) and ip
.get('tenant_id') == server
.tenant_id
:
867 free_floating_ip
= ip
.get("floating_ip_address")
869 fix_ip
= floating_network
.get('ip')
870 server
.add_floating_ip(free_floating_ip
, fix_ip
)
872 except Exception as e
:
873 raise vimconn
.vimconnException(type(e
).__name
__ + ": Cannot create floating_ip "+ str(e
), http_code
=vimconn
.HTTP_Conflict
)
875 #Find the external network
876 external_nets
= list()
877 for net
in self
.neutron
.list_networks()['networks']:
878 if net
['router:external']:
879 external_nets
.append(net
)
881 if len(external_nets
) == 0:
882 raise vimconn
.vimconnException("Cannot create floating_ip automatically since no external "
883 "network is present",
884 http_code
=vimconn
.HTTP_Conflict
)
885 if len(external_nets
) > 1:
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 raise vimconn
.vimconnException(type(e
).__name
__ + ": Cannot assign floating_ip "+ str(e
), http_code
=vimconn
.HTTP_Conflict
)
901 except Exception as e
:
902 if not floating_network
['exit_on_floating_ip_error']:
903 self
.logger
.warn("Cannot create floating_ip. %s", str(e
))
905 self
.delete_vminstance(server
.id)
909 # except nvExceptions.NotFound as e:
910 # error_value=-vimconn.HTTP_Not_Found
911 # error_text= "vm instance %s not found" % vm_id
912 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
, ConnectionError
) as e
:
913 # delete the volumes we just created
914 if block_device_mapping
!= None:
915 for volume_id
in block_device_mapping
.itervalues():
916 self
.cinder
.volumes
.delete(volume_id
)
918 # delete ports we just created
919 for net_item
in net_list_vim
:
920 if 'port-id' in net_item
:
921 self
.neutron
.delete_port(net_item
['port-id'])
922 self
._format
_exception
(e
)
923 except TypeError as e
:
924 raise vimconn
.vimconnException(type(e
).__name
__ + ": "+ str(e
), http_code
=vimconn
.HTTP_Bad_Request
)
926 def get_vminstance(self
,vm_id
):
927 '''Returns the VM instance information from VIM'''
928 #self.logger.debug("Getting VM from VIM")
930 self
._reload
_connection
()
931 server
= self
.nova
.servers
.find(id=vm_id
)
932 #TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
933 return server
.to_dict()
934 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
, nvExceptions
.NotFound
, ConnectionError
) as e
:
935 self
._format
_exception
(e
)
937 def get_vminstance_console(self
,vm_id
, console_type
="vnc"):
939 Get a console for the virtual machine
941 vm_id: uuid of the VM
942 console_type, can be:
943 "novnc" (by default), "xvpvnc" for VNC types,
944 "rdp-html5" for RDP types, "spice-html5" for SPICE types
945 Returns dict with the console parameters:
946 protocol: ssh, ftp, http, https, ...
947 server: usually ip address
948 port: the http, ssh, ... port
949 suffix: extra text, e.g. the http path and query string
951 self
.logger
.debug("Getting VM CONSOLE from VIM")
953 self
._reload
_connection
()
954 server
= self
.nova
.servers
.find(id=vm_id
)
955 if console_type
== None or console_type
== "novnc":
956 console_dict
= server
.get_vnc_console("novnc")
957 elif console_type
== "xvpvnc":
958 console_dict
= server
.get_vnc_console(console_type
)
959 elif console_type
== "rdp-html5":
960 console_dict
= server
.get_rdp_console(console_type
)
961 elif console_type
== "spice-html5":
962 console_dict
= server
.get_spice_console(console_type
)
964 raise vimconn
.vimconnException("console type '{}' not allowed".format(console_type
), http_code
=vimconn
.HTTP_Bad_Request
)
966 console_dict1
= console_dict
.get("console")
968 console_url
= console_dict1
.get("url")
971 protocol_index
= console_url
.find("//")
972 suffix_index
= console_url
[protocol_index
+2:].find("/") + protocol_index
+2
973 port_index
= console_url
[protocol_index
+2:suffix_index
].find(":") + protocol_index
+2
974 if protocol_index
< 0 or port_index
<0 or suffix_index
<0:
975 return -vimconn
.HTTP_Internal_Server_Error
, "Unexpected response from VIM"
976 console_dict
={"protocol": console_url
[0:protocol_index
],
977 "server": console_url
[protocol_index
+2:port_index
],
978 "port": console_url
[port_index
:suffix_index
],
979 "suffix": console_url
[suffix_index
+1:]
983 raise vimconn
.vimconnUnexpectedResponse("Unexpected response from VIM")
985 except (nvExceptions
.NotFound
, ksExceptions
.ClientException
, nvExceptions
.ClientException
, nvExceptions
.BadRequest
, ConnectionError
) as e
:
986 self
._format
_exception
(e
)
988 def delete_vminstance(self
, vm_id
):
989 '''Removes a VM instance from VIM. Returns the old identifier
991 #print "osconnector: Getting VM from VIM"
993 self
._reload
_connection
()
994 #delete VM ports attached to this networks before the virtual machine
995 ports
= self
.neutron
.list_ports(device_id
=vm_id
)
996 for p
in ports
['ports']:
998 self
.neutron
.delete_port(p
["id"])
999 except Exception as e
:
1000 self
.logger
.error("Error deleting port: " + type(e
).__name
__ + ": "+ str(e
))
1002 #commented because detaching the volumes makes the servers.delete not work properly ?!?
1003 #dettach volumes attached
1004 server
= self
.nova
.servers
.get(vm_id
)
1005 volumes_attached_dict
= server
._info
['os-extended-volumes:volumes_attached']
1006 #for volume in volumes_attached_dict:
1007 # self.cinder.volumes.detach(volume['id'])
1009 self
.nova
.servers
.delete(vm_id
)
1012 #Although having detached them should have them in active status
1013 #we ensure in this loop
1016 while keep_waiting
and elapsed_time
< volume_timeout
:
1017 keep_waiting
= False
1018 for volume
in volumes_attached_dict
:
1019 if self
.cinder
.volumes
.get(volume
['id']).status
!= 'available':
1022 self
.cinder
.volumes
.delete(volume
['id'])
1028 except (nvExceptions
.NotFound
, ksExceptions
.ClientException
, nvExceptions
.ClientException
, ConnectionError
) as e
:
1029 self
._format
_exception
(e
)
1030 #TODO insert exception vimconn.HTTP_Unauthorized
1031 #if reaching here is because an exception
1033 def refresh_vms_status(self
, vm_list
):
1034 '''Get the status of the virtual machines and their interfaces/ports
1035 Params: the list of VM identifiers
1036 Returns a dictionary with:
1037 vm_id: #VIM id of this Virtual Machine
1038 status: #Mandatory. Text with one of:
1039 # DELETED (not found at vim)
1040 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
1041 # OTHER (Vim reported other status not understood)
1042 # ERROR (VIM indicates an ERROR status)
1043 # ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running),
1044 # CREATING (on building process), ERROR
1045 # ACTIVE:NoMgmtIP (Active but any of its interface has an IP address
1047 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
1048 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
1050 - vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
1051 mac_address: #Text format XX:XX:XX:XX:XX:XX
1052 vim_net_id: #network id where this interface is connected
1053 vim_interface_id: #interface/port VIM id
1054 ip_address: #null, or text with IPv4, IPv6 address
1057 self
.logger
.debug("refresh_vms status: Getting tenant VM instance information from VIM")
1058 for vm_id
in vm_list
:
1061 vm_vim
= self
.get_vminstance(vm_id
)
1062 if vm_vim
['status'] in vmStatus2manoFormat
:
1063 vm
['status'] = vmStatus2manoFormat
[ vm_vim
['status'] ]
1065 vm
['status'] = "OTHER"
1066 vm
['error_msg'] = "VIM status reported " + vm_vim
['status']
1068 vm
['vim_info'] = yaml
.safe_dump(vm_vim
, default_flow_style
=True, width
=256)
1069 except yaml
.representer
.RepresenterError
:
1070 vm
['vim_info'] = str(vm_vim
)
1071 vm
["interfaces"] = []
1072 if vm_vim
.get('fault'):
1073 vm
['error_msg'] = str(vm_vim
['fault'])
1076 self
._reload
_connection
()
1077 port_dict
=self
.neutron
.list_ports(device_id
=vm_id
)
1078 for port
in port_dict
["ports"]:
1081 interface
['vim_info'] = yaml
.safe_dump(port
, default_flow_style
=True, width
=256)
1082 except yaml
.representer
.RepresenterError
:
1083 interface
['vim_info'] = str(port
)
1084 interface
["mac_address"] = port
.get("mac_address")
1085 interface
["vim_net_id"] = port
["network_id"]
1086 interface
["vim_interface_id"] = port
["id"]
1088 #look for floating ip address
1089 floating_ip_dict
= self
.neutron
.list_floatingips(port_id
=port
["id"])
1090 if floating_ip_dict
.get("floatingips"):
1091 ips
.append(floating_ip_dict
["floatingips"][0].get("floating_ip_address") )
1093 for subnet
in port
["fixed_ips"]:
1094 ips
.append(subnet
["ip_address"])
1095 interface
["ip_address"] = ";".join(ips
)
1096 vm
["interfaces"].append(interface
)
1097 except Exception as e
:
1098 self
.logger
.error("Error getting vm interface information " + type(e
).__name
__ + ": "+ str(e
))
1099 except vimconn
.vimconnNotFoundException
as e
:
1100 self
.logger
.error("Exception getting vm status: %s", str(e
))
1101 vm
['status'] = "DELETED"
1102 vm
['error_msg'] = str(e
)
1103 except vimconn
.vimconnException
as e
:
1104 self
.logger
.error("Exception getting vm status: %s", str(e
))
1105 vm
['status'] = "VIM_ERROR"
1106 vm
['error_msg'] = str(e
)
1110 def action_vminstance(self
, vm_id
, action_dict
):
1111 '''Send and action over a VM instance from VIM
1112 Returns the vm_id if the action was successfully sent to the VIM'''
1113 self
.logger
.debug("Action over VM '%s': %s", vm_id
, str(action_dict
))
1115 self
._reload
_connection
()
1116 server
= self
.nova
.servers
.find(id=vm_id
)
1117 if "start" in action_dict
:
1118 if action_dict
["start"]=="rebuild":
1121 if server
.status
=="PAUSED":
1123 elif server
.status
=="SUSPENDED":
1125 elif server
.status
=="SHUTOFF":
1127 elif "pause" in action_dict
:
1129 elif "resume" in action_dict
:
1131 elif "shutoff" in action_dict
or "shutdown" in action_dict
:
1133 elif "forceOff" in action_dict
:
1135 elif "terminate" in action_dict
:
1137 elif "createImage" in action_dict
:
1138 server
.create_image()
1139 #"path":path_schema,
1140 #"description":description_schema,
1141 #"name":name_schema,
1142 #"metadata":metadata_schema,
1143 #"imageRef": id_schema,
1144 #"disk": {"oneOf":[{"type": "null"}, {"type":"string"}] },
1145 elif "rebuild" in action_dict
:
1146 server
.rebuild(server
.image
['id'])
1147 elif "reboot" in action_dict
:
1148 server
.reboot() #reboot_type='SOFT'
1149 elif "console" in action_dict
:
1150 console_type
= action_dict
["console"]
1151 if console_type
== None or console_type
== "novnc":
1152 console_dict
= server
.get_vnc_console("novnc")
1153 elif console_type
== "xvpvnc":
1154 console_dict
= server
.get_vnc_console(console_type
)
1155 elif console_type
== "rdp-html5":
1156 console_dict
= server
.get_rdp_console(console_type
)
1157 elif console_type
== "spice-html5":
1158 console_dict
= server
.get_spice_console(console_type
)
1160 raise vimconn
.vimconnException("console type '{}' not allowed".format(console_type
),
1161 http_code
=vimconn
.HTTP_Bad_Request
)
1163 console_url
= console_dict
["console"]["url"]
1165 protocol_index
= console_url
.find("//")
1166 suffix_index
= console_url
[protocol_index
+2:].find("/") + protocol_index
+2
1167 port_index
= console_url
[protocol_index
+2:suffix_index
].find(":") + protocol_index
+2
1168 if protocol_index
< 0 or port_index
<0 or suffix_index
<0:
1169 raise vimconn
.vimconnException("Unexpected response from VIM " + str(console_dict
))
1170 console_dict2
={"protocol": console_url
[0:protocol_index
],
1171 "server": console_url
[protocol_index
+2 : port_index
],
1172 "port": int(console_url
[port_index
+1 : suffix_index
]),
1173 "suffix": console_url
[suffix_index
+1:]
1175 return console_dict2
1176 except Exception as e
:
1177 raise vimconn
.vimconnException("Unexpected response from VIM " + str(console_dict
))
1180 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
, nvExceptions
.NotFound
, ConnectionError
) as e
:
1181 self
._format
_exception
(e
)
1182 #TODO insert exception vimconn.HTTP_Unauthorized
1186 def new_external_port(self
, port_data
):
1187 #TODO openstack if needed
1188 '''Adds a external port to VIM'''
1189 '''Returns the port identifier'''
1190 return -vimconn
.HTTP_Internal_Server_Error
, "osconnector.new_external_port() not implemented"
1192 def connect_port_network(self
, port_id
, network_id
, admin
=False):
1193 #TODO openstack if needed
1194 '''Connects a external port to a network'''
1195 '''Returns status code of the VIM response'''
1196 return -vimconn
.HTTP_Internal_Server_Error
, "osconnector.connect_port_network() not implemented"
1198 def new_user(self
, user_name
, user_passwd
, tenant_id
=None):
1199 '''Adds a new user to openstack VIM'''
1200 '''Returns the user identifier'''
1201 self
.logger
.debug("osconnector: Adding a new user to VIM")
1203 self
._reload
_connection
()
1204 user
=self
.keystone
.users
.create(user_name
, user_passwd
, tenant_id
=tenant_id
)
1205 #self.keystone.tenants.add_user(self.k_creds["username"], #role)
1207 except ksExceptions
.ConnectionError
as e
:
1208 error_value
=-vimconn
.HTTP_Bad_Request
1209 error_text
= type(e
).__name
__ + ": "+ (str(e
) if len(e
.args
)==0 else str(e
.args
[0]))
1210 except ksExceptions
.ClientException
as e
: #TODO remove
1211 error_value
=-vimconn
.HTTP_Bad_Request
1212 error_text
= type(e
).__name
__ + ": "+ (str(e
) if len(e
.args
)==0 else str(e
.args
[0]))
1213 #TODO insert exception vimconn.HTTP_Unauthorized
1214 #if reaching here is because an exception
1216 self
.logger
.debug("new_user " + error_text
)
1217 return error_value
, error_text
1219 def delete_user(self
, user_id
):
1220 '''Delete a user from openstack VIM'''
1221 '''Returns the user identifier'''
1223 print "osconnector: Deleting a user from VIM"
1225 self
._reload
_connection
()
1226 self
.keystone
.users
.delete(user_id
)
1228 except ksExceptions
.ConnectionError
as e
:
1229 error_value
=-vimconn
.HTTP_Bad_Request
1230 error_text
= type(e
).__name
__ + ": "+ (str(e
) if len(e
.args
)==0 else str(e
.args
[0]))
1231 except ksExceptions
.NotFound
as e
:
1232 error_value
=-vimconn
.HTTP_Not_Found
1233 error_text
= type(e
).__name
__ + ": "+ (str(e
) if len(e
.args
)==0 else str(e
.args
[0]))
1234 except ksExceptions
.ClientException
as e
: #TODO remove
1235 error_value
=-vimconn
.HTTP_Bad_Request
1236 error_text
= type(e
).__name
__ + ": "+ (str(e
) if len(e
.args
)==0 else str(e
.args
[0]))
1237 #TODO insert exception vimconn.HTTP_Unauthorized
1238 #if reaching here is because an exception
1240 print "delete_tenant " + error_text
1241 return error_value
, error_text
1243 def get_hosts_info(self
):
1244 '''Get the information of deployed hosts
1245 Returns the hosts content'''
1247 print "osconnector: Getting Host info from VIM"
1250 self
._reload
_connection
()
1251 hypervisors
= self
.nova
.hypervisors
.list()
1252 for hype
in hypervisors
:
1253 h_list
.append( hype
.to_dict() )
1254 return 1, {"hosts":h_list
}
1255 except nvExceptions
.NotFound
as e
:
1256 error_value
=-vimconn
.HTTP_Not_Found
1257 error_text
= (str(e
) if len(e
.args
)==0 else str(e
.args
[0]))
1258 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
) as e
:
1259 error_value
=-vimconn
.HTTP_Bad_Request
1260 error_text
= type(e
).__name
__ + ": "+ (str(e
) if len(e
.args
)==0 else str(e
.args
[0]))
1261 #TODO insert exception vimconn.HTTP_Unauthorized
1262 #if reaching here is because an exception
1264 print "get_hosts_info " + error_text
1265 return error_value
, error_text
1267 def get_hosts(self
, vim_tenant
):
1268 '''Get the hosts and deployed instances
1269 Returns the hosts content'''
1270 r
, hype_dict
= self
.get_hosts_info()
1273 hypervisors
= hype_dict
["hosts"]
1275 servers
= self
.nova
.servers
.list()
1276 for hype
in hypervisors
:
1277 for server
in servers
:
1278 if server
.to_dict()['OS-EXT-SRV-ATTR:hypervisor_hostname']==hype
['hypervisor_hostname']:
1280 hype
['vm'].append(server
.id)
1282 hype
['vm'] = [server
.id]
1284 except nvExceptions
.NotFound
as e
:
1285 error_value
=-vimconn
.HTTP_Not_Found
1286 error_text
= (str(e
) if len(e
.args
)==0 else str(e
.args
[0]))
1287 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
) as e
:
1288 error_value
=-vimconn
.HTTP_Bad_Request
1289 error_text
= type(e
).__name
__ + ": "+ (str(e
) if len(e
.args
)==0 else str(e
.args
[0]))
1290 #TODO insert exception vimconn.HTTP_Unauthorized
1291 #if reaching here is because an exception
1293 print "get_hosts " + error_text
1294 return error_value
, error_text