Bug 194 - Openstack API v3.3
[osm/RO.git] / vimconn_openstack.py
1 # -*- coding: utf-8 -*-
2
3 ##
4 # Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U.
5 # This file is part of openmano
6 # All Rights Reserved.
7 #
8 # Licensed under the Apache License, Version 2.0 (the "License"); you may
9 # not use this file except in compliance with the License. You may obtain
10 # a copy of the License at
11 #
12 # http://www.apache.org/licenses/LICENSE-2.0
13 #
14 # Unless required by applicable law or agreed to in writing, software
15 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17 # License for the specific language governing permissions and limitations
18 # under the License.
19 #
20 # For those usages not covered by the Apache License, Version 2.0 please
21 # contact with: nfvlabs@tid.es
22 ##
23
24 '''
25 osconnector implements all the methods to interact with openstack using the python-client.
26 '''
27 __author__="Alfonso Tierno, Gerardo Garcia, Pablo Montes, xFlow Research"
28 __date__ ="$22-jun-2014 11:19:29$"
29
30 import vimconn
31 import json
32 import yaml
33 import logging
34 import netaddr
35 import time
36 import yaml
37
38 from novaclient import client as nClient_v2, exceptions as nvExceptions
39 from novaclient import api_versions
40 import keystoneclient.v2_0.client as ksClient_v2
41 from novaclient.v2.client import Client as nClient
42 import keystoneclient.v3.client as ksClient
43 import keystoneclient.exceptions as ksExceptions
44 import glanceclient.v2.client as glClient
45 import glanceclient.client as gl1Client
46 import glanceclient.exc as gl1Exceptions
47 import cinderclient.v2.client as cClient_v2
48 from httplib import HTTPException
49 from neutronclient.neutron import client as neClient_v2
50 from neutronclient.v2_0 import client as neClient
51 from neutronclient.common import exceptions as neExceptions
52 from requests.exceptions import ConnectionError
53
54 '''contain the openstack virtual machine status to openmano status'''
55 vmStatus2manoFormat={'ACTIVE':'ACTIVE',
56 'PAUSED':'PAUSED',
57 'SUSPENDED': 'SUSPENDED',
58 'SHUTOFF':'INACTIVE',
59 'BUILD':'BUILD',
60 'ERROR':'ERROR','DELETED':'DELETED'
61 }
62 netStatus2manoFormat={'ACTIVE':'ACTIVE','PAUSED':'PAUSED','INACTIVE':'INACTIVE','BUILD':'BUILD','ERROR':'ERROR','DELETED':'DELETED'
63 }
64
65 #global var to have a timeout creating and deleting volumes
66 volume_timeout = 60
67 server_timeout = 60
68
69 class vimconnector(vimconn.vimconnector):
70 def __init__(self, uuid, name, tenant_id, tenant_name, url, url_admin=None, user=None, passwd=None, log_level=None, config={}):
71 '''using common constructor parameters. In this case
72 'url' is the keystone authorization url,
73 'url_admin' is not use
74 '''
75 self.osc_api_version = 'v2.0'
76 if config.get('APIversion') == 'v3.3':
77 self.osc_api_version = 'v3.3'
78 vimconn.vimconnector.__init__(self, uuid, name, tenant_id, tenant_name, url, url_admin, user, passwd, log_level, config)
79
80 self.k_creds={}
81 self.n_creds={}
82 if not url:
83 raise TypeError, 'url param can not be NoneType'
84 self.k_creds['auth_url'] = url
85 self.n_creds['auth_url'] = url
86 if tenant_name:
87 self.k_creds['tenant_name'] = tenant_name
88 self.n_creds['project_id'] = tenant_name
89 if tenant_id:
90 self.k_creds['tenant_id'] = tenant_id
91 self.n_creds['tenant_id'] = tenant_id
92 if user:
93 self.k_creds['username'] = user
94 self.n_creds['username'] = user
95 if passwd:
96 self.k_creds['password'] = passwd
97 self.n_creds['api_key'] = passwd
98 if self.osc_api_version == 'v3.3':
99 self.k_creds['project_name'] = tenant_name
100 self.k_creds['project_id'] = tenant_id
101 if config.get('region_name'):
102 self.k_creds['region_name'] = config.get('region_name')
103 self.n_creds['region_name'] = config.get('region_name')
104
105 self.reload_client = True
106 self.logger = logging.getLogger('openmano.vim.openstack')
107 if log_level:
108 self.logger.setLevel( getattr(logging, log_level) )
109
110 def __setitem__(self,index, value):
111 '''Set individuals parameters
112 Throw TypeError, KeyError
113 '''
114 if index=='tenant_id':
115 self.reload_client=True
116 self.tenant_id = value
117 if self.osc_api_version == 'v3.3':
118 if value:
119 self.k_creds['project_id'] = value
120 self.n_creds['project_id'] = value
121 else:
122 del self.k_creds['project_id']
123 del self.n_creds['project_id']
124 else:
125 if value:
126 self.k_creds['tenant_id'] = value
127 self.n_creds['tenant_id'] = value
128 else:
129 del self.k_creds['tenant_id']
130 del self.n_creds['tenant_id']
131 elif index=='tenant_name':
132 self.reload_client=True
133 self.tenant_name = value
134 if self.osc_api_version == 'v3.3':
135 if value:
136 self.k_creds['project_name'] = value
137 self.n_creds['project_name'] = value
138 else:
139 del self.k_creds['project_name']
140 del self.n_creds['project_name']
141 else:
142 if value:
143 self.k_creds['tenant_name'] = value
144 self.n_creds['project_id'] = value
145 else:
146 del self.k_creds['tenant_name']
147 del self.n_creds['project_id']
148 elif index=='user':
149 self.reload_client=True
150 self.user = value
151 if value:
152 self.k_creds['username'] = value
153 self.n_creds['username'] = value
154 else:
155 del self.k_creds['username']
156 del self.n_creds['username']
157 elif index=='passwd':
158 self.reload_client=True
159 self.passwd = value
160 if value:
161 self.k_creds['password'] = value
162 self.n_creds['api_key'] = value
163 else:
164 del self.k_creds['password']
165 del self.n_creds['api_key']
166 elif index=='url':
167 self.reload_client=True
168 self.url = value
169 if value:
170 self.k_creds['auth_url'] = value
171 self.n_creds['auth_url'] = value
172 else:
173 raise TypeError, 'url param can not be NoneType'
174 else:
175 vimconn.vimconnector.__setitem__(self,index, value)
176
177 def _reload_connection(self):
178 '''Called before any operation, it check if credentials has changed
179 Throw keystoneclient.apiclient.exceptions.AuthorizationFailure
180 '''
181 #TODO control the timing and possible token timeout, but it seams that python client does this task for us :-)
182 if self.reload_client:
183 #test valid params
184 if len(self.n_creds) <4:
185 raise ksExceptions.ClientException("Not enough parameters to connect to openstack")
186 if self.osc_api_version == 'v3.3':
187 self.nova = nClient(api_version=api_versions.APIVersion(version_str='2.0'), **self.n_creds)
188 #TODO To be updated for v3
189 #self.cinder = cClient.Client(**self.n_creds)
190 self.keystone = ksClient.Client(**self.k_creds)
191 self.ne_endpoint=self.keystone.service_catalog.url_for(service_type='network', endpoint_type='publicURL')
192 self.neutron = neClient.Client(api_version=api_versions.APIVersion(version_str='2.0'), endpoint_url=self.ne_endpoint, token=self.keystone.auth_token, **self.k_creds)
193 else:
194 self.nova = nClient_v2.Client(version='2', **self.n_creds)
195 self.cinder = cClient_v2.Client(**self.n_creds)
196 self.keystone = ksClient_v2.Client(**self.k_creds)
197 self.ne_endpoint=self.keystone.service_catalog.url_for(service_type='network', endpoint_type='publicURL')
198 self.neutron = neClient_v2.Client('2.0', endpoint_url=self.ne_endpoint, token=self.keystone.auth_token, **self.k_creds)
199 self.glance_endpoint = self.keystone.service_catalog.url_for(service_type='image', endpoint_type='publicURL')
200 self.glance = glClient.Client(self.glance_endpoint, token=self.keystone.auth_token, **self.k_creds) #TODO check k_creds vs n_creds
201 self.reload_client = False
202
203 def __net_os2mano(self, net_list_dict):
204 '''Transform the net openstack format to mano format
205 net_list_dict can be a list of dict or a single dict'''
206 if type(net_list_dict) is dict:
207 net_list_=(net_list_dict,)
208 elif type(net_list_dict) is list:
209 net_list_=net_list_dict
210 else:
211 raise TypeError("param net_list_dict must be a list or a dictionary")
212 for net in net_list_:
213 if net.get('provider:network_type') == "vlan":
214 net['type']='data'
215 else:
216 net['type']='bridge'
217
218
219
220 def _format_exception(self, exception):
221 '''Transform a keystone, nova, neutron exception into a vimconn exception'''
222 if isinstance(exception, (HTTPException, gl1Exceptions.HTTPException, gl1Exceptions.CommunicationError,
223 ConnectionError, ksExceptions.ConnectionError, neExceptions.ConnectionFailed
224 )):
225 raise vimconn.vimconnConnectionException(type(exception).__name__ + ": " + str(exception))
226 elif isinstance(exception, (nvExceptions.ClientException, ksExceptions.ClientException,
227 neExceptions.NeutronException, nvExceptions.BadRequest)):
228 raise vimconn.vimconnUnexpectedResponse(type(exception).__name__ + ": " + str(exception))
229 elif isinstance(exception, (neExceptions.NetworkNotFoundClient, nvExceptions.NotFound)):
230 raise vimconn.vimconnNotFoundException(type(exception).__name__ + ": " + str(exception))
231 elif isinstance(exception, nvExceptions.Conflict):
232 raise vimconn.vimconnConflictException(type(exception).__name__ + ": " + str(exception))
233 else: # ()
234 raise vimconn.vimconnConnectionException(type(exception).__name__ + ": " + str(exception))
235
236 def get_tenant_list(self, filter_dict={}):
237 '''Obtain tenants of VIM
238 filter_dict can contain the following keys:
239 name: filter by tenant name
240 id: filter by tenant uuid/id
241 <other VIM specific>
242 Returns the tenant list of dictionaries: [{'name':'<name>, 'id':'<id>, ...}, ...]
243 '''
244 self.logger.debug("Getting tenants from VIM filter: '%s'", str(filter_dict))
245 try:
246 self._reload_connection()
247 if self.osc_api_version == 'v3.3':
248 project_class_list=self.keystone.projects.findall(**filter_dict)
249 else:
250 project_class_list=self.keystone.tenants.findall(**filter_dict)
251 project_list=[]
252 for project in project_class_list:
253 project_list.append(project.to_dict())
254 return project_list
255 except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e:
256 self._format_exception(e)
257
258 def new_tenant(self, tenant_name, tenant_description):
259 '''Adds a new tenant to openstack VIM. Returns the tenant identifier'''
260 self.logger.debug("Adding a new tenant name: %s", tenant_name)
261 try:
262 self._reload_connection()
263 if self.osc_api_version == 'v3.3':
264 project=self.keystone.projects.create(tenant_name, tenant_description)
265 else:
266 project=self.keystone.tenants.create(tenant_name, tenant_description)
267 return project.id
268 except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e:
269 self._format_exception(e)
270
271 def delete_tenant(self, tenant_id):
272 '''Delete a tenant from openstack VIM. Returns the old tenant identifier'''
273 self.logger.debug("Deleting tenant %s from VIM", tenant_id)
274 try:
275 self._reload_connection()
276 if self.osc_api_version == 'v3.3':
277 self.keystone.projects.delete(tenant_id)
278 else:
279 self.keystone.tenants.delete(tenant_id)
280 return tenant_id
281 except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e:
282 self._format_exception(e)
283
284 def new_network(self,net_name, net_type, ip_profile=None, shared=False, vlan=None):
285 '''Adds a tenant network to VIM. Returns the network identifier'''
286 self.logger.debug("Adding a new network to VIM name '%s', type '%s'", net_name, net_type)
287 #self.logger.debug(">>>>>>>>>>>>>>>>>> IP profile %s", str(ip_profile))
288 try:
289 new_net = None
290 self._reload_connection()
291 network_dict = {'name': net_name, 'admin_state_up': True}
292 if net_type=="data" or net_type=="ptp":
293 if self.config.get('dataplane_physical_net') == None:
294 raise vimconn.vimconnConflictException("You must provide a 'dataplane_physical_net' at config value before creating sriov network")
295 network_dict["provider:physical_network"] = self.config['dataplane_physical_net'] #"physnet_sriov" #TODO physical
296 network_dict["provider:network_type"] = "vlan"
297 if vlan!=None:
298 network_dict["provider:network_type"] = vlan
299 network_dict["shared"]=shared
300 new_net=self.neutron.create_network({'network':network_dict})
301 #print new_net
302 #create subnetwork, even if there is no profile
303 if not ip_profile:
304 ip_profile = {}
305 if 'subnet_address' not in ip_profile:
306 #Fake subnet is required
307 ip_profile['subnet_address'] = "192.168.111.0/24"
308 if 'ip_version' not in ip_profile:
309 ip_profile['ip_version'] = "IPv4"
310 subnet={"name":net_name+"-subnet",
311 "network_id": new_net["network"]["id"],
312 "ip_version": 4 if ip_profile['ip_version']=="IPv4" else 6,
313 "cidr": ip_profile['subnet_address']
314 }
315 if 'gateway_address' in ip_profile:
316 subnet['gateway_ip'] = ip_profile['gateway_address']
317 if ip_profile.get('dns_address'):
318 #TODO: manage dns_address as a list of addresses separated by commas
319 subnet['dns_nameservers'] = []
320 subnet['dns_nameservers'].append(ip_profile['dns_address'])
321 if 'dhcp_enabled' in ip_profile:
322 subnet['enable_dhcp'] = False if ip_profile['dhcp_enabled']=="false" else True
323 if 'dhcp_start_address' in ip_profile:
324 subnet['allocation_pools']=[]
325 subnet['allocation_pools'].append(dict())
326 subnet['allocation_pools'][0]['start'] = ip_profile['dhcp_start_address']
327 if 'dhcp_count' in ip_profile:
328 #parts = ip_profile['dhcp_start_address'].split('.')
329 #ip_int = (int(parts[0]) << 24) + (int(parts[1]) << 16) + (int(parts[2]) << 8) + int(parts[3])
330 ip_int = int(netaddr.IPAddress(ip_profile['dhcp_start_address']))
331 ip_int += ip_profile['dhcp_count'] - 1
332 ip_str = str(netaddr.IPAddress(ip_int))
333 subnet['allocation_pools'][0]['end'] = ip_str
334 #self.logger.debug(">>>>>>>>>>>>>>>>>> Subnet: %s", str(subnet))
335 self.neutron.create_subnet({"subnet": subnet} )
336 return new_net["network"]["id"]
337 except (neExceptions.ConnectionFailed, ksExceptions.ClientException, neExceptions.NeutronException, ConnectionError) as e:
338 if new_net:
339 self.neutron.delete_network(new_net['network']['id'])
340 self._format_exception(e)
341
342 def get_network_list(self, filter_dict={}):
343 '''Obtain tenant networks of VIM
344 Filter_dict can be:
345 name: network name
346 id: network uuid
347 shared: boolean
348 tenant_id: tenant
349 admin_state_up: boolean
350 status: 'ACTIVE'
351 Returns the network list of dictionaries
352 '''
353 self.logger.debug("Getting network from VIM filter: '%s'", str(filter_dict))
354 try:
355 self._reload_connection()
356 if self.osc_api_version == 'v3.3' and "tenant_id" in filter_dict:
357 filter_dict['project_id'] = filter_dict.pop('tenant_id')
358 net_dict=self.neutron.list_networks(**filter_dict)
359 net_list=net_dict["networks"]
360 self.__net_os2mano(net_list)
361 return net_list
362 except (neExceptions.ConnectionFailed, ksExceptions.ClientException, neExceptions.NeutronException, ConnectionError) as e:
363 self._format_exception(e)
364
365 def get_network(self, net_id):
366 '''Obtain details of network from VIM
367 Returns the network information from a network id'''
368 self.logger.debug(" Getting tenant network %s from VIM", net_id)
369 filter_dict={"id": net_id}
370 net_list = self.get_network_list(filter_dict)
371 if len(net_list)==0:
372 raise vimconn.vimconnNotFoundException("Network '{}' not found".format(net_id))
373 elif len(net_list)>1:
374 raise vimconn.vimconnConflictException("Found more than one network with this criteria")
375 net = net_list[0]
376 subnets=[]
377 for subnet_id in net.get("subnets", () ):
378 try:
379 subnet = self.neutron.show_subnet(subnet_id)
380 except Exception as e:
381 self.logger.error("osconnector.get_network(): Error getting subnet %s %s" % (net_id, str(e)))
382 subnet = {"id": subnet_id, "fault": str(e)}
383 subnets.append(subnet)
384 net["subnets"] = subnets
385 return net
386
387 def delete_network(self, net_id):
388 '''Deletes a tenant network from VIM. Returns the old network identifier'''
389 self.logger.debug("Deleting network '%s' from VIM", net_id)
390 try:
391 self._reload_connection()
392 #delete VM ports attached to this networks before the network
393 ports = self.neutron.list_ports(network_id=net_id)
394 for p in ports['ports']:
395 try:
396 self.neutron.delete_port(p["id"])
397 except Exception as e:
398 self.logger.error("Error deleting port %s: %s", p["id"], str(e))
399 self.neutron.delete_network(net_id)
400 return net_id
401 except (neExceptions.ConnectionFailed, neExceptions.NetworkNotFoundClient, neExceptions.NeutronException,
402 ksExceptions.ClientException, neExceptions.NeutronException, ConnectionError) as e:
403 self._format_exception(e)
404
405 def refresh_nets_status(self, net_list):
406 '''Get the status of the networks
407 Params: the list of network identifiers
408 Returns a dictionary with:
409 net_id: #VIM id of this network
410 status: #Mandatory. Text with one of:
411 # DELETED (not found at vim)
412 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
413 # OTHER (Vim reported other status not understood)
414 # ERROR (VIM indicates an ERROR status)
415 # ACTIVE, INACTIVE, DOWN (admin down),
416 # BUILD (on building process)
417 #
418 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
419 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
420
421 '''
422 net_dict={}
423 for net_id in net_list:
424 net = {}
425 try:
426 net_vim = self.get_network(net_id)
427 if net_vim['status'] in netStatus2manoFormat:
428 net["status"] = netStatus2manoFormat[ net_vim['status'] ]
429 else:
430 net["status"] = "OTHER"
431 net["error_msg"] = "VIM status reported " + net_vim['status']
432
433 if net['status'] == "ACTIVE" and not net_vim['admin_state_up']:
434 net['status'] = 'DOWN'
435 try:
436 net['vim_info'] = yaml.safe_dump(net_vim, default_flow_style=True, width=256)
437 except yaml.representer.RepresenterError:
438 net['vim_info'] = str(net_vim)
439 if net_vim.get('fault'): #TODO
440 net['error_msg'] = str(net_vim['fault'])
441 except vimconn.vimconnNotFoundException as e:
442 self.logger.error("Exception getting net status: %s", str(e))
443 net['status'] = "DELETED"
444 net['error_msg'] = str(e)
445 except vimconn.vimconnException as e:
446 self.logger.error("Exception getting net status: %s", str(e))
447 net['status'] = "VIM_ERROR"
448 net['error_msg'] = str(e)
449 net_dict[net_id] = net
450 return net_dict
451
452 def get_flavor(self, flavor_id):
453 '''Obtain flavor details from the VIM. Returns the flavor dict details'''
454 self.logger.debug("Getting flavor '%s'", flavor_id)
455 try:
456 self._reload_connection()
457 flavor = self.nova.flavors.find(id=flavor_id)
458 #TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
459 return flavor.to_dict()
460 except (nvExceptions.NotFound, nvExceptions.ClientException, ksExceptions.ClientException, ConnectionError) as e:
461 self._format_exception(e)
462
463 def new_flavor(self, flavor_data, change_name_if_used=True):
464 '''Adds a tenant flavor to openstack VIM
465 if change_name_if_used is True, it will change name in case of conflict, because it is not supported name repetition
466 Returns the flavor identifier
467 '''
468 self.logger.debug("Adding flavor '%s'", str(flavor_data))
469 retry=0
470 max_retries=3
471 name_suffix = 0
472 name=flavor_data['name']
473 while retry<max_retries:
474 retry+=1
475 try:
476 self._reload_connection()
477 if change_name_if_used:
478 #get used names
479 fl_names=[]
480 fl=self.nova.flavors.list()
481 for f in fl:
482 fl_names.append(f.name)
483 while name in fl_names:
484 name_suffix += 1
485 name = flavor_data['name']+"-" + str(name_suffix)
486
487 ram = flavor_data.get('ram',64)
488 vcpus = flavor_data.get('vcpus',1)
489 numa_properties=None
490
491 extended = flavor_data.get("extended")
492 if extended:
493 numas=extended.get("numas")
494 if numas:
495 numa_nodes = len(numas)
496 if numa_nodes > 1:
497 return -1, "Can not add flavor with more than one numa"
498 numa_properties = {"hw:numa_nodes":str(numa_nodes)}
499 numa_properties["hw:mem_page_size"] = "large"
500 numa_properties["hw:cpu_policy"] = "dedicated"
501 numa_properties["hw:numa_mempolicy"] = "strict"
502 for numa in numas:
503 #overwrite ram and vcpus
504 ram = numa['memory']*1024
505 if 'paired-threads' in numa:
506 vcpus = numa['paired-threads']*2
507 numa_properties["hw:cpu_threads_policy"] = "prefer"
508 elif 'cores' in numa:
509 vcpus = numa['cores']
510 #numa_properties["hw:cpu_threads_policy"] = "prefer"
511 elif 'threads' in numa:
512 vcpus = numa['threads']
513 numa_properties["hw:cpu_policy"] = "isolated"
514 for interface in numa.get("interfaces",() ):
515 if interface["dedicated"]=="yes":
516 raise vimconn.vimconnException("Passthrough interfaces are not supported for the openstack connector", http_code=vimconn.HTTP_Service_Unavailable)
517 #TODO, add the key 'pci_passthrough:alias"="<label at config>:<number ifaces>"' when a way to connect it is available
518
519 #create flavor
520 new_flavor=self.nova.flavors.create(name,
521 ram,
522 vcpus,
523 flavor_data.get('disk',1),
524 is_public=flavor_data.get('is_public', True)
525 )
526 #add metadata
527 if numa_properties:
528 new_flavor.set_keys(numa_properties)
529 return new_flavor.id
530 except nvExceptions.Conflict as e:
531 if change_name_if_used and retry < max_retries:
532 continue
533 self._format_exception(e)
534 #except nvExceptions.BadRequest as e:
535 except (ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e:
536 self._format_exception(e)
537
538 def delete_flavor(self,flavor_id):
539 '''Deletes a tenant flavor from openstack VIM. Returns the old flavor_id
540 '''
541 try:
542 self._reload_connection()
543 self.nova.flavors.delete(flavor_id)
544 return flavor_id
545 #except nvExceptions.BadRequest as e:
546 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e:
547 self._format_exception(e)
548
549 def new_image(self,image_dict):
550 '''
551 Adds a tenant image to VIM. imge_dict is a dictionary with:
552 name: name
553 disk_format: qcow2, vhd, vmdk, raw (by default), ...
554 location: path or URI
555 public: "yes" or "no"
556 metadata: metadata of the image
557 Returns the image_id
558 '''
559 #using version 1 of glance client
560 glancev1 = gl1Client.Client('1',self.glance_endpoint, token=self.keystone.auth_token, **self.k_creds) #TODO check k_creds vs n_creds
561 retry=0
562 max_retries=3
563 while retry<max_retries:
564 retry+=1
565 try:
566 self._reload_connection()
567 #determine format http://docs.openstack.org/developer/glance/formats.html
568 if "disk_format" in image_dict:
569 disk_format=image_dict["disk_format"]
570 else: #autodiscover based on extension
571 if image_dict['location'][-6:]==".qcow2":
572 disk_format="qcow2"
573 elif image_dict['location'][-4:]==".vhd":
574 disk_format="vhd"
575 elif image_dict['location'][-5:]==".vmdk":
576 disk_format="vmdk"
577 elif image_dict['location'][-4:]==".vdi":
578 disk_format="vdi"
579 elif image_dict['location'][-4:]==".iso":
580 disk_format="iso"
581 elif image_dict['location'][-4:]==".aki":
582 disk_format="aki"
583 elif image_dict['location'][-4:]==".ari":
584 disk_format="ari"
585 elif image_dict['location'][-4:]==".ami":
586 disk_format="ami"
587 else:
588 disk_format="raw"
589 self.logger.debug("new_image: '%s' loading from '%s'", image_dict['name'], image_dict['location'])
590 if image_dict['location'][0:4]=="http":
591 new_image = glancev1.images.create(name=image_dict['name'], is_public=image_dict.get('public',"yes")=="yes",
592 container_format="bare", location=image_dict['location'], disk_format=disk_format)
593 else: #local path
594 with open(image_dict['location']) as fimage:
595 new_image = glancev1.images.create(name=image_dict['name'], is_public=image_dict.get('public',"yes")=="yes",
596 container_format="bare", data=fimage, disk_format=disk_format)
597 #insert metadata. We cannot use 'new_image.properties.setdefault'
598 #because nova and glance are "INDEPENDENT" and we are using nova for reading metadata
599 new_image_nova=self.nova.images.find(id=new_image.id)
600 new_image_nova.metadata.setdefault('location',image_dict['location'])
601 metadata_to_load = image_dict.get('metadata')
602 if metadata_to_load:
603 for k,v in yaml.load(metadata_to_load).iteritems():
604 new_image_nova.metadata.setdefault(k,v)
605 return new_image.id
606 except (nvExceptions.Conflict, ksExceptions.ClientException, nvExceptions.ClientException) as e:
607 self._format_exception(e)
608 except (HTTPException, gl1Exceptions.HTTPException, gl1Exceptions.CommunicationError, ConnectionError) as e:
609 if retry==max_retries:
610 continue
611 self._format_exception(e)
612 except IOError as e: #can not open the file
613 raise vimconn.vimconnConnectionException(type(e).__name__ + ": " + str(e)+ " for " + image_dict['location'],
614 http_code=vimconn.HTTP_Bad_Request)
615
616 def delete_image(self, image_id):
617 '''Deletes a tenant image from openstack VIM. Returns the old id
618 '''
619 try:
620 self._reload_connection()
621 self.nova.images.delete(image_id)
622 return image_id
623 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e: #TODO remove
624 self._format_exception(e)
625
626 def get_image_id_from_path(self, path):
627 '''Get the image id from image path in the VIM database. Returns the image_id'''
628 try:
629 self._reload_connection()
630 images = self.nova.images.list()
631 for image in images:
632 if image.metadata.get("location")==path:
633 return image.id
634 raise vimconn.vimconnNotFoundException("image with location '{}' not found".format( path))
635 except (ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e:
636 self._format_exception(e)
637
638 def get_image_list(self, filter_dict={}):
639 '''Obtain tenant images from VIM
640 Filter_dict can be:
641 id: image id
642 name: image name
643 checksum: image checksum
644 Returns the image list of dictionaries:
645 [{<the fields at Filter_dict plus some VIM specific>}, ...]
646 List can be empty
647 '''
648 self.logger.debug("Getting image list from VIM filter: '%s'", str(filter_dict))
649 try:
650 self._reload_connection()
651 filter_dict_os=filter_dict.copy()
652 #First we filter by the available filter fields: name, id. The others are removed.
653 filter_dict_os.pop('checksum',None)
654 image_list=self.nova.images.findall(**filter_dict_os)
655 if len(image_list)==0:
656 return []
657 #Then we filter by the rest of filter fields: checksum
658 filtered_list = []
659 for image in image_list:
660 image_dict=self.glance.images.get(image.id)
661 if 'checksum' not in filter_dict or image_dict['checksum']==filter_dict.get('checksum'):
662 filtered_list.append(image_dict)
663 return filtered_list
664 except (ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e:
665 self._format_exception(e)
666
667 def new_vminstance(self,name,description,start,image_id,flavor_id,net_list,cloud_config=None,disk_list=None):
668 '''Adds a VM instance to VIM
669 Params:
670 start: indicates if VM must start or boot in pause mode. Ignored
671 image_id,flavor_id: iamge and flavor uuid
672 net_list: list of interfaces, each one is a dictionary with:
673 name:
674 net_id: network uuid to connect
675 vpci: virtual vcpi to assign, ignored because openstack lack #TODO
676 model: interface model, ignored #TODO
677 mac_address: used for SR-IOV ifaces #TODO for other types
678 use: 'data', 'bridge', 'mgmt'
679 type: 'virtual', 'PF', 'VF', 'VFnotShared'
680 vim_id: filled/added by this function
681 floating_ip: True/False (or it can be None)
682 #TODO ip, security groups
683 Returns the instance identifier
684 '''
685 self.logger.debug("Creating VM image '%s' flavor '%s' nics='%s'",image_id, flavor_id,str(net_list))
686 try:
687 metadata={}
688 net_list_vim=[]
689 external_network=[] #list of external networks to be connected to instance, later on used to create floating_ip
690 self._reload_connection()
691 metadata_vpci={} #For a specific neutron plugin
692 for net in net_list:
693 if not net.get("net_id"): #skip non connected iface
694 continue
695 if net["type"]=="virtual" or net["type"]=="VF":
696 port_dict={
697 "network_id": net["net_id"],
698 "name": net.get("name"),
699 "admin_state_up": True
700 }
701 if net["type"]=="virtual":
702 if "vpci" in net:
703 metadata_vpci[ net["net_id"] ] = [[ net["vpci"], "" ]]
704 else: # for VF
705 if "vpci" in net:
706 if "VF" not in metadata_vpci:
707 metadata_vpci["VF"]=[]
708 metadata_vpci["VF"].append([ net["vpci"], "" ])
709 port_dict["binding:vnic_type"]="direct"
710 if not port_dict["name"]:
711 port_dict["name"]=name
712 if net.get("mac_address"):
713 port_dict["mac_address"]=net["mac_address"]
714 if net.get("port_security") == False:
715 port_dict["port_security_enabled"]=net["port_security"]
716 new_port = self.neutron.create_port({"port": port_dict })
717 net["mac_adress"] = new_port["port"]["mac_address"]
718 net["vim_id"] = new_port["port"]["id"]
719 net["ip"] = new_port["port"].get("fixed_ips", [{}])[0].get("ip_address")
720 net_list_vim.append({"port-id": new_port["port"]["id"]})
721 else: # for PF
722 self.logger.warn("new_vminstance: Warning, can not connect a passthrough interface ")
723 #TODO insert this when openstack consider passthrough ports as openstack neutron ports
724 if net.get('floating_ip', False):
725 external_network.append(net)
726
727 if metadata_vpci:
728 metadata = {"pci_assignement": json.dumps(metadata_vpci)}
729 if len(metadata["pci_assignement"]) >255:
730 #limit the metadata size
731 #metadata["pci_assignement"] = metadata["pci_assignement"][0:255]
732 self.logger.warn("Metadata deleted since it exceeds the expected length (255) ")
733 metadata = {}
734
735 self.logger.debug("name '%s' image_id '%s'flavor_id '%s' net_list_vim '%s' description '%s' metadata %s",
736 name, image_id, flavor_id, str(net_list_vim), description, str(metadata))
737
738 security_groups = self.config.get('security_groups')
739 if type(security_groups) is str:
740 security_groups = ( security_groups, )
741 #cloud config
742 userdata=None
743 config_drive = None
744 if isinstance(cloud_config, dict):
745 if cloud_config.get("user-data"):
746 userdata=cloud_config["user-data"]
747 if cloud_config.get("boot-data-drive") != None:
748 config_drive = cloud_config["boot-data-drive"]
749 if cloud_config.get("config-files") or cloud_config.get("users") or cloud_config.get("key-pairs"):
750 if userdata:
751 raise vimconn.vimconnConflictException("Cloud-config cannot contain both 'userdata' and 'config-files'/'users'/'key-pairs'")
752 userdata_dict={}
753 #default user
754 if cloud_config.get("key-pairs"):
755 userdata_dict["ssh-authorized-keys"] = cloud_config["key-pairs"]
756 userdata_dict["users"] = [{"default": None, "ssh-authorized-keys": cloud_config["key-pairs"] }]
757 if cloud_config.get("users"):
758 if "users" not in cloud_config:
759 userdata_dict["users"] = [ "default" ]
760 for user in cloud_config["users"]:
761 user_info = {
762 "name" : user["name"],
763 "sudo": "ALL = (ALL)NOPASSWD:ALL"
764 }
765 if "user-info" in user:
766 user_info["gecos"] = user["user-info"]
767 if user.get("key-pairs"):
768 user_info["ssh-authorized-keys"] = user["key-pairs"]
769 userdata_dict["users"].append(user_info)
770
771 if cloud_config.get("config-files"):
772 userdata_dict["write_files"] = []
773 for file in cloud_config["config-files"]:
774 file_info = {
775 "path" : file["dest"],
776 "content": file["content"]
777 }
778 if file.get("encoding"):
779 file_info["encoding"] = file["encoding"]
780 if file.get("permissions"):
781 file_info["permissions"] = file["permissions"]
782 if file.get("owner"):
783 file_info["owner"] = file["owner"]
784 userdata_dict["write_files"].append(file_info)
785 userdata = "#cloud-config\n"
786 userdata += yaml.safe_dump(userdata_dict, indent=4, default_flow_style=False)
787 self.logger.debug("userdata: %s", userdata)
788 elif isinstance(cloud_config, str):
789 userdata = cloud_config
790
791 #Create additional volumes in case these are present in disk_list
792 block_device_mapping = None
793 base_disk_index = ord('b')
794 if disk_list != None:
795 block_device_mapping = dict()
796 for disk in disk_list:
797 if 'image_id' in disk:
798 volume = self.cinder.volumes.create(size = disk['size'],name = name + '_vd' +
799 chr(base_disk_index), imageRef = disk['image_id'])
800 else:
801 volume = self.cinder.volumes.create(size=disk['size'], name=name + '_vd' +
802 chr(base_disk_index))
803 block_device_mapping['_vd' + chr(base_disk_index)] = volume.id
804 base_disk_index += 1
805
806 #wait until volumes are with status available
807 keep_waiting = True
808 elapsed_time = 0
809 while keep_waiting and elapsed_time < volume_timeout:
810 keep_waiting = False
811 for volume_id in block_device_mapping.itervalues():
812 if self.cinder.volumes.get(volume_id).status != 'available':
813 keep_waiting = True
814 if keep_waiting:
815 time.sleep(1)
816 elapsed_time += 1
817
818 #if we exceeded the timeout rollback
819 if elapsed_time >= volume_timeout:
820 #delete the volumes we just created
821 for volume_id in block_device_mapping.itervalues():
822 self.cinder.volumes.delete(volume_id)
823
824 #delete ports we just created
825 for net_item in net_list_vim:
826 if 'port-id' in net_item:
827 self.neutron.delete_port(net_item['port-id'])
828
829 raise vimconn.vimconnException('Timeout creating volumes for instance ' + name,
830 http_code=vimconn.HTTP_Request_Timeout)
831
832 server = self.nova.servers.create(name, image_id, flavor_id, nics=net_list_vim, meta=metadata,
833 security_groups=security_groups,
834 availability_zone=self.config.get('availability_zone'),
835 key_name=self.config.get('keypair'),
836 userdata=userdata,
837 config_drive = config_drive,
838 block_device_mapping = block_device_mapping
839 ) # , description=description)
840 #print "DONE :-)", server
841 pool_id = None
842 floating_ips = self.neutron.list_floatingips().get("floatingips", ())
843 for floating_network in external_network:
844 # wait until vm is active
845 elapsed_time = 0
846 while elapsed_time < server_timeout:
847 status = self.nova.servers.get(server.id).status
848 if status == 'ACTIVE':
849 break
850 time.sleep(1)
851 elapsed_time += 1
852
853 #if we exceeded the timeout rollback
854 if elapsed_time >= server_timeout:
855 self.delete_vminstance(server.id)
856 raise vimconn.vimconnException('Timeout creating instance ' + name,
857 http_code=vimconn.HTTP_Request_Timeout)
858
859 assigned = False
860 while(assigned == False):
861 if floating_ips:
862 ip = floating_ips.pop(0)
863 if not ip.get("port_id", False) and ip.get('tenant_id') == server.tenant_id:
864 free_floating_ip = ip.get("floating_ip_address")
865 try:
866 fix_ip = floating_network.get('ip')
867 server.add_floating_ip(free_floating_ip, fix_ip)
868 assigned = True
869 except Exception as e:
870 self.delete_vminstance(server.id)
871 raise vimconn.vimconnException(type(e).__name__ + ": Cannot create floating_ip "+ str(e), http_code=vimconn.HTTP_Conflict)
872 else:
873 #Find the external network
874 external_nets = list()
875 for net in self.neutron.list_networks()['networks']:
876 if net['router:external']:
877 external_nets.append(net)
878
879 if len(external_nets) == 0:
880 self.delete_vminstance(server.id)
881 raise vimconn.vimconnException("Cannot create floating_ip automatically since no external "
882 "network is present",
883 http_code=vimconn.HTTP_Conflict)
884 if len(external_nets) > 1:
885 self.delete_vminstance(server.id)
886 raise vimconn.vimconnException("Cannot create floating_ip automatically since multiple "
887 "external networks are present",
888 http_code=vimconn.HTTP_Conflict)
889
890 pool_id = external_nets[0].get('id')
891 param = {'floatingip': {'floating_network_id': pool_id, 'tenant_id': server.tenant_id}}
892 try:
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)
898 assigned=True
899 except Exception as e:
900 self.delete_vminstance(server.id)
901 raise vimconn.vimconnException(type(e).__name__ + ": Cannot create floating_ip "+ str(e), http_code=vimconn.HTTP_Conflict)
902
903 return server.id
904 # except nvExceptions.NotFound as e:
905 # error_value=-vimconn.HTTP_Not_Found
906 # error_text= "vm instance %s not found" % vm_id
907 except (ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError
908 ) as e:
909 # delete the volumes we just created
910 if block_device_mapping != None:
911 for volume_id in block_device_mapping.itervalues():
912 self.cinder.volumes.delete(volume_id)
913
914 # delete ports we just created
915 for net_item in net_list_vim:
916 if 'port-id' in net_item:
917 self.neutron.delete_port(net_item['port-id'])
918 self._format_exception(e)
919 except TypeError as e:
920 raise vimconn.vimconnException(type(e).__name__ + ": "+ str(e), http_code=vimconn.HTTP_Bad_Request)
921
922 def get_vminstance(self,vm_id):
923 '''Returns the VM instance information from VIM'''
924 #self.logger.debug("Getting VM from VIM")
925 try:
926 self._reload_connection()
927 server = self.nova.servers.find(id=vm_id)
928 #TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
929 return server.to_dict()
930 except (ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.NotFound, ConnectionError) as e:
931 self._format_exception(e)
932
933 def get_vminstance_console(self,vm_id, console_type="vnc"):
934 '''
935 Get a console for the virtual machine
936 Params:
937 vm_id: uuid of the VM
938 console_type, can be:
939 "novnc" (by default), "xvpvnc" for VNC types,
940 "rdp-html5" for RDP types, "spice-html5" for SPICE types
941 Returns dict with the console parameters:
942 protocol: ssh, ftp, http, https, ...
943 server: usually ip address
944 port: the http, ssh, ... port
945 suffix: extra text, e.g. the http path and query string
946 '''
947 self.logger.debug("Getting VM CONSOLE from VIM")
948 try:
949 self._reload_connection()
950 server = self.nova.servers.find(id=vm_id)
951 if console_type == None or console_type == "novnc":
952 console_dict = server.get_vnc_console("novnc")
953 elif console_type == "xvpvnc":
954 console_dict = server.get_vnc_console(console_type)
955 elif console_type == "rdp-html5":
956 console_dict = server.get_rdp_console(console_type)
957 elif console_type == "spice-html5":
958 console_dict = server.get_spice_console(console_type)
959 else:
960 raise vimconn.vimconnException("console type '{}' not allowed".format(console_type), http_code=vimconn.HTTP_Bad_Request)
961
962 console_dict1 = console_dict.get("console")
963 if console_dict1:
964 console_url = console_dict1.get("url")
965 if console_url:
966 #parse console_url
967 protocol_index = console_url.find("//")
968 suffix_index = console_url[protocol_index+2:].find("/") + protocol_index+2
969 port_index = console_url[protocol_index+2:suffix_index].find(":") + protocol_index+2
970 if protocol_index < 0 or port_index<0 or suffix_index<0:
971 return -vimconn.HTTP_Internal_Server_Error, "Unexpected response from VIM"
972 console_dict={"protocol": console_url[0:protocol_index],
973 "server": console_url[protocol_index+2:port_index],
974 "port": console_url[port_index:suffix_index],
975 "suffix": console_url[suffix_index+1:]
976 }
977 protocol_index += 2
978 return console_dict
979 raise vimconn.vimconnUnexpectedResponse("Unexpected response from VIM")
980
981 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.BadRequest, ConnectionError) as e:
982 self._format_exception(e)
983
984 def delete_vminstance(self, vm_id):
985 '''Removes a VM instance from VIM. Returns the old identifier
986 '''
987 #print "osconnector: Getting VM from VIM"
988 try:
989 self._reload_connection()
990 #delete VM ports attached to this networks before the virtual machine
991 ports = self.neutron.list_ports(device_id=vm_id)
992 for p in ports['ports']:
993 try:
994 self.neutron.delete_port(p["id"])
995 except Exception as e:
996 self.logger.error("Error deleting port: " + type(e).__name__ + ": "+ str(e))
997
998 #commented because detaching the volumes makes the servers.delete not work properly ?!?
999 #dettach volumes attached
1000 server = self.nova.servers.get(vm_id)
1001 volumes_attached_dict = server._info['os-extended-volumes:volumes_attached']
1002 #for volume in volumes_attached_dict:
1003 # self.cinder.volumes.detach(volume['id'])
1004
1005 self.nova.servers.delete(vm_id)
1006
1007 #delete volumes.
1008 #Although having detached them should have them in active status
1009 #we ensure in this loop
1010 keep_waiting = True
1011 elapsed_time = 0
1012 while keep_waiting and elapsed_time < volume_timeout:
1013 keep_waiting = False
1014 for volume in volumes_attached_dict:
1015 if self.cinder.volumes.get(volume['id']).status != 'available':
1016 keep_waiting = True
1017 else:
1018 self.cinder.volumes.delete(volume['id'])
1019 if keep_waiting:
1020 time.sleep(1)
1021 elapsed_time += 1
1022
1023 return vm_id
1024 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e:
1025 self._format_exception(e)
1026 #TODO insert exception vimconn.HTTP_Unauthorized
1027 #if reaching here is because an exception
1028
1029 def refresh_vms_status(self, vm_list):
1030 '''Get the status of the virtual machines and their interfaces/ports
1031 Params: the list of VM identifiers
1032 Returns a dictionary with:
1033 vm_id: #VIM id of this Virtual Machine
1034 status: #Mandatory. Text with one of:
1035 # DELETED (not found at vim)
1036 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
1037 # OTHER (Vim reported other status not understood)
1038 # ERROR (VIM indicates an ERROR status)
1039 # ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running),
1040 # CREATING (on building process), ERROR
1041 # ACTIVE:NoMgmtIP (Active but any of its interface has an IP address
1042 #
1043 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
1044 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
1045 interfaces:
1046 - vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
1047 mac_address: #Text format XX:XX:XX:XX:XX:XX
1048 vim_net_id: #network id where this interface is connected
1049 vim_interface_id: #interface/port VIM id
1050 ip_address: #null, or text with IPv4, IPv6 address
1051 '''
1052 vm_dict={}
1053 self.logger.debug("refresh_vms status: Getting tenant VM instance information from VIM")
1054 for vm_id in vm_list:
1055 vm={}
1056 try:
1057 vm_vim = self.get_vminstance(vm_id)
1058 if vm_vim['status'] in vmStatus2manoFormat:
1059 vm['status'] = vmStatus2manoFormat[ vm_vim['status'] ]
1060 else:
1061 vm['status'] = "OTHER"
1062 vm['error_msg'] = "VIM status reported " + vm_vim['status']
1063 try:
1064 vm['vim_info'] = yaml.safe_dump(vm_vim, default_flow_style=True, width=256)
1065 except yaml.representer.RepresenterError:
1066 vm['vim_info'] = str(vm_vim)
1067 vm["interfaces"] = []
1068 if vm_vim.get('fault'):
1069 vm['error_msg'] = str(vm_vim['fault'])
1070 #get interfaces
1071 try:
1072 self._reload_connection()
1073 port_dict=self.neutron.list_ports(device_id=vm_id)
1074 for port in port_dict["ports"]:
1075 interface={}
1076 try:
1077 interface['vim_info'] = yaml.safe_dump(port, default_flow_style=True, width=256)
1078 except yaml.representer.RepresenterError:
1079 interface['vim_info'] = str(port)
1080 interface["mac_address"] = port.get("mac_address")
1081 interface["vim_net_id"] = port["network_id"]
1082 interface["vim_interface_id"] = port["id"]
1083 ips=[]
1084 #look for floating ip address
1085 floating_ip_dict = self.neutron.list_floatingips(port_id=port["id"])
1086 if floating_ip_dict.get("floatingips"):
1087 ips.append(floating_ip_dict["floatingips"][0].get("floating_ip_address") )
1088
1089 for subnet in port["fixed_ips"]:
1090 ips.append(subnet["ip_address"])
1091 interface["ip_address"] = ";".join(ips)
1092 vm["interfaces"].append(interface)
1093 except Exception as e:
1094 self.logger.error("Error getting vm interface information " + type(e).__name__ + ": "+ str(e))
1095 except vimconn.vimconnNotFoundException as e:
1096 self.logger.error("Exception getting vm status: %s", str(e))
1097 vm['status'] = "DELETED"
1098 vm['error_msg'] = str(e)
1099 except vimconn.vimconnException as e:
1100 self.logger.error("Exception getting vm status: %s", str(e))
1101 vm['status'] = "VIM_ERROR"
1102 vm['error_msg'] = str(e)
1103 vm_dict[vm_id] = vm
1104 return vm_dict
1105
1106 def action_vminstance(self, vm_id, action_dict):
1107 '''Send and action over a VM instance from VIM
1108 Returns the vm_id if the action was successfully sent to the VIM'''
1109 self.logger.debug("Action over VM '%s': %s", vm_id, str(action_dict))
1110 try:
1111 self._reload_connection()
1112 server = self.nova.servers.find(id=vm_id)
1113 if "start" in action_dict:
1114 if action_dict["start"]=="rebuild":
1115 server.rebuild()
1116 else:
1117 if server.status=="PAUSED":
1118 server.unpause()
1119 elif server.status=="SUSPENDED":
1120 server.resume()
1121 elif server.status=="SHUTOFF":
1122 server.start()
1123 elif "pause" in action_dict:
1124 server.pause()
1125 elif "resume" in action_dict:
1126 server.resume()
1127 elif "shutoff" in action_dict or "shutdown" in action_dict:
1128 server.stop()
1129 elif "forceOff" in action_dict:
1130 server.stop() #TODO
1131 elif "terminate" in action_dict:
1132 server.delete()
1133 elif "createImage" in action_dict:
1134 server.create_image()
1135 #"path":path_schema,
1136 #"description":description_schema,
1137 #"name":name_schema,
1138 #"metadata":metadata_schema,
1139 #"imageRef": id_schema,
1140 #"disk": {"oneOf":[{"type": "null"}, {"type":"string"}] },
1141 elif "rebuild" in action_dict:
1142 server.rebuild(server.image['id'])
1143 elif "reboot" in action_dict:
1144 server.reboot() #reboot_type='SOFT'
1145 elif "console" in action_dict:
1146 console_type = action_dict["console"]
1147 if console_type == None or console_type == "novnc":
1148 console_dict = server.get_vnc_console("novnc")
1149 elif console_type == "xvpvnc":
1150 console_dict = server.get_vnc_console(console_type)
1151 elif console_type == "rdp-html5":
1152 console_dict = server.get_rdp_console(console_type)
1153 elif console_type == "spice-html5":
1154 console_dict = server.get_spice_console(console_type)
1155 else:
1156 raise vimconn.vimconnException("console type '{}' not allowed".format(console_type),
1157 http_code=vimconn.HTTP_Bad_Request)
1158 try:
1159 console_url = console_dict["console"]["url"]
1160 #parse console_url
1161 protocol_index = console_url.find("//")
1162 suffix_index = console_url[protocol_index+2:].find("/") + protocol_index+2
1163 port_index = console_url[protocol_index+2:suffix_index].find(":") + protocol_index+2
1164 if protocol_index < 0 or port_index<0 or suffix_index<0:
1165 raise vimconn.vimconnException("Unexpected response from VIM " + str(console_dict))
1166 console_dict2={"protocol": console_url[0:protocol_index],
1167 "server": console_url[protocol_index+2 : port_index],
1168 "port": int(console_url[port_index+1 : suffix_index]),
1169 "suffix": console_url[suffix_index+1:]
1170 }
1171 return console_dict2
1172 except Exception as e:
1173 raise vimconn.vimconnException("Unexpected response from VIM " + str(console_dict))
1174
1175 return vm_id
1176 except (ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.NotFound, ConnectionError) as e:
1177 self._format_exception(e)
1178 #TODO insert exception vimconn.HTTP_Unauthorized
1179
1180 #NOT USED FUNCTIONS
1181
1182 def new_external_port(self, port_data):
1183 #TODO openstack if needed
1184 '''Adds a external port to VIM'''
1185 '''Returns the port identifier'''
1186 return -vimconn.HTTP_Internal_Server_Error, "osconnector.new_external_port() not implemented"
1187
1188 def connect_port_network(self, port_id, network_id, admin=False):
1189 #TODO openstack if needed
1190 '''Connects a external port to a network'''
1191 '''Returns status code of the VIM response'''
1192 return -vimconn.HTTP_Internal_Server_Error, "osconnector.connect_port_network() not implemented"
1193
1194 def new_user(self, user_name, user_passwd, tenant_id=None):
1195 '''Adds a new user to openstack VIM'''
1196 '''Returns the user identifier'''
1197 self.logger.debug("osconnector: Adding a new user to VIM")
1198 try:
1199 self._reload_connection()
1200 user=self.keystone.users.create(user_name, user_passwd, tenant_id=tenant_id)
1201 #self.keystone.tenants.add_user(self.k_creds["username"], #role)
1202 return user.id
1203 except ksExceptions.ConnectionError as e:
1204 error_value=-vimconn.HTTP_Bad_Request
1205 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1206 except ksExceptions.ClientException as e: #TODO remove
1207 error_value=-vimconn.HTTP_Bad_Request
1208 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1209 #TODO insert exception vimconn.HTTP_Unauthorized
1210 #if reaching here is because an exception
1211 if self.debug:
1212 self.logger.debug("new_user " + error_text)
1213 return error_value, error_text
1214
1215 def delete_user(self, user_id):
1216 '''Delete a user from openstack VIM'''
1217 '''Returns the user identifier'''
1218 if self.debug:
1219 print "osconnector: Deleting a user from VIM"
1220 try:
1221 self._reload_connection()
1222 self.keystone.users.delete(user_id)
1223 return 1, user_id
1224 except ksExceptions.ConnectionError as e:
1225 error_value=-vimconn.HTTP_Bad_Request
1226 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1227 except ksExceptions.NotFound as e:
1228 error_value=-vimconn.HTTP_Not_Found
1229 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1230 except ksExceptions.ClientException as e: #TODO remove
1231 error_value=-vimconn.HTTP_Bad_Request
1232 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1233 #TODO insert exception vimconn.HTTP_Unauthorized
1234 #if reaching here is because an exception
1235 if self.debug:
1236 print "delete_tenant " + error_text
1237 return error_value, error_text
1238
1239 def get_hosts_info(self):
1240 '''Get the information of deployed hosts
1241 Returns the hosts content'''
1242 if self.debug:
1243 print "osconnector: Getting Host info from VIM"
1244 try:
1245 h_list=[]
1246 self._reload_connection()
1247 hypervisors = self.nova.hypervisors.list()
1248 for hype in hypervisors:
1249 h_list.append( hype.to_dict() )
1250 return 1, {"hosts":h_list}
1251 except nvExceptions.NotFound as e:
1252 error_value=-vimconn.HTTP_Not_Found
1253 error_text= (str(e) if len(e.args)==0 else str(e.args[0]))
1254 except (ksExceptions.ClientException, nvExceptions.ClientException) as e:
1255 error_value=-vimconn.HTTP_Bad_Request
1256 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1257 #TODO insert exception vimconn.HTTP_Unauthorized
1258 #if reaching here is because an exception
1259 if self.debug:
1260 print "get_hosts_info " + error_text
1261 return error_value, error_text
1262
1263 def get_hosts(self, vim_tenant):
1264 '''Get the hosts and deployed instances
1265 Returns the hosts content'''
1266 r, hype_dict = self.get_hosts_info()
1267 if r<0:
1268 return r, hype_dict
1269 hypervisors = hype_dict["hosts"]
1270 try:
1271 servers = self.nova.servers.list()
1272 for hype in hypervisors:
1273 for server in servers:
1274 if server.to_dict()['OS-EXT-SRV-ATTR:hypervisor_hostname']==hype['hypervisor_hostname']:
1275 if 'vm' in hype:
1276 hype['vm'].append(server.id)
1277 else:
1278 hype['vm'] = [server.id]
1279 return 1, hype_dict
1280 except nvExceptions.NotFound as e:
1281 error_value=-vimconn.HTTP_Not_Found
1282 error_text= (str(e) if len(e.args)==0 else str(e.args[0]))
1283 except (ksExceptions.ClientException, nvExceptions.ClientException) as e:
1284 error_value=-vimconn.HTTP_Bad_Request
1285 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1286 #TODO insert exception vimconn.HTTP_Unauthorized
1287 #if reaching here is because an exception
1288 if self.debug:
1289 print "get_hosts " + error_text
1290 return error_value, error_text
1291
1292