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$"
39 from novaclient
import client
as nClient_v2
, exceptions
as nvExceptions
40 from novaclient
import api_versions
41 import keystoneclient
.v2_0
.client
as ksClient_v2
42 from novaclient
.v2
.client
import Client
as nClient
43 import keystoneclient
.v3
.client
as ksClient
44 import keystoneclient
.exceptions
as ksExceptions
45 import glanceclient
.v2
.client
as glClient
46 import glanceclient
.client
as gl1Client
47 import glanceclient
.exc
as gl1Exceptions
48 import cinderclient
.v2
.client
as cClient_v2
49 from httplib
import HTTPException
50 from neutronclient
.neutron
import client
as neClient_v2
51 from neutronclient
.v2_0
import client
as neClient
52 from neutronclient
.common
import exceptions
as neExceptions
53 from requests
.exceptions
import ConnectionError
55 '''contain the openstack virtual machine status to openmano status'''
56 vmStatus2manoFormat
={'ACTIVE':'ACTIVE',
58 'SUSPENDED': 'SUSPENDED',
61 'ERROR':'ERROR','DELETED':'DELETED'
63 netStatus2manoFormat
={'ACTIVE':'ACTIVE','PAUSED':'PAUSED','INACTIVE':'INACTIVE','BUILD':'BUILD','ERROR':'ERROR','DELETED':'DELETED'
66 #global var to have a timeout creating and deleting volumes
70 class vimconnector(vimconn
.vimconnector
):
71 def __init__(self
, uuid
, name
, tenant_id
, tenant_name
, url
, url_admin
=None, user
=None, passwd
=None,
72 log_level
=None, config
={}, persistent_info
={}):
73 '''using common constructor parameters. In this case
74 'url' is the keystone authorization url,
75 'url_admin' is not use
77 self
.osc_api_version
= 'v2.0'
78 if config
.get('APIversion') == 'v3.3':
79 self
.osc_api_version
= 'v3.3'
80 vimconn
.vimconnector
.__init
__(self
, uuid
, name
, tenant_id
, tenant_name
, url
, url_admin
, user
, passwd
, log_level
, config
)
82 self
.persistent_info
= persistent_info
85 if self
.config
.get("insecure"):
86 self
.k_creds
["insecure"] = True
87 self
.n_creds
["insecure"] = True
89 raise TypeError, 'url param can not be NoneType'
90 self
.k_creds
['auth_url'] = url
91 self
.n_creds
['auth_url'] = url
93 self
.k_creds
['tenant_name'] = tenant_name
94 self
.n_creds
['project_id'] = tenant_name
96 self
.k_creds
['tenant_id'] = tenant_id
97 self
.n_creds
['tenant_id'] = tenant_id
99 self
.k_creds
['username'] = user
100 self
.n_creds
['username'] = user
102 self
.k_creds
['password'] = passwd
103 self
.n_creds
['api_key'] = passwd
104 if self
.osc_api_version
== 'v3.3':
105 self
.k_creds
['project_name'] = tenant_name
106 self
.k_creds
['project_id'] = tenant_id
107 if config
.get('region_name'):
108 self
.k_creds
['region_name'] = config
.get('region_name')
109 self
.n_creds
['region_name'] = config
.get('region_name')
111 self
.reload_client
= True
112 self
.logger
= logging
.getLogger('openmano.vim.openstack')
114 self
.logger
.setLevel( getattr(logging
, log_level
) )
116 def __setitem__(self
,index
, value
):
117 '''Set individuals parameters
118 Throw TypeError, KeyError
120 if index
=='tenant_id':
121 self
.reload_client
=True
122 self
.tenant_id
= value
123 if self
.osc_api_version
== 'v3.3':
125 self
.k_creds
['project_id'] = value
126 self
.n_creds
['project_id'] = value
128 del self
.k_creds
['project_id']
129 del self
.n_creds
['project_id']
132 self
.k_creds
['tenant_id'] = value
133 self
.n_creds
['tenant_id'] = value
135 del self
.k_creds
['tenant_id']
136 del self
.n_creds
['tenant_id']
137 elif index
=='tenant_name':
138 self
.reload_client
=True
139 self
.tenant_name
= value
140 if self
.osc_api_version
== 'v3.3':
142 self
.k_creds
['project_name'] = value
143 self
.n_creds
['project_name'] = value
145 del self
.k_creds
['project_name']
146 del self
.n_creds
['project_name']
149 self
.k_creds
['tenant_name'] = value
150 self
.n_creds
['project_id'] = value
152 del self
.k_creds
['tenant_name']
153 del self
.n_creds
['project_id']
155 self
.reload_client
=True
158 self
.k_creds
['username'] = value
159 self
.n_creds
['username'] = value
161 del self
.k_creds
['username']
162 del self
.n_creds
['username']
163 elif index
=='passwd':
164 self
.reload_client
=True
167 self
.k_creds
['password'] = value
168 self
.n_creds
['api_key'] = value
170 del self
.k_creds
['password']
171 del self
.n_creds
['api_key']
173 self
.reload_client
=True
176 self
.k_creds
['auth_url'] = value
177 self
.n_creds
['auth_url'] = value
179 raise TypeError, 'url param can not be NoneType'
181 vimconn
.vimconnector
.__setitem
__(self
,index
, value
)
183 def _reload_connection(self
):
184 '''Called before any operation, it check if credentials has changed
185 Throw keystoneclient.apiclient.exceptions.AuthorizationFailure
187 #TODO control the timing and possible token timeout, but it seams that python client does this task for us :-)
188 if self
.reload_client
:
190 if len(self
.n_creds
) <4:
191 raise ksExceptions
.ClientException("Not enough parameters to connect to openstack")
192 if self
.osc_api_version
== 'v3.3':
193 self
.nova
= nClient(api_version
=api_versions
.APIVersion(version_str
='2.0'), **self
.n_creds
)
194 #TODO To be updated for v3
195 #self.cinder = cClient.Client(**self.n_creds)
196 self
.keystone
= ksClient
.Client(**self
.k_creds
)
197 self
.ne_endpoint
=self
.keystone
.service_catalog
.url_for(service_type
='network', endpoint_type
='publicURL')
198 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
)
200 self
.nova
= nClient_v2
.Client(version
='2', **self
.n_creds
)
201 self
.cinder
= cClient_v2
.Client(**self
.n_creds
)
202 self
.keystone
= ksClient_v2
.Client(**self
.k_creds
)
203 self
.ne_endpoint
=self
.keystone
.service_catalog
.url_for(service_type
='network', endpoint_type
='publicURL')
204 self
.neutron
= neClient_v2
.Client('2.0', endpoint_url
=self
.ne_endpoint
, token
=self
.keystone
.auth_token
, **self
.k_creds
)
205 self
.glance_endpoint
= self
.keystone
.service_catalog
.url_for(service_type
='image', endpoint_type
='publicURL')
206 self
.glance
= glClient
.Client(self
.glance_endpoint
, token
=self
.keystone
.auth_token
, **self
.k_creds
) #TODO check k_creds vs n_creds
207 self
.reload_client
= False
209 def __net_os2mano(self
, net_list_dict
):
210 '''Transform the net openstack format to mano format
211 net_list_dict can be a list of dict or a single dict'''
212 if type(net_list_dict
) is dict:
213 net_list_
=(net_list_dict
,)
214 elif type(net_list_dict
) is list:
215 net_list_
=net_list_dict
217 raise TypeError("param net_list_dict must be a list or a dictionary")
218 for net
in net_list_
:
219 if net
.get('provider:network_type') == "vlan":
226 def _format_exception(self
, exception
):
227 '''Transform a keystone, nova, neutron exception into a vimconn exception'''
228 if isinstance(exception
, (HTTPException
, gl1Exceptions
.HTTPException
, gl1Exceptions
.CommunicationError
,
229 ConnectionError
, ksExceptions
.ConnectionError
, neExceptions
.ConnectionFailed
231 raise vimconn
.vimconnConnectionException(type(exception
).__name
__ + ": " + str(exception
))
232 elif isinstance(exception
, (nvExceptions
.ClientException
, ksExceptions
.ClientException
,
233 neExceptions
.NeutronException
, nvExceptions
.BadRequest
)):
234 raise vimconn
.vimconnUnexpectedResponse(type(exception
).__name
__ + ": " + str(exception
))
235 elif isinstance(exception
, (neExceptions
.NetworkNotFoundClient
, nvExceptions
.NotFound
)):
236 raise vimconn
.vimconnNotFoundException(type(exception
).__name
__ + ": " + str(exception
))
237 elif isinstance(exception
, nvExceptions
.Conflict
):
238 raise vimconn
.vimconnConflictException(type(exception
).__name
__ + ": " + str(exception
))
240 raise vimconn
.vimconnConnectionException(type(exception
).__name
__ + ": " + str(exception
))
242 def get_tenant_list(self
, filter_dict
={}):
243 '''Obtain tenants of VIM
244 filter_dict can contain the following keys:
245 name: filter by tenant name
246 id: filter by tenant uuid/id
248 Returns the tenant list of dictionaries: [{'name':'<name>, 'id':'<id>, ...}, ...]
250 self
.logger
.debug("Getting tenants from VIM filter: '%s'", str(filter_dict
))
252 self
._reload
_connection
()
253 if self
.osc_api_version
== 'v3.3':
254 project_class_list
=self
.keystone
.projects
.findall(**filter_dict
)
256 project_class_list
=self
.keystone
.tenants
.findall(**filter_dict
)
258 for project
in project_class_list
:
259 project_list
.append(project
.to_dict())
261 except (ksExceptions
.ConnectionError
, ksExceptions
.ClientException
, ConnectionError
) as e
:
262 self
._format
_exception
(e
)
264 def new_tenant(self
, tenant_name
, tenant_description
):
265 '''Adds a new tenant to openstack VIM. Returns the tenant identifier'''
266 self
.logger
.debug("Adding a new tenant name: %s", tenant_name
)
268 self
._reload
_connection
()
269 if self
.osc_api_version
== 'v3.3':
270 project
=self
.keystone
.projects
.create(tenant_name
, tenant_description
)
272 project
=self
.keystone
.tenants
.create(tenant_name
, tenant_description
)
274 except (ksExceptions
.ConnectionError
, ksExceptions
.ClientException
, ConnectionError
) as e
:
275 self
._format
_exception
(e
)
277 def delete_tenant(self
, tenant_id
):
278 '''Delete a tenant from openstack VIM. Returns the old tenant identifier'''
279 self
.logger
.debug("Deleting tenant %s from VIM", tenant_id
)
281 self
._reload
_connection
()
282 if self
.osc_api_version
== 'v3.3':
283 self
.keystone
.projects
.delete(tenant_id
)
285 self
.keystone
.tenants
.delete(tenant_id
)
287 except (ksExceptions
.ConnectionError
, ksExceptions
.ClientException
, ConnectionError
) as e
:
288 self
._format
_exception
(e
)
290 def new_network(self
,net_name
, net_type
, ip_profile
=None, shared
=False, vlan
=None):
291 '''Adds a tenant network to VIM. Returns the network identifier'''
292 self
.logger
.debug("Adding a new network to VIM name '%s', type '%s'", net_name
, net_type
)
293 #self.logger.debug(">>>>>>>>>>>>>>>>>> IP profile %s", str(ip_profile))
296 self
._reload
_connection
()
297 network_dict
= {'name': net_name
, 'admin_state_up': True}
298 if net_type
=="data" or net_type
=="ptp":
299 if self
.config
.get('dataplane_physical_net') == None:
300 raise vimconn
.vimconnConflictException("You must provide a 'dataplane_physical_net' at config value before creating sriov network")
301 network_dict
["provider:physical_network"] = self
.config
['dataplane_physical_net'] #"physnet_sriov" #TODO physical
302 network_dict
["provider:network_type"] = "vlan"
304 network_dict
["provider:network_type"] = vlan
305 network_dict
["shared"]=shared
306 new_net
=self
.neutron
.create_network({'network':network_dict
})
308 #create subnetwork, even if there is no profile
311 if 'subnet_address' not in ip_profile
:
312 #Fake subnet is required
313 subnet_rand
= random
.randint(0, 255)
314 ip_profile
['subnet_address'] = "192.168.{}.0/24".format(subnet_rand
)
315 if 'ip_version' not in ip_profile
:
316 ip_profile
['ip_version'] = "IPv4"
317 subnet
={"name":net_name
+"-subnet",
318 "network_id": new_net
["network"]["id"],
319 "ip_version": 4 if ip_profile
['ip_version']=="IPv4" else 6,
320 "cidr": ip_profile
['subnet_address']
322 if 'gateway_address' in ip_profile
:
323 subnet
['gateway_ip'] = ip_profile
['gateway_address']
324 if ip_profile
.get('dns_address'):
325 #TODO: manage dns_address as a list of addresses separated by commas
326 subnet
['dns_nameservers'] = []
327 subnet
['dns_nameservers'].append(ip_profile
['dns_address'])
328 if 'dhcp_enabled' in ip_profile
:
329 subnet
['enable_dhcp'] = False if ip_profile
['dhcp_enabled']=="false" else True
330 if 'dhcp_start_address' in ip_profile
:
331 subnet
['allocation_pools']=[]
332 subnet
['allocation_pools'].append(dict())
333 subnet
['allocation_pools'][0]['start'] = ip_profile
['dhcp_start_address']
334 if 'dhcp_count' in ip_profile
:
335 #parts = ip_profile['dhcp_start_address'].split('.')
336 #ip_int = (int(parts[0]) << 24) + (int(parts[1]) << 16) + (int(parts[2]) << 8) + int(parts[3])
337 ip_int
= int(netaddr
.IPAddress(ip_profile
['dhcp_start_address']))
338 ip_int
+= ip_profile
['dhcp_count'] - 1
339 ip_str
= str(netaddr
.IPAddress(ip_int
))
340 subnet
['allocation_pools'][0]['end'] = ip_str
341 #self.logger.debug(">>>>>>>>>>>>>>>>>> Subnet: %s", str(subnet))
342 self
.neutron
.create_subnet({"subnet": subnet
} )
343 return new_net
["network"]["id"]
344 except (neExceptions
.ConnectionFailed
, ksExceptions
.ClientException
, neExceptions
.NeutronException
, ConnectionError
) as e
:
346 self
.neutron
.delete_network(new_net
['network']['id'])
347 self
._format
_exception
(e
)
349 def get_network_list(self
, filter_dict
={}):
350 '''Obtain tenant networks of VIM
356 admin_state_up: boolean
358 Returns the network list of dictionaries
360 self
.logger
.debug("Getting network from VIM filter: '%s'", str(filter_dict
))
362 self
._reload
_connection
()
363 if self
.osc_api_version
== 'v3.3' and "tenant_id" in filter_dict
:
364 filter_dict
['project_id'] = filter_dict
.pop('tenant_id')
365 net_dict
=self
.neutron
.list_networks(**filter_dict
)
366 net_list
=net_dict
["networks"]
367 self
.__net
_os
2mano
(net_list
)
369 except (neExceptions
.ConnectionFailed
, ksExceptions
.ClientException
, neExceptions
.NeutronException
, ConnectionError
) as e
:
370 self
._format
_exception
(e
)
372 def get_network(self
, net_id
):
373 '''Obtain details of network from VIM
374 Returns the network information from a network id'''
375 self
.logger
.debug(" Getting tenant network %s from VIM", net_id
)
376 filter_dict
={"id": net_id
}
377 net_list
= self
.get_network_list(filter_dict
)
379 raise vimconn
.vimconnNotFoundException("Network '{}' not found".format(net_id
))
380 elif len(net_list
)>1:
381 raise vimconn
.vimconnConflictException("Found more than one network with this criteria")
384 for subnet_id
in net
.get("subnets", () ):
386 subnet
= self
.neutron
.show_subnet(subnet_id
)
387 except Exception as e
:
388 self
.logger
.error("osconnector.get_network(): Error getting subnet %s %s" % (net_id
, str(e
)))
389 subnet
= {"id": subnet_id
, "fault": str(e
)}
390 subnets
.append(subnet
)
391 net
["subnets"] = subnets
394 def delete_network(self
, net_id
):
395 '''Deletes a tenant network from VIM. Returns the old network identifier'''
396 self
.logger
.debug("Deleting network '%s' from VIM", net_id
)
398 self
._reload
_connection
()
399 #delete VM ports attached to this networks before the network
400 ports
= self
.neutron
.list_ports(network_id
=net_id
)
401 for p
in ports
['ports']:
403 self
.neutron
.delete_port(p
["id"])
404 except Exception as e
:
405 self
.logger
.error("Error deleting port %s: %s", p
["id"], str(e
))
406 self
.neutron
.delete_network(net_id
)
408 except (neExceptions
.ConnectionFailed
, neExceptions
.NetworkNotFoundClient
, neExceptions
.NeutronException
,
409 ksExceptions
.ClientException
, neExceptions
.NeutronException
, ConnectionError
) as e
:
410 self
._format
_exception
(e
)
412 def refresh_nets_status(self
, net_list
):
413 '''Get the status of the networks
414 Params: the list of network identifiers
415 Returns a dictionary with:
416 net_id: #VIM id of this network
417 status: #Mandatory. Text with one of:
418 # DELETED (not found at vim)
419 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
420 # OTHER (Vim reported other status not understood)
421 # ERROR (VIM indicates an ERROR status)
422 # ACTIVE, INACTIVE, DOWN (admin down),
423 # BUILD (on building process)
425 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
426 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
430 for net_id
in net_list
:
433 net_vim
= self
.get_network(net_id
)
434 if net_vim
['status'] in netStatus2manoFormat
:
435 net
["status"] = netStatus2manoFormat
[ net_vim
['status'] ]
437 net
["status"] = "OTHER"
438 net
["error_msg"] = "VIM status reported " + net_vim
['status']
440 if net
['status'] == "ACTIVE" and not net_vim
['admin_state_up']:
441 net
['status'] = 'DOWN'
443 net
['vim_info'] = yaml
.safe_dump(net_vim
, default_flow_style
=True, width
=256)
444 except yaml
.representer
.RepresenterError
:
445 net
['vim_info'] = str(net_vim
)
446 if net_vim
.get('fault'): #TODO
447 net
['error_msg'] = str(net_vim
['fault'])
448 except vimconn
.vimconnNotFoundException
as e
:
449 self
.logger
.error("Exception getting net status: %s", str(e
))
450 net
['status'] = "DELETED"
451 net
['error_msg'] = str(e
)
452 except vimconn
.vimconnException
as e
:
453 self
.logger
.error("Exception getting net status: %s", str(e
))
454 net
['status'] = "VIM_ERROR"
455 net
['error_msg'] = str(e
)
456 net_dict
[net_id
] = net
459 def get_flavor(self
, flavor_id
):
460 '''Obtain flavor details from the VIM. Returns the flavor dict details'''
461 self
.logger
.debug("Getting flavor '%s'", flavor_id
)
463 self
._reload
_connection
()
464 flavor
= self
.nova
.flavors
.find(id=flavor_id
)
465 #TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
466 return flavor
.to_dict()
467 except (nvExceptions
.NotFound
, nvExceptions
.ClientException
, ksExceptions
.ClientException
, ConnectionError
) as e
:
468 self
._format
_exception
(e
)
470 def get_flavor_id_from_data(self
, flavor_dict
):
471 """Obtain flavor id that match the flavor description
472 Returns the flavor_id or raises a vimconnNotFoundException
475 self
._reload
_connection
()
477 numas
= flavor_dict
.get("extended",{}).get("numas")
480 raise vimconn
.vimconnNotFoundException("Flavor with EPA still not implemted")
482 # raise vimconn.vimconnNotFoundException("Cannot find any flavor with more than one numa")
484 # numas = extended.get("numas")
485 for flavor
in self
.nova
.flavors
.list():
486 epa
= flavor
.get_keys()
490 if flavor
.ram
!= flavor_dict
["ram"]:
492 if flavor
.vcpus
!= flavor_dict
["vcpus"]:
494 if flavor
.disk
!= flavor_dict
["disk"]:
497 raise vimconn
.vimconnNotFoundException("Cannot find any flavor matching '{}'".format(str(flavor_dict
)))
498 except (nvExceptions
.NotFound
, nvExceptions
.ClientException
, ksExceptions
.ClientException
, ConnectionError
) as e
:
499 self
._format
_exception
(e
)
502 def new_flavor(self
, flavor_data
, change_name_if_used
=True):
503 '''Adds a tenant flavor to openstack VIM
504 if change_name_if_used is True, it will change name in case of conflict, because it is not supported name repetition
505 Returns the flavor identifier
507 self
.logger
.debug("Adding flavor '%s'", str(flavor_data
))
511 name
=flavor_data
['name']
512 while retry
<max_retries
:
515 self
._reload
_connection
()
516 if change_name_if_used
:
519 fl
=self
.nova
.flavors
.list()
521 fl_names
.append(f
.name
)
522 while name
in fl_names
:
524 name
= flavor_data
['name']+"-" + str(name_suffix
)
526 ram
= flavor_data
.get('ram',64)
527 vcpus
= flavor_data
.get('vcpus',1)
530 extended
= flavor_data
.get("extended")
532 numas
=extended
.get("numas")
534 numa_nodes
= len(numas
)
536 return -1, "Can not add flavor with more than one numa"
537 numa_properties
= {"hw:numa_nodes":str(numa_nodes
)}
538 numa_properties
["hw:mem_page_size"] = "large"
539 numa_properties
["hw:cpu_policy"] = "dedicated"
540 numa_properties
["hw:numa_mempolicy"] = "strict"
542 #overwrite ram and vcpus
543 ram
= numa
['memory']*1024
544 if 'paired-threads' in numa
:
545 vcpus
= numa
['paired-threads']*2
546 numa_properties
["hw:cpu_threads_policy"] = "prefer"
547 elif 'cores' in numa
:
548 vcpus
= numa
['cores']
549 #numa_properties["hw:cpu_threads_policy"] = "prefer"
550 elif 'threads' in numa
:
551 vcpus
= numa
['threads']
552 numa_properties
["hw:cpu_policy"] = "isolated"
553 for interface
in numa
.get("interfaces",() ):
554 if interface
["dedicated"]=="yes":
555 raise vimconn
.vimconnException("Passthrough interfaces are not supported for the openstack connector", http_code
=vimconn
.HTTP_Service_Unavailable
)
556 #TODO, add the key 'pci_passthrough:alias"="<label at config>:<number ifaces>"' when a way to connect it is available
559 new_flavor
=self
.nova
.flavors
.create(name
,
562 flavor_data
.get('disk',1),
563 is_public
=flavor_data
.get('is_public', True)
567 new_flavor
.set_keys(numa_properties
)
569 except nvExceptions
.Conflict
as e
:
570 if change_name_if_used
and retry
< max_retries
:
572 self
._format
_exception
(e
)
573 #except nvExceptions.BadRequest as e:
574 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
, ConnectionError
) as e
:
575 self
._format
_exception
(e
)
577 def delete_flavor(self
,flavor_id
):
578 '''Deletes a tenant flavor from openstack VIM. Returns the old flavor_id
581 self
._reload
_connection
()
582 self
.nova
.flavors
.delete(flavor_id
)
584 #except nvExceptions.BadRequest as e:
585 except (nvExceptions
.NotFound
, ksExceptions
.ClientException
, nvExceptions
.ClientException
, ConnectionError
) as e
:
586 self
._format
_exception
(e
)
588 def new_image(self
,image_dict
):
590 Adds a tenant image to VIM. imge_dict is a dictionary with:
592 disk_format: qcow2, vhd, vmdk, raw (by default), ...
593 location: path or URI
594 public: "yes" or "no"
595 metadata: metadata of the image
598 #using version 1 of glance client
599 glancev1
= gl1Client
.Client('1',self
.glance_endpoint
, token
=self
.keystone
.auth_token
, **self
.k_creds
) #TODO check k_creds vs n_creds
602 while retry
<max_retries
:
605 self
._reload
_connection
()
606 #determine format http://docs.openstack.org/developer/glance/formats.html
607 if "disk_format" in image_dict
:
608 disk_format
=image_dict
["disk_format"]
609 else: #autodiscover based on extension
610 if image_dict
['location'][-6:]==".qcow2":
612 elif image_dict
['location'][-4:]==".vhd":
614 elif image_dict
['location'][-5:]==".vmdk":
616 elif image_dict
['location'][-4:]==".vdi":
618 elif image_dict
['location'][-4:]==".iso":
620 elif image_dict
['location'][-4:]==".aki":
622 elif image_dict
['location'][-4:]==".ari":
624 elif image_dict
['location'][-4:]==".ami":
628 self
.logger
.debug("new_image: '%s' loading from '%s'", image_dict
['name'], image_dict
['location'])
629 if image_dict
['location'][0:4]=="http":
630 new_image
= glancev1
.images
.create(name
=image_dict
['name'], is_public
=image_dict
.get('public',"yes")=="yes",
631 container_format
="bare", location
=image_dict
['location'], disk_format
=disk_format
)
633 with
open(image_dict
['location']) as fimage
:
634 new_image
= glancev1
.images
.create(name
=image_dict
['name'], is_public
=image_dict
.get('public',"yes")=="yes",
635 container_format
="bare", data
=fimage
, disk_format
=disk_format
)
636 #insert metadata. We cannot use 'new_image.properties.setdefault'
637 #because nova and glance are "INDEPENDENT" and we are using nova for reading metadata
638 new_image_nova
=self
.nova
.images
.find(id=new_image
.id)
639 new_image_nova
.metadata
.setdefault('location',image_dict
['location'])
640 metadata_to_load
= image_dict
.get('metadata')
642 for k
,v
in yaml
.load(metadata_to_load
).iteritems():
643 new_image_nova
.metadata
.setdefault(k
,v
)
645 except (nvExceptions
.Conflict
, ksExceptions
.ClientException
, nvExceptions
.ClientException
) as e
:
646 self
._format
_exception
(e
)
647 except (HTTPException
, gl1Exceptions
.HTTPException
, gl1Exceptions
.CommunicationError
, ConnectionError
) as e
:
648 if retry
==max_retries
:
650 self
._format
_exception
(e
)
651 except IOError as e
: #can not open the file
652 raise vimconn
.vimconnConnectionException(type(e
).__name
__ + ": " + str(e
)+ " for " + image_dict
['location'],
653 http_code
=vimconn
.HTTP_Bad_Request
)
655 def delete_image(self
, image_id
):
656 '''Deletes a tenant image from openstack VIM. Returns the old id
659 self
._reload
_connection
()
660 self
.nova
.images
.delete(image_id
)
662 except (nvExceptions
.NotFound
, ksExceptions
.ClientException
, nvExceptions
.ClientException
, gl1Exceptions
.CommunicationError
, ConnectionError
) as e
: #TODO remove
663 self
._format
_exception
(e
)
665 def get_image_id_from_path(self
, path
):
666 '''Get the image id from image path in the VIM database. Returns the image_id'''
668 self
._reload
_connection
()
669 images
= self
.nova
.images
.list()
671 if image
.metadata
.get("location")==path
:
673 raise vimconn
.vimconnNotFoundException("image with location '{}' not found".format( path
))
674 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
, gl1Exceptions
.CommunicationError
, ConnectionError
) as e
:
675 self
._format
_exception
(e
)
677 def get_image_list(self
, filter_dict
={}):
678 '''Obtain tenant images from VIM
682 checksum: image checksum
683 Returns the image list of dictionaries:
684 [{<the fields at Filter_dict plus some VIM specific>}, ...]
687 self
.logger
.debug("Getting image list from VIM filter: '%s'", str(filter_dict
))
689 self
._reload
_connection
()
690 filter_dict_os
=filter_dict
.copy()
691 #First we filter by the available filter fields: name, id. The others are removed.
692 filter_dict_os
.pop('checksum',None)
693 image_list
=self
.nova
.images
.findall(**filter_dict_os
)
694 if len(image_list
)==0:
696 #Then we filter by the rest of filter fields: checksum
698 for image
in image_list
:
699 image_class
=self
.glance
.images
.get(image
.id)
700 if 'checksum' not in filter_dict
or image_class
['checksum']==filter_dict
.get('checksum'):
701 filtered_list
.append(image_class
.copy())
703 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
, gl1Exceptions
.CommunicationError
, ConnectionError
) as e
:
704 self
._format
_exception
(e
)
706 def new_vminstance(self
,name
,description
,start
,image_id
,flavor_id
,net_list
,cloud_config
=None,disk_list
=None):
707 '''Adds a VM instance to VIM
709 start: indicates if VM must start or boot in pause mode. Ignored
710 image_id,flavor_id: iamge and flavor uuid
711 net_list: list of interfaces, each one is a dictionary with:
713 net_id: network uuid to connect
714 vpci: virtual vcpi to assign, ignored because openstack lack #TODO
715 model: interface model, ignored #TODO
716 mac_address: used for SR-IOV ifaces #TODO for other types
717 use: 'data', 'bridge', 'mgmt'
718 type: 'virtual', 'PF', 'VF', 'VFnotShared'
719 vim_id: filled/added by this function
720 floating_ip: True/False (or it can be None)
721 #TODO ip, security groups
722 Returns the instance identifier
724 self
.logger
.debug("new_vminstance input: image='%s' flavor='%s' nics='%s'",image_id
, flavor_id
,str(net_list
))
728 external_network
=[] #list of external networks to be connected to instance, later on used to create floating_ip
729 self
._reload
_connection
()
730 metadata_vpci
={} #For a specific neutron plugin
732 if not net
.get("net_id"): #skip non connected iface
734 if net
["type"]=="virtual" or net
["type"]=="VF":
736 "network_id": net
["net_id"],
737 "name": net
.get("name"),
738 "admin_state_up": True
740 if net
["type"]=="virtual":
742 metadata_vpci
[ net
["net_id"] ] = [[ net
["vpci"], "" ]]
745 if "VF" not in metadata_vpci
:
746 metadata_vpci
["VF"]=[]
747 metadata_vpci
["VF"].append([ net
["vpci"], "" ])
748 port_dict
["binding:vnic_type"]="direct"
749 if not port_dict
["name"]:
750 port_dict
["name"]=name
751 if net
.get("mac_address"):
752 port_dict
["mac_address"]=net
["mac_address"]
753 if net
.get("port_security") == False:
754 port_dict
["port_security_enabled"]=net
["port_security"]
755 new_port
= self
.neutron
.create_port({"port": port_dict
})
756 net
["mac_adress"] = new_port
["port"]["mac_address"]
757 net
["vim_id"] = new_port
["port"]["id"]
758 net
["ip"] = new_port
["port"].get("fixed_ips", [{}])[0].get("ip_address")
759 net_list_vim
.append({"port-id": new_port
["port"]["id"]})
761 self
.logger
.warn("new_vminstance: Warning, can not connect a passthrough interface ")
762 #TODO insert this when openstack consider passthrough ports as openstack neutron ports
763 if net
.get('floating_ip', False):
764 net
['exit_on_floating_ip_error'] = True
765 external_network
.append(net
)
766 elif net
['use'] == 'mgmt' and self
.config
.get('use_floating_ip'):
767 net
['exit_on_floating_ip_error'] = False
768 external_network
.append(net
)
771 metadata
= {"pci_assignement": json
.dumps(metadata_vpci
)}
772 if len(metadata
["pci_assignement"]) >255:
773 #limit the metadata size
774 #metadata["pci_assignement"] = metadata["pci_assignement"][0:255]
775 self
.logger
.warn("Metadata deleted since it exceeds the expected length (255) ")
778 self
.logger
.debug("name '%s' image_id '%s'flavor_id '%s' net_list_vim '%s' description '%s' metadata %s",
779 name
, image_id
, flavor_id
, str(net_list_vim
), description
, str(metadata
))
781 security_groups
= self
.config
.get('security_groups')
782 if type(security_groups
) is str:
783 security_groups
= ( security_groups
, )
787 if isinstance(cloud_config
, dict):
788 if cloud_config
.get("user-data"):
789 userdata
=cloud_config
["user-data"]
790 if cloud_config
.get("boot-data-drive") != None:
791 config_drive
= cloud_config
["boot-data-drive"]
792 if cloud_config
.get("config-files") or cloud_config
.get("users") or cloud_config
.get("key-pairs"):
794 raise vimconn
.vimconnConflictException("Cloud-config cannot contain both 'userdata' and 'config-files'/'users'/'key-pairs'")
797 if cloud_config
.get("key-pairs"):
798 userdata_dict
["ssh-authorized-keys"] = cloud_config
["key-pairs"]
799 userdata_dict
["users"] = [{"default": None, "ssh-authorized-keys": cloud_config
["key-pairs"] }]
800 if cloud_config
.get("users"):
801 if "users" not in userdata_dict
:
802 userdata_dict
["users"] = [ "default" ]
803 for user
in cloud_config
["users"]:
805 "name" : user
["name"],
806 "sudo": "ALL = (ALL)NOPASSWD:ALL"
808 if "user-info" in user
:
809 user_info
["gecos"] = user
["user-info"]
810 if user
.get("key-pairs"):
811 user_info
["ssh-authorized-keys"] = user
["key-pairs"]
812 userdata_dict
["users"].append(user_info
)
814 if cloud_config
.get("config-files"):
815 userdata_dict
["write_files"] = []
816 for file in cloud_config
["config-files"]:
818 "path" : file["dest"],
819 "content": file["content"]
821 if file.get("encoding"):
822 file_info
["encoding"] = file["encoding"]
823 if file.get("permissions"):
824 file_info
["permissions"] = file["permissions"]
825 if file.get("owner"):
826 file_info
["owner"] = file["owner"]
827 userdata_dict
["write_files"].append(file_info
)
828 userdata
= "#cloud-config\n"
829 userdata
+= yaml
.safe_dump(userdata_dict
, indent
=4, default_flow_style
=False)
830 self
.logger
.debug("userdata: %s", userdata
)
831 elif isinstance(cloud_config
, str):
832 userdata
= cloud_config
834 #Create additional volumes in case these are present in disk_list
835 block_device_mapping
= None
836 base_disk_index
= ord('b')
837 if disk_list
!= None:
838 block_device_mapping
= dict()
839 for disk
in disk_list
:
840 if 'image_id' in disk
:
841 volume
= self
.cinder
.volumes
.create(size
= disk
['size'],name
= name
+ '_vd' +
842 chr(base_disk_index
), imageRef
= disk
['image_id'])
844 volume
= self
.cinder
.volumes
.create(size
=disk
['size'], name
=name
+ '_vd' +
845 chr(base_disk_index
))
846 block_device_mapping
['_vd' + chr(base_disk_index
)] = volume
.id
849 #wait until volumes are with status available
852 while keep_waiting
and elapsed_time
< volume_timeout
:
854 for volume_id
in block_device_mapping
.itervalues():
855 if self
.cinder
.volumes
.get(volume_id
).status
!= 'available':
861 #if we exceeded the timeout rollback
862 if elapsed_time
>= volume_timeout
:
863 #delete the volumes we just created
864 for volume_id
in block_device_mapping
.itervalues():
865 self
.cinder
.volumes
.delete(volume_id
)
867 #delete ports we just created
868 for net_item
in net_list_vim
:
869 if 'port-id' in net_item
:
870 self
.neutron
.delete_port(net_item
['port-id'])
872 raise vimconn
.vimconnException('Timeout creating volumes for instance ' + name
,
873 http_code
=vimconn
.HTTP_Request_Timeout
)
875 server
= self
.nova
.servers
.create(name
, image_id
, flavor_id
, nics
=net_list_vim
, meta
=metadata
,
876 security_groups
=security_groups
,
877 availability_zone
=self
.config
.get('availability_zone'),
878 key_name
=self
.config
.get('keypair'),
880 config_drive
= config_drive
,
881 block_device_mapping
= block_device_mapping
882 ) # , description=description)
883 #print "DONE :-)", server
885 floating_ips
= self
.neutron
.list_floatingips().get("floatingips", ())
886 for floating_network
in external_network
:
888 # wait until vm is active
890 while elapsed_time
< server_timeout
:
891 status
= self
.nova
.servers
.get(server
.id).status
892 if status
== 'ACTIVE':
897 #if we exceeded the timeout rollback
898 if elapsed_time
>= server_timeout
:
899 raise vimconn
.vimconnException('Timeout creating instance ' + name
,
900 http_code
=vimconn
.HTTP_Request_Timeout
)
903 while(assigned
== False):
905 ip
= floating_ips
.pop(0)
906 if not ip
.get("port_id", False) and ip
.get('tenant_id') == server
.tenant_id
:
907 free_floating_ip
= ip
.get("floating_ip_address")
909 fix_ip
= floating_network
.get('ip')
910 server
.add_floating_ip(free_floating_ip
, fix_ip
)
912 except Exception as e
:
913 raise vimconn
.vimconnException(type(e
).__name
__ + ": Cannot create floating_ip "+ str(e
), http_code
=vimconn
.HTTP_Conflict
)
915 #Find the external network
916 external_nets
= list()
917 for net
in self
.neutron
.list_networks()['networks']:
918 if net
['router:external']:
919 external_nets
.append(net
)
921 if len(external_nets
) == 0:
922 raise vimconn
.vimconnException("Cannot create floating_ip automatically since no external "
923 "network is present",
924 http_code
=vimconn
.HTTP_Conflict
)
925 if len(external_nets
) > 1:
926 raise vimconn
.vimconnException("Cannot create floating_ip automatically since multiple "
927 "external networks are present",
928 http_code
=vimconn
.HTTP_Conflict
)
930 pool_id
= external_nets
[0].get('id')
931 param
= {'floatingip': {'floating_network_id': pool_id
, 'tenant_id': server
.tenant_id
}}
933 #self.logger.debug("Creating floating IP")
934 new_floating_ip
= self
.neutron
.create_floatingip(param
)
935 free_floating_ip
= new_floating_ip
['floatingip']['floating_ip_address']
936 fix_ip
= floating_network
.get('ip')
937 server
.add_floating_ip(free_floating_ip
, fix_ip
)
939 except Exception as e
:
940 raise vimconn
.vimconnException(type(e
).__name
__ + ": Cannot assign floating_ip "+ str(e
), http_code
=vimconn
.HTTP_Conflict
)
941 except Exception as e
:
942 if not floating_network
['exit_on_floating_ip_error']:
943 self
.logger
.warn("Cannot create floating_ip. %s", str(e
))
945 self
.delete_vminstance(server
.id)
949 # except nvExceptions.NotFound as e:
950 # error_value=-vimconn.HTTP_Not_Found
951 # error_text= "vm instance %s not found" % vm_id
952 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
, ConnectionError
) as e
:
953 # delete the volumes we just created
954 if block_device_mapping
!= None:
955 for volume_id
in block_device_mapping
.itervalues():
956 self
.cinder
.volumes
.delete(volume_id
)
958 # delete ports we just created
959 for net_item
in net_list_vim
:
960 if 'port-id' in net_item
:
961 self
.neutron
.delete_port(net_item
['port-id'])
962 self
._format
_exception
(e
)
963 except TypeError as e
:
964 raise vimconn
.vimconnException(type(e
).__name
__ + ": "+ str(e
), http_code
=vimconn
.HTTP_Bad_Request
)
966 def get_vminstance(self
,vm_id
):
967 '''Returns the VM instance information from VIM'''
968 #self.logger.debug("Getting VM from VIM")
970 self
._reload
_connection
()
971 server
= self
.nova
.servers
.find(id=vm_id
)
972 #TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
973 return server
.to_dict()
974 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
, nvExceptions
.NotFound
, ConnectionError
) as e
:
975 self
._format
_exception
(e
)
977 def get_vminstance_console(self
,vm_id
, console_type
="vnc"):
979 Get a console for the virtual machine
981 vm_id: uuid of the VM
982 console_type, can be:
983 "novnc" (by default), "xvpvnc" for VNC types,
984 "rdp-html5" for RDP types, "spice-html5" for SPICE types
985 Returns dict with the console parameters:
986 protocol: ssh, ftp, http, https, ...
987 server: usually ip address
988 port: the http, ssh, ... port
989 suffix: extra text, e.g. the http path and query string
991 self
.logger
.debug("Getting VM CONSOLE from VIM")
993 self
._reload
_connection
()
994 server
= self
.nova
.servers
.find(id=vm_id
)
995 if console_type
== None or console_type
== "novnc":
996 console_dict
= server
.get_vnc_console("novnc")
997 elif console_type
== "xvpvnc":
998 console_dict
= server
.get_vnc_console(console_type
)
999 elif console_type
== "rdp-html5":
1000 console_dict
= server
.get_rdp_console(console_type
)
1001 elif console_type
== "spice-html5":
1002 console_dict
= server
.get_spice_console(console_type
)
1004 raise vimconn
.vimconnException("console type '{}' not allowed".format(console_type
), http_code
=vimconn
.HTTP_Bad_Request
)
1006 console_dict1
= console_dict
.get("console")
1008 console_url
= console_dict1
.get("url")
1011 protocol_index
= console_url
.find("//")
1012 suffix_index
= console_url
[protocol_index
+2:].find("/") + protocol_index
+2
1013 port_index
= console_url
[protocol_index
+2:suffix_index
].find(":") + protocol_index
+2
1014 if protocol_index
< 0 or port_index
<0 or suffix_index
<0:
1015 return -vimconn
.HTTP_Internal_Server_Error
, "Unexpected response from VIM"
1016 console_dict
={"protocol": console_url
[0:protocol_index
],
1017 "server": console_url
[protocol_index
+2:port_index
],
1018 "port": console_url
[port_index
:suffix_index
],
1019 "suffix": console_url
[suffix_index
+1:]
1023 raise vimconn
.vimconnUnexpectedResponse("Unexpected response from VIM")
1025 except (nvExceptions
.NotFound
, ksExceptions
.ClientException
, nvExceptions
.ClientException
, nvExceptions
.BadRequest
, ConnectionError
) as e
:
1026 self
._format
_exception
(e
)
1028 def delete_vminstance(self
, vm_id
):
1029 '''Removes a VM instance from VIM. Returns the old identifier
1031 #print "osconnector: Getting VM from VIM"
1033 self
._reload
_connection
()
1034 #delete VM ports attached to this networks before the virtual machine
1035 ports
= self
.neutron
.list_ports(device_id
=vm_id
)
1036 for p
in ports
['ports']:
1038 self
.neutron
.delete_port(p
["id"])
1039 except Exception as e
:
1040 self
.logger
.error("Error deleting port: " + type(e
).__name
__ + ": "+ str(e
))
1042 #commented because detaching the volumes makes the servers.delete not work properly ?!?
1043 #dettach volumes attached
1044 server
= self
.nova
.servers
.get(vm_id
)
1045 volumes_attached_dict
= server
._info
['os-extended-volumes:volumes_attached']
1046 #for volume in volumes_attached_dict:
1047 # self.cinder.volumes.detach(volume['id'])
1049 self
.nova
.servers
.delete(vm_id
)
1052 #Although having detached them should have them in active status
1053 #we ensure in this loop
1056 while keep_waiting
and elapsed_time
< volume_timeout
:
1057 keep_waiting
= False
1058 for volume
in volumes_attached_dict
:
1059 if self
.cinder
.volumes
.get(volume
['id']).status
!= 'available':
1062 self
.cinder
.volumes
.delete(volume
['id'])
1068 except (nvExceptions
.NotFound
, ksExceptions
.ClientException
, nvExceptions
.ClientException
, ConnectionError
) as e
:
1069 self
._format
_exception
(e
)
1070 #TODO insert exception vimconn.HTTP_Unauthorized
1071 #if reaching here is because an exception
1073 def refresh_vms_status(self
, vm_list
):
1074 '''Get the status of the virtual machines and their interfaces/ports
1075 Params: the list of VM identifiers
1076 Returns a dictionary with:
1077 vm_id: #VIM id of this Virtual Machine
1078 status: #Mandatory. Text with one of:
1079 # DELETED (not found at vim)
1080 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
1081 # OTHER (Vim reported other status not understood)
1082 # ERROR (VIM indicates an ERROR status)
1083 # ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running),
1084 # CREATING (on building process), ERROR
1085 # ACTIVE:NoMgmtIP (Active but any of its interface has an IP address
1087 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
1088 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
1090 - vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
1091 mac_address: #Text format XX:XX:XX:XX:XX:XX
1092 vim_net_id: #network id where this interface is connected
1093 vim_interface_id: #interface/port VIM id
1094 ip_address: #null, or text with IPv4, IPv6 address
1097 self
.logger
.debug("refresh_vms status: Getting tenant VM instance information from VIM")
1098 for vm_id
in vm_list
:
1101 vm_vim
= self
.get_vminstance(vm_id
)
1102 if vm_vim
['status'] in vmStatus2manoFormat
:
1103 vm
['status'] = vmStatus2manoFormat
[ vm_vim
['status'] ]
1105 vm
['status'] = "OTHER"
1106 vm
['error_msg'] = "VIM status reported " + vm_vim
['status']
1108 vm
['vim_info'] = yaml
.safe_dump(vm_vim
, default_flow_style
=True, width
=256)
1109 except yaml
.representer
.RepresenterError
:
1110 vm
['vim_info'] = str(vm_vim
)
1111 vm
["interfaces"] = []
1112 if vm_vim
.get('fault'):
1113 vm
['error_msg'] = str(vm_vim
['fault'])
1116 self
._reload
_connection
()
1117 port_dict
=self
.neutron
.list_ports(device_id
=vm_id
)
1118 for port
in port_dict
["ports"]:
1121 interface
['vim_info'] = yaml
.safe_dump(port
, default_flow_style
=True, width
=256)
1122 except yaml
.representer
.RepresenterError
:
1123 interface
['vim_info'] = str(port
)
1124 interface
["mac_address"] = port
.get("mac_address")
1125 interface
["vim_net_id"] = port
["network_id"]
1126 interface
["vim_interface_id"] = port
["id"]
1128 #look for floating ip address
1129 floating_ip_dict
= self
.neutron
.list_floatingips(port_id
=port
["id"])
1130 if floating_ip_dict
.get("floatingips"):
1131 ips
.append(floating_ip_dict
["floatingips"][0].get("floating_ip_address") )
1133 for subnet
in port
["fixed_ips"]:
1134 ips
.append(subnet
["ip_address"])
1135 interface
["ip_address"] = ";".join(ips
)
1136 vm
["interfaces"].append(interface
)
1137 except Exception as e
:
1138 self
.logger
.error("Error getting vm interface information " + type(e
).__name
__ + ": "+ str(e
))
1139 except vimconn
.vimconnNotFoundException
as e
:
1140 self
.logger
.error("Exception getting vm status: %s", str(e
))
1141 vm
['status'] = "DELETED"
1142 vm
['error_msg'] = str(e
)
1143 except vimconn
.vimconnException
as e
:
1144 self
.logger
.error("Exception getting vm status: %s", str(e
))
1145 vm
['status'] = "VIM_ERROR"
1146 vm
['error_msg'] = str(e
)
1150 def action_vminstance(self
, vm_id
, action_dict
):
1151 '''Send and action over a VM instance from VIM
1152 Returns the vm_id if the action was successfully sent to the VIM'''
1153 self
.logger
.debug("Action over VM '%s': %s", vm_id
, str(action_dict
))
1155 self
._reload
_connection
()
1156 server
= self
.nova
.servers
.find(id=vm_id
)
1157 if "start" in action_dict
:
1158 if action_dict
["start"]=="rebuild":
1161 if server
.status
=="PAUSED":
1163 elif server
.status
=="SUSPENDED":
1165 elif server
.status
=="SHUTOFF":
1167 elif "pause" in action_dict
:
1169 elif "resume" in action_dict
:
1171 elif "shutoff" in action_dict
or "shutdown" in action_dict
:
1173 elif "forceOff" in action_dict
:
1175 elif "terminate" in action_dict
:
1177 elif "createImage" in action_dict
:
1178 server
.create_image()
1179 #"path":path_schema,
1180 #"description":description_schema,
1181 #"name":name_schema,
1182 #"metadata":metadata_schema,
1183 #"imageRef": id_schema,
1184 #"disk": {"oneOf":[{"type": "null"}, {"type":"string"}] },
1185 elif "rebuild" in action_dict
:
1186 server
.rebuild(server
.image
['id'])
1187 elif "reboot" in action_dict
:
1188 server
.reboot() #reboot_type='SOFT'
1189 elif "console" in action_dict
:
1190 console_type
= action_dict
["console"]
1191 if console_type
== None or console_type
== "novnc":
1192 console_dict
= server
.get_vnc_console("novnc")
1193 elif console_type
== "xvpvnc":
1194 console_dict
= server
.get_vnc_console(console_type
)
1195 elif console_type
== "rdp-html5":
1196 console_dict
= server
.get_rdp_console(console_type
)
1197 elif console_type
== "spice-html5":
1198 console_dict
= server
.get_spice_console(console_type
)
1200 raise vimconn
.vimconnException("console type '{}' not allowed".format(console_type
),
1201 http_code
=vimconn
.HTTP_Bad_Request
)
1203 console_url
= console_dict
["console"]["url"]
1205 protocol_index
= console_url
.find("//")
1206 suffix_index
= console_url
[protocol_index
+2:].find("/") + protocol_index
+2
1207 port_index
= console_url
[protocol_index
+2:suffix_index
].find(":") + protocol_index
+2
1208 if protocol_index
< 0 or port_index
<0 or suffix_index
<0:
1209 raise vimconn
.vimconnException("Unexpected response from VIM " + str(console_dict
))
1210 console_dict2
={"protocol": console_url
[0:protocol_index
],
1211 "server": console_url
[protocol_index
+2 : port_index
],
1212 "port": int(console_url
[port_index
+1 : suffix_index
]),
1213 "suffix": console_url
[suffix_index
+1:]
1215 return console_dict2
1216 except Exception as e
:
1217 raise vimconn
.vimconnException("Unexpected response from VIM " + str(console_dict
))
1220 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
, nvExceptions
.NotFound
, ConnectionError
) as e
:
1221 self
._format
_exception
(e
)
1222 #TODO insert exception vimconn.HTTP_Unauthorized
1226 def new_external_port(self
, port_data
):
1227 #TODO openstack if needed
1228 '''Adds a external port to VIM'''
1229 '''Returns the port identifier'''
1230 return -vimconn
.HTTP_Internal_Server_Error
, "osconnector.new_external_port() not implemented"
1232 def connect_port_network(self
, port_id
, network_id
, admin
=False):
1233 #TODO openstack if needed
1234 '''Connects a external port to a network'''
1235 '''Returns status code of the VIM response'''
1236 return -vimconn
.HTTP_Internal_Server_Error
, "osconnector.connect_port_network() not implemented"
1238 def new_user(self
, user_name
, user_passwd
, tenant_id
=None):
1239 '''Adds a new user to openstack VIM'''
1240 '''Returns the user identifier'''
1241 self
.logger
.debug("osconnector: Adding a new user to VIM")
1243 self
._reload
_connection
()
1244 user
=self
.keystone
.users
.create(user_name
, user_passwd
, tenant_id
=tenant_id
)
1245 #self.keystone.tenants.add_user(self.k_creds["username"], #role)
1247 except ksExceptions
.ConnectionError
as e
:
1248 error_value
=-vimconn
.HTTP_Bad_Request
1249 error_text
= type(e
).__name
__ + ": "+ (str(e
) if len(e
.args
)==0 else str(e
.args
[0]))
1250 except ksExceptions
.ClientException
as e
: #TODO remove
1251 error_value
=-vimconn
.HTTP_Bad_Request
1252 error_text
= type(e
).__name
__ + ": "+ (str(e
) if len(e
.args
)==0 else str(e
.args
[0]))
1253 #TODO insert exception vimconn.HTTP_Unauthorized
1254 #if reaching here is because an exception
1256 self
.logger
.debug("new_user " + error_text
)
1257 return error_value
, error_text
1259 def delete_user(self
, user_id
):
1260 '''Delete a user from openstack VIM'''
1261 '''Returns the user identifier'''
1263 print "osconnector: Deleting a user from VIM"
1265 self
._reload
_connection
()
1266 self
.keystone
.users
.delete(user_id
)
1268 except ksExceptions
.ConnectionError
as e
:
1269 error_value
=-vimconn
.HTTP_Bad_Request
1270 error_text
= type(e
).__name
__ + ": "+ (str(e
) if len(e
.args
)==0 else str(e
.args
[0]))
1271 except ksExceptions
.NotFound
as e
:
1272 error_value
=-vimconn
.HTTP_Not_Found
1273 error_text
= type(e
).__name
__ + ": "+ (str(e
) if len(e
.args
)==0 else str(e
.args
[0]))
1274 except ksExceptions
.ClientException
as e
: #TODO remove
1275 error_value
=-vimconn
.HTTP_Bad_Request
1276 error_text
= type(e
).__name
__ + ": "+ (str(e
) if len(e
.args
)==0 else str(e
.args
[0]))
1277 #TODO insert exception vimconn.HTTP_Unauthorized
1278 #if reaching here is because an exception
1280 print "delete_tenant " + error_text
1281 return error_value
, error_text
1283 def get_hosts_info(self
):
1284 '''Get the information of deployed hosts
1285 Returns the hosts content'''
1287 print "osconnector: Getting Host info from VIM"
1290 self
._reload
_connection
()
1291 hypervisors
= self
.nova
.hypervisors
.list()
1292 for hype
in hypervisors
:
1293 h_list
.append( hype
.to_dict() )
1294 return 1, {"hosts":h_list
}
1295 except nvExceptions
.NotFound
as e
:
1296 error_value
=-vimconn
.HTTP_Not_Found
1297 error_text
= (str(e
) if len(e
.args
)==0 else str(e
.args
[0]))
1298 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
) as e
:
1299 error_value
=-vimconn
.HTTP_Bad_Request
1300 error_text
= type(e
).__name
__ + ": "+ (str(e
) if len(e
.args
)==0 else str(e
.args
[0]))
1301 #TODO insert exception vimconn.HTTP_Unauthorized
1302 #if reaching here is because an exception
1304 print "get_hosts_info " + error_text
1305 return error_value
, error_text
1307 def get_hosts(self
, vim_tenant
):
1308 '''Get the hosts and deployed instances
1309 Returns the hosts content'''
1310 r
, hype_dict
= self
.get_hosts_info()
1313 hypervisors
= hype_dict
["hosts"]
1315 servers
= self
.nova
.servers
.list()
1316 for hype
in hypervisors
:
1317 for server
in servers
:
1318 if server
.to_dict()['OS-EXT-SRV-ATTR:hypervisor_hostname']==hype
['hypervisor_hostname']:
1320 hype
['vm'].append(server
.id)
1322 hype
['vm'] = [server
.id]
1324 except nvExceptions
.NotFound
as e
:
1325 error_value
=-vimconn
.HTTP_Not_Found
1326 error_text
= (str(e
) if len(e
.args
)==0 else str(e
.args
[0]))
1327 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
) as e
:
1328 error_value
=-vimconn
.HTTP_Bad_Request
1329 error_text
= type(e
).__name
__ + ": "+ (str(e
) if len(e
.args
)==0 else str(e
.args
[0]))
1330 #TODO insert exception vimconn.HTTP_Unauthorized
1331 #if reaching here is because an exception
1333 print "get_hosts " + error_text
1334 return error_value
, error_text