Bug 256 fixed
[osm/RO.git] / osm_ro / 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 import random
38
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
54
55 '''contain the openstack virtual machine status to openmano status'''
56 vmStatus2manoFormat={'ACTIVE':'ACTIVE',
57 'PAUSED':'PAUSED',
58 'SUSPENDED': 'SUSPENDED',
59 'SHUTOFF':'INACTIVE',
60 'BUILD':'BUILD',
61 'ERROR':'ERROR','DELETED':'DELETED'
62 }
63 netStatus2manoFormat={'ACTIVE':'ACTIVE','PAUSED':'PAUSED','INACTIVE':'INACTIVE','BUILD':'BUILD','ERROR':'ERROR','DELETED':'DELETED'
64 }
65
66 #global var to have a timeout creating and deleting volumes
67 volume_timeout = 60
68 server_timeout = 60
69
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
76 '''
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)
81
82 self.persistent_info = persistent_info
83 self.k_creds={}
84 self.n_creds={}
85 if self.config.get("insecure"):
86 self.k_creds["insecure"] = True
87 self.n_creds["insecure"] = True
88 if not url:
89 raise TypeError, 'url param can not be NoneType'
90 self.k_creds['auth_url'] = url
91 self.n_creds['auth_url'] = url
92 if tenant_name:
93 self.k_creds['tenant_name'] = tenant_name
94 self.n_creds['project_id'] = tenant_name
95 if tenant_id:
96 self.k_creds['tenant_id'] = tenant_id
97 self.n_creds['tenant_id'] = tenant_id
98 if user:
99 self.k_creds['username'] = user
100 self.n_creds['username'] = user
101 if passwd:
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')
110
111 self.reload_client = True
112 self.logger = logging.getLogger('openmano.vim.openstack')
113 if log_level:
114 self.logger.setLevel( getattr(logging, log_level) )
115
116 def __setitem__(self,index, value):
117 '''Set individuals parameters
118 Throw TypeError, KeyError
119 '''
120 if index=='tenant_id':
121 self.reload_client=True
122 self.tenant_id = value
123 if self.osc_api_version == 'v3.3':
124 if value:
125 self.k_creds['project_id'] = value
126 self.n_creds['project_id'] = value
127 else:
128 del self.k_creds['project_id']
129 del self.n_creds['project_id']
130 else:
131 if value:
132 self.k_creds['tenant_id'] = value
133 self.n_creds['tenant_id'] = value
134 else:
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':
141 if value:
142 self.k_creds['project_name'] = value
143 self.n_creds['project_name'] = value
144 else:
145 del self.k_creds['project_name']
146 del self.n_creds['project_name']
147 else:
148 if value:
149 self.k_creds['tenant_name'] = value
150 self.n_creds['project_id'] = value
151 else:
152 del self.k_creds['tenant_name']
153 del self.n_creds['project_id']
154 elif index=='user':
155 self.reload_client=True
156 self.user = value
157 if value:
158 self.k_creds['username'] = value
159 self.n_creds['username'] = value
160 else:
161 del self.k_creds['username']
162 del self.n_creds['username']
163 elif index=='passwd':
164 self.reload_client=True
165 self.passwd = value
166 if value:
167 self.k_creds['password'] = value
168 self.n_creds['api_key'] = value
169 else:
170 del self.k_creds['password']
171 del self.n_creds['api_key']
172 elif index=='url':
173 self.reload_client=True
174 self.url = value
175 if value:
176 self.k_creds['auth_url'] = value
177 self.n_creds['auth_url'] = value
178 else:
179 raise TypeError, 'url param can not be NoneType'
180 else:
181 vimconn.vimconnector.__setitem__(self,index, value)
182
183 def _reload_connection(self):
184 '''Called before any operation, it check if credentials has changed
185 Throw keystoneclient.apiclient.exceptions.AuthorizationFailure
186 '''
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:
189 #test valid params
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)
199 else:
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
208
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
216 else:
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":
220 net['type']='data'
221 else:
222 net['type']='bridge'
223
224
225
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
230 )):
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))
239 else: # ()
240 raise vimconn.vimconnConnectionException(type(exception).__name__ + ": " + str(exception))
241
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
247 <other VIM specific>
248 Returns the tenant list of dictionaries: [{'name':'<name>, 'id':'<id>, ...}, ...]
249 '''
250 self.logger.debug("Getting tenants from VIM filter: '%s'", str(filter_dict))
251 try:
252 self._reload_connection()
253 if self.osc_api_version == 'v3.3':
254 project_class_list=self.keystone.projects.findall(**filter_dict)
255 else:
256 project_class_list=self.keystone.tenants.findall(**filter_dict)
257 project_list=[]
258 for project in project_class_list:
259 project_list.append(project.to_dict())
260 return project_list
261 except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e:
262 self._format_exception(e)
263
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)
267 try:
268 self._reload_connection()
269 if self.osc_api_version == 'v3.3':
270 project=self.keystone.projects.create(tenant_name, tenant_description)
271 else:
272 project=self.keystone.tenants.create(tenant_name, tenant_description)
273 return project.id
274 except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e:
275 self._format_exception(e)
276
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)
280 try:
281 self._reload_connection()
282 if self.osc_api_version == 'v3.3':
283 self.keystone.projects.delete(tenant_id)
284 else:
285 self.keystone.tenants.delete(tenant_id)
286 return tenant_id
287 except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e:
288 self._format_exception(e)
289
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))
294 try:
295 new_net = None
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"
303 if vlan!=None:
304 network_dict["provider:network_type"] = vlan
305 network_dict["shared"]=shared
306 new_net=self.neutron.create_network({'network':network_dict})
307 #print new_net
308 #create subnetwork, even if there is no profile
309 if not ip_profile:
310 ip_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']
321 }
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:
345 if new_net:
346 self.neutron.delete_network(new_net['network']['id'])
347 self._format_exception(e)
348
349 def get_network_list(self, filter_dict={}):
350 '''Obtain tenant networks of VIM
351 Filter_dict can be:
352 name: network name
353 id: network uuid
354 shared: boolean
355 tenant_id: tenant
356 admin_state_up: boolean
357 status: 'ACTIVE'
358 Returns the network list of dictionaries
359 '''
360 self.logger.debug("Getting network from VIM filter: '%s'", str(filter_dict))
361 try:
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_os2mano(net_list)
368 return net_list
369 except (neExceptions.ConnectionFailed, ksExceptions.ClientException, neExceptions.NeutronException, ConnectionError) as e:
370 self._format_exception(e)
371
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)
378 if len(net_list)==0:
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")
382 net = net_list[0]
383 subnets=[]
384 for subnet_id in net.get("subnets", () ):
385 try:
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
392 net["encapsulation"] = net.get('provider:network_type')
393 net["segmentation_id"] = net.get('provider:segmentation_id')
394 return net
395
396 def delete_network(self, net_id):
397 '''Deletes a tenant network from VIM. Returns the old network identifier'''
398 self.logger.debug("Deleting network '%s' from VIM", net_id)
399 try:
400 self._reload_connection()
401 #delete VM ports attached to this networks before the network
402 ports = self.neutron.list_ports(network_id=net_id)
403 for p in ports['ports']:
404 try:
405 self.neutron.delete_port(p["id"])
406 except Exception as e:
407 self.logger.error("Error deleting port %s: %s", p["id"], str(e))
408 self.neutron.delete_network(net_id)
409 return net_id
410 except (neExceptions.ConnectionFailed, neExceptions.NetworkNotFoundClient, neExceptions.NeutronException,
411 ksExceptions.ClientException, neExceptions.NeutronException, ConnectionError) as e:
412 self._format_exception(e)
413
414 def refresh_nets_status(self, net_list):
415 '''Get the status of the networks
416 Params: the list of network identifiers
417 Returns a dictionary with:
418 net_id: #VIM id of this network
419 status: #Mandatory. Text with one of:
420 # DELETED (not found at vim)
421 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
422 # OTHER (Vim reported other status not understood)
423 # ERROR (VIM indicates an ERROR status)
424 # ACTIVE, INACTIVE, DOWN (admin down),
425 # BUILD (on building process)
426 #
427 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
428 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
429
430 '''
431 net_dict={}
432 for net_id in net_list:
433 net = {}
434 try:
435 net_vim = self.get_network(net_id)
436 if net_vim['status'] in netStatus2manoFormat:
437 net["status"] = netStatus2manoFormat[ net_vim['status'] ]
438 else:
439 net["status"] = "OTHER"
440 net["error_msg"] = "VIM status reported " + net_vim['status']
441
442 if net['status'] == "ACTIVE" and not net_vim['admin_state_up']:
443 net['status'] = 'DOWN'
444 try:
445 net['vim_info'] = yaml.safe_dump(net_vim, default_flow_style=True, width=256)
446 except yaml.representer.RepresenterError:
447 net['vim_info'] = str(net_vim)
448 if net_vim.get('fault'): #TODO
449 net['error_msg'] = str(net_vim['fault'])
450 except vimconn.vimconnNotFoundException as e:
451 self.logger.error("Exception getting net status: %s", str(e))
452 net['status'] = "DELETED"
453 net['error_msg'] = str(e)
454 except vimconn.vimconnException as e:
455 self.logger.error("Exception getting net status: %s", str(e))
456 net['status'] = "VIM_ERROR"
457 net['error_msg'] = str(e)
458 net_dict[net_id] = net
459 return net_dict
460
461 def get_flavor(self, flavor_id):
462 '''Obtain flavor details from the VIM. Returns the flavor dict details'''
463 self.logger.debug("Getting flavor '%s'", flavor_id)
464 try:
465 self._reload_connection()
466 flavor = self.nova.flavors.find(id=flavor_id)
467 #TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
468 return flavor.to_dict()
469 except (nvExceptions.NotFound, nvExceptions.ClientException, ksExceptions.ClientException, ConnectionError) as e:
470 self._format_exception(e)
471
472 def get_flavor_id_from_data(self, flavor_dict):
473 """Obtain flavor id that match the flavor description
474 Returns the flavor_id or raises a vimconnNotFoundException
475 """
476 try:
477 self._reload_connection()
478 numa=None
479 numas = flavor_dict.get("extended",{}).get("numas")
480 if numas:
481 #TODO
482 raise vimconn.vimconnNotFoundException("Flavor with EPA still not implemted")
483 # if len(numas) > 1:
484 # raise vimconn.vimconnNotFoundException("Cannot find any flavor with more than one numa")
485 # numa=numas[0]
486 # numas = extended.get("numas")
487 for flavor in self.nova.flavors.list():
488 epa = flavor.get_keys()
489 if epa:
490 continue
491 #TODO
492 if flavor.ram != flavor_dict["ram"]:
493 continue
494 if flavor.vcpus != flavor_dict["vcpus"]:
495 continue
496 if flavor.disk != flavor_dict["disk"]:
497 continue
498 return flavor.id
499 raise vimconn.vimconnNotFoundException("Cannot find any flavor matching '{}'".format(str(flavor_dict)))
500 except (nvExceptions.NotFound, nvExceptions.ClientException, ksExceptions.ClientException, ConnectionError) as e:
501 self._format_exception(e)
502
503
504 def new_flavor(self, flavor_data, change_name_if_used=True):
505 '''Adds a tenant flavor to openstack VIM
506 if change_name_if_used is True, it will change name in case of conflict, because it is not supported name repetition
507 Returns the flavor identifier
508 '''
509 self.logger.debug("Adding flavor '%s'", str(flavor_data))
510 retry=0
511 max_retries=3
512 name_suffix = 0
513 name=flavor_data['name']
514 while retry<max_retries:
515 retry+=1
516 try:
517 self._reload_connection()
518 if change_name_if_used:
519 #get used names
520 fl_names=[]
521 fl=self.nova.flavors.list()
522 for f in fl:
523 fl_names.append(f.name)
524 while name in fl_names:
525 name_suffix += 1
526 name = flavor_data['name']+"-" + str(name_suffix)
527
528 ram = flavor_data.get('ram',64)
529 vcpus = flavor_data.get('vcpus',1)
530 numa_properties=None
531
532 extended = flavor_data.get("extended")
533 if extended:
534 numas=extended.get("numas")
535 if numas:
536 numa_nodes = len(numas)
537 if numa_nodes > 1:
538 return -1, "Can not add flavor with more than one numa"
539 numa_properties = {"hw:numa_nodes":str(numa_nodes)}
540 numa_properties["hw:mem_page_size"] = "large"
541 numa_properties["hw:cpu_policy"] = "dedicated"
542 numa_properties["hw:numa_mempolicy"] = "strict"
543 for numa in numas:
544 #overwrite ram and vcpus
545 ram = numa['memory']*1024
546 if 'paired-threads' in numa:
547 vcpus = numa['paired-threads']*2
548 numa_properties["hw:cpu_threads_policy"] = "prefer"
549 elif 'cores' in numa:
550 vcpus = numa['cores']
551 #numa_properties["hw:cpu_threads_policy"] = "prefer"
552 elif 'threads' in numa:
553 vcpus = numa['threads']
554 numa_properties["hw:cpu_policy"] = "isolated"
555 # for interface in numa.get("interfaces",() ):
556 # if interface["dedicated"]=="yes":
557 # raise vimconn.vimconnException("Passthrough interfaces are not supported for the openstack connector", http_code=vimconn.HTTP_Service_Unavailable)
558 # #TODO, add the key 'pci_passthrough:alias"="<label at config>:<number ifaces>"' when a way to connect it is available
559
560 #create flavor
561 new_flavor=self.nova.flavors.create(name,
562 ram,
563 vcpus,
564 flavor_data.get('disk',1),
565 is_public=flavor_data.get('is_public', True)
566 )
567 #add metadata
568 if numa_properties:
569 new_flavor.set_keys(numa_properties)
570 return new_flavor.id
571 except nvExceptions.Conflict as e:
572 if change_name_if_used and retry < max_retries:
573 continue
574 self._format_exception(e)
575 #except nvExceptions.BadRequest as e:
576 except (ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e:
577 self._format_exception(e)
578
579 def delete_flavor(self,flavor_id):
580 '''Deletes a tenant flavor from openstack VIM. Returns the old flavor_id
581 '''
582 try:
583 self._reload_connection()
584 self.nova.flavors.delete(flavor_id)
585 return flavor_id
586 #except nvExceptions.BadRequest as e:
587 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e:
588 self._format_exception(e)
589
590 def new_image(self,image_dict):
591 '''
592 Adds a tenant image to VIM. imge_dict is a dictionary with:
593 name: name
594 disk_format: qcow2, vhd, vmdk, raw (by default), ...
595 location: path or URI
596 public: "yes" or "no"
597 metadata: metadata of the image
598 Returns the image_id
599 '''
600 #using version 1 of glance client
601 glancev1 = gl1Client.Client('1',self.glance_endpoint, token=self.keystone.auth_token, **self.k_creds) #TODO check k_creds vs n_creds
602 retry=0
603 max_retries=3
604 while retry<max_retries:
605 retry+=1
606 try:
607 self._reload_connection()
608 #determine format http://docs.openstack.org/developer/glance/formats.html
609 if "disk_format" in image_dict:
610 disk_format=image_dict["disk_format"]
611 else: #autodiscover based on extension
612 if image_dict['location'][-6:]==".qcow2":
613 disk_format="qcow2"
614 elif image_dict['location'][-4:]==".vhd":
615 disk_format="vhd"
616 elif image_dict['location'][-5:]==".vmdk":
617 disk_format="vmdk"
618 elif image_dict['location'][-4:]==".vdi":
619 disk_format="vdi"
620 elif image_dict['location'][-4:]==".iso":
621 disk_format="iso"
622 elif image_dict['location'][-4:]==".aki":
623 disk_format="aki"
624 elif image_dict['location'][-4:]==".ari":
625 disk_format="ari"
626 elif image_dict['location'][-4:]==".ami":
627 disk_format="ami"
628 else:
629 disk_format="raw"
630 self.logger.debug("new_image: '%s' loading from '%s'", image_dict['name'], image_dict['location'])
631 if image_dict['location'][0:4]=="http":
632 new_image = glancev1.images.create(name=image_dict['name'], is_public=image_dict.get('public',"yes")=="yes",
633 container_format="bare", location=image_dict['location'], disk_format=disk_format)
634 else: #local path
635 with open(image_dict['location']) as fimage:
636 new_image = glancev1.images.create(name=image_dict['name'], is_public=image_dict.get('public',"yes")=="yes",
637 container_format="bare", data=fimage, disk_format=disk_format)
638 #insert metadata. We cannot use 'new_image.properties.setdefault'
639 #because nova and glance are "INDEPENDENT" and we are using nova for reading metadata
640 new_image_nova=self.nova.images.find(id=new_image.id)
641 new_image_nova.metadata.setdefault('location',image_dict['location'])
642 metadata_to_load = image_dict.get('metadata')
643 if metadata_to_load:
644 for k,v in yaml.load(metadata_to_load).iteritems():
645 new_image_nova.metadata.setdefault(k,v)
646 return new_image.id
647 except (nvExceptions.Conflict, ksExceptions.ClientException, nvExceptions.ClientException) as e:
648 self._format_exception(e)
649 except (HTTPException, gl1Exceptions.HTTPException, gl1Exceptions.CommunicationError, ConnectionError) as e:
650 if retry==max_retries:
651 continue
652 self._format_exception(e)
653 except IOError as e: #can not open the file
654 raise vimconn.vimconnConnectionException(type(e).__name__ + ": " + str(e)+ " for " + image_dict['location'],
655 http_code=vimconn.HTTP_Bad_Request)
656
657 def delete_image(self, image_id):
658 '''Deletes a tenant image from openstack VIM. Returns the old id
659 '''
660 try:
661 self._reload_connection()
662 self.nova.images.delete(image_id)
663 return image_id
664 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e: #TODO remove
665 self._format_exception(e)
666
667 def get_image_id_from_path(self, path):
668 '''Get the image id from image path in the VIM database. Returns the image_id'''
669 try:
670 self._reload_connection()
671 images = self.nova.images.list()
672 for image in images:
673 if image.metadata.get("location")==path:
674 return image.id
675 raise vimconn.vimconnNotFoundException("image with location '{}' not found".format( path))
676 except (ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e:
677 self._format_exception(e)
678
679 def get_image_list(self, filter_dict={}):
680 '''Obtain tenant images from VIM
681 Filter_dict can be:
682 id: image id
683 name: image name
684 checksum: image checksum
685 Returns the image list of dictionaries:
686 [{<the fields at Filter_dict plus some VIM specific>}, ...]
687 List can be empty
688 '''
689 self.logger.debug("Getting image list from VIM filter: '%s'", str(filter_dict))
690 try:
691 self._reload_connection()
692 filter_dict_os=filter_dict.copy()
693 #First we filter by the available filter fields: name, id. The others are removed.
694 filter_dict_os.pop('checksum',None)
695 image_list=self.nova.images.findall(**filter_dict_os)
696 if len(image_list)==0:
697 return []
698 #Then we filter by the rest of filter fields: checksum
699 filtered_list = []
700 for image in image_list:
701 image_class=self.glance.images.get(image.id)
702 if 'checksum' not in filter_dict or image_class['checksum']==filter_dict.get('checksum'):
703 filtered_list.append(image_class.copy())
704 return filtered_list
705 except (ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e:
706 self._format_exception(e)
707
708 def new_vminstance(self,name,description,start,image_id,flavor_id,net_list,cloud_config=None,disk_list=None):
709 '''Adds a VM instance to VIM
710 Params:
711 start: indicates if VM must start or boot in pause mode. Ignored
712 image_id,flavor_id: iamge and flavor uuid
713 net_list: list of interfaces, each one is a dictionary with:
714 name:
715 net_id: network uuid to connect
716 vpci: virtual vcpi to assign, ignored because openstack lack #TODO
717 model: interface model, ignored #TODO
718 mac_address: used for SR-IOV ifaces #TODO for other types
719 use: 'data', 'bridge', 'mgmt'
720 type: 'virtual', 'PF', 'VF', 'VFnotShared'
721 vim_id: filled/added by this function
722 floating_ip: True/False (or it can be None)
723 #TODO ip, security groups
724 Returns the instance identifier
725 '''
726 self.logger.debug("new_vminstance input: image='%s' flavor='%s' nics='%s'",image_id, flavor_id,str(net_list))
727 try:
728 metadata={}
729 net_list_vim=[]
730 external_network=[] #list of external networks to be connected to instance, later on used to create floating_ip
731 self._reload_connection()
732 metadata_vpci={} #For a specific neutron plugin
733 for net in net_list:
734 if not net.get("net_id"): #skip non connected iface
735 continue
736
737 port_dict={
738 "network_id": net["net_id"],
739 "name": net.get("name"),
740 "admin_state_up": True
741 }
742 if net["type"]=="virtual":
743 if "vpci" in net:
744 metadata_vpci[ net["net_id"] ] = [[ net["vpci"], "" ]]
745 elif net["type"]=="VF": # for VF
746 if "vpci" in net:
747 if "VF" not in metadata_vpci:
748 metadata_vpci["VF"]=[]
749 metadata_vpci["VF"].append([ net["vpci"], "" ])
750 port_dict["binding:vnic_type"]="direct"
751 else: #For PT
752 if "vpci" in net:
753 if "PF" not in metadata_vpci:
754 metadata_vpci["PF"]=[]
755 metadata_vpci["PF"].append([ net["vpci"], "" ])
756 port_dict["binding:vnic_type"]="direct-physical"
757 if not port_dict["name"]:
758 port_dict["name"]=name
759 if net.get("mac_address"):
760 port_dict["mac_address"]=net["mac_address"]
761 if net.get("port_security") == False:
762 port_dict["port_security_enabled"]=net["port_security"]
763 new_port = self.neutron.create_port({"port": port_dict })
764 net["mac_adress"] = new_port["port"]["mac_address"]
765 net["vim_id"] = new_port["port"]["id"]
766 net["ip"] = new_port["port"].get("fixed_ips", [{}])[0].get("ip_address")
767 net_list_vim.append({"port-id": new_port["port"]["id"]})
768
769 if net.get('floating_ip', False):
770 net['exit_on_floating_ip_error'] = True
771 external_network.append(net)
772 elif net['use'] == 'mgmt' and self.config.get('use_floating_ip'):
773 net['exit_on_floating_ip_error'] = False
774 external_network.append(net)
775
776 if metadata_vpci:
777 metadata = {"pci_assignement": json.dumps(metadata_vpci)}
778 if len(metadata["pci_assignement"]) >255:
779 #limit the metadata size
780 #metadata["pci_assignement"] = metadata["pci_assignement"][0:255]
781 self.logger.warn("Metadata deleted since it exceeds the expected length (255) ")
782 metadata = {}
783
784 self.logger.debug("name '%s' image_id '%s'flavor_id '%s' net_list_vim '%s' description '%s' metadata %s",
785 name, image_id, flavor_id, str(net_list_vim), description, str(metadata))
786
787 security_groups = self.config.get('security_groups')
788 if type(security_groups) is str:
789 security_groups = ( security_groups, )
790 #cloud config
791 userdata=None
792 config_drive = None
793 if isinstance(cloud_config, dict):
794 if cloud_config.get("user-data"):
795 userdata=cloud_config["user-data"]
796 if cloud_config.get("boot-data-drive") != None:
797 config_drive = cloud_config["boot-data-drive"]
798 if cloud_config.get("config-files") or cloud_config.get("users") or cloud_config.get("key-pairs"):
799 if userdata:
800 raise vimconn.vimconnConflictException("Cloud-config cannot contain both 'userdata' and 'config-files'/'users'/'key-pairs'")
801 userdata_dict={}
802 #default user
803 if cloud_config.get("key-pairs"):
804 userdata_dict["ssh-authorized-keys"] = cloud_config["key-pairs"]
805 userdata_dict["users"] = [{"default": None, "ssh-authorized-keys": cloud_config["key-pairs"] }]
806 if cloud_config.get("users"):
807 if "users" not in userdata_dict:
808 userdata_dict["users"] = [ "default" ]
809 for user in cloud_config["users"]:
810 user_info = {
811 "name" : user["name"],
812 "sudo": "ALL = (ALL)NOPASSWD:ALL"
813 }
814 if "user-info" in user:
815 user_info["gecos"] = user["user-info"]
816 if user.get("key-pairs"):
817 user_info["ssh-authorized-keys"] = user["key-pairs"]
818 userdata_dict["users"].append(user_info)
819
820 if cloud_config.get("config-files"):
821 userdata_dict["write_files"] = []
822 for file in cloud_config["config-files"]:
823 file_info = {
824 "path" : file["dest"],
825 "content": file["content"]
826 }
827 if file.get("encoding"):
828 file_info["encoding"] = file["encoding"]
829 if file.get("permissions"):
830 file_info["permissions"] = file["permissions"]
831 if file.get("owner"):
832 file_info["owner"] = file["owner"]
833 userdata_dict["write_files"].append(file_info)
834 userdata = "#cloud-config\n"
835 userdata += yaml.safe_dump(userdata_dict, indent=4, default_flow_style=False)
836 self.logger.debug("userdata: %s", userdata)
837 elif isinstance(cloud_config, str):
838 userdata = cloud_config
839
840 #Create additional volumes in case these are present in disk_list
841 block_device_mapping = None
842 base_disk_index = ord('b')
843 if disk_list != None:
844 block_device_mapping = dict()
845 for disk in disk_list:
846 if 'image_id' in disk:
847 volume = self.cinder.volumes.create(size = disk['size'],name = name + '_vd' +
848 chr(base_disk_index), imageRef = disk['image_id'])
849 else:
850 volume = self.cinder.volumes.create(size=disk['size'], name=name + '_vd' +
851 chr(base_disk_index))
852 block_device_mapping['_vd' + chr(base_disk_index)] = volume.id
853 base_disk_index += 1
854
855 #wait until volumes are with status available
856 keep_waiting = True
857 elapsed_time = 0
858 while keep_waiting and elapsed_time < volume_timeout:
859 keep_waiting = False
860 for volume_id in block_device_mapping.itervalues():
861 if self.cinder.volumes.get(volume_id).status != 'available':
862 keep_waiting = True
863 if keep_waiting:
864 time.sleep(1)
865 elapsed_time += 1
866
867 #if we exceeded the timeout rollback
868 if elapsed_time >= volume_timeout:
869 #delete the volumes we just created
870 for volume_id in block_device_mapping.itervalues():
871 self.cinder.volumes.delete(volume_id)
872
873 #delete ports we just created
874 for net_item in net_list_vim:
875 if 'port-id' in net_item:
876 self.neutron.delete_port(net_item['port-id'])
877
878 raise vimconn.vimconnException('Timeout creating volumes for instance ' + name,
879 http_code=vimconn.HTTP_Request_Timeout)
880
881 server = self.nova.servers.create(name, image_id, flavor_id, nics=net_list_vim, meta=metadata,
882 security_groups=security_groups,
883 availability_zone=self.config.get('availability_zone'),
884 key_name=self.config.get('keypair'),
885 userdata=userdata,
886 config_drive = config_drive,
887 block_device_mapping = block_device_mapping
888 ) # , description=description)
889 #print "DONE :-)", server
890 pool_id = None
891 floating_ips = self.neutron.list_floatingips().get("floatingips", ())
892 for floating_network in external_network:
893 try:
894 # wait until vm is active
895 elapsed_time = 0
896 while elapsed_time < server_timeout:
897 status = self.nova.servers.get(server.id).status
898 if status == 'ACTIVE':
899 break
900 time.sleep(1)
901 elapsed_time += 1
902
903 #if we exceeded the timeout rollback
904 if elapsed_time >= server_timeout:
905 raise vimconn.vimconnException('Timeout creating instance ' + name,
906 http_code=vimconn.HTTP_Request_Timeout)
907
908 assigned = False
909 while(assigned == False):
910 if floating_ips:
911 ip = floating_ips.pop(0)
912 if not ip.get("port_id", False) and ip.get('tenant_id') == server.tenant_id:
913 free_floating_ip = ip.get("floating_ip_address")
914 try:
915 fix_ip = floating_network.get('ip')
916 server.add_floating_ip(free_floating_ip, fix_ip)
917 assigned = True
918 except Exception as e:
919 raise vimconn.vimconnException(type(e).__name__ + ": Cannot create floating_ip "+ str(e), http_code=vimconn.HTTP_Conflict)
920 else:
921 #Find the external network
922 external_nets = list()
923 for net in self.neutron.list_networks()['networks']:
924 if net['router:external']:
925 external_nets.append(net)
926
927 if len(external_nets) == 0:
928 raise vimconn.vimconnException("Cannot create floating_ip automatically since no external "
929 "network is present",
930 http_code=vimconn.HTTP_Conflict)
931 if len(external_nets) > 1:
932 raise vimconn.vimconnException("Cannot create floating_ip automatically since multiple "
933 "external networks are present",
934 http_code=vimconn.HTTP_Conflict)
935
936 pool_id = external_nets[0].get('id')
937 param = {'floatingip': {'floating_network_id': pool_id, 'tenant_id': server.tenant_id}}
938 try:
939 #self.logger.debug("Creating floating IP")
940 new_floating_ip = self.neutron.create_floatingip(param)
941 free_floating_ip = new_floating_ip['floatingip']['floating_ip_address']
942 fix_ip = floating_network.get('ip')
943 server.add_floating_ip(free_floating_ip, fix_ip)
944 assigned=True
945 except Exception as e:
946 raise vimconn.vimconnException(type(e).__name__ + ": Cannot assign floating_ip "+ str(e), http_code=vimconn.HTTP_Conflict)
947 except Exception as e:
948 if not floating_network['exit_on_floating_ip_error']:
949 self.logger.warn("Cannot create floating_ip. %s", str(e))
950 continue
951 self.delete_vminstance(server.id)
952 raise
953
954 return server.id
955 # except nvExceptions.NotFound as e:
956 # error_value=-vimconn.HTTP_Not_Found
957 # error_text= "vm instance %s not found" % vm_id
958 except (ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e:
959 # delete the volumes we just created
960 if block_device_mapping != None:
961 for volume_id in block_device_mapping.itervalues():
962 self.cinder.volumes.delete(volume_id)
963
964 # delete ports we just created
965 for net_item in net_list_vim:
966 if 'port-id' in net_item:
967 self.neutron.delete_port(net_item['port-id'])
968 self._format_exception(e)
969 except TypeError as e:
970 raise vimconn.vimconnException(type(e).__name__ + ": "+ str(e), http_code=vimconn.HTTP_Bad_Request)
971
972 def get_vminstance(self,vm_id):
973 '''Returns the VM instance information from VIM'''
974 #self.logger.debug("Getting VM from VIM")
975 try:
976 self._reload_connection()
977 server = self.nova.servers.find(id=vm_id)
978 #TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
979 return server.to_dict()
980 except (ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.NotFound, ConnectionError) as e:
981 self._format_exception(e)
982
983 def get_vminstance_console(self,vm_id, console_type="vnc"):
984 '''
985 Get a console for the virtual machine
986 Params:
987 vm_id: uuid of the VM
988 console_type, can be:
989 "novnc" (by default), "xvpvnc" for VNC types,
990 "rdp-html5" for RDP types, "spice-html5" for SPICE types
991 Returns dict with the console parameters:
992 protocol: ssh, ftp, http, https, ...
993 server: usually ip address
994 port: the http, ssh, ... port
995 suffix: extra text, e.g. the http path and query string
996 '''
997 self.logger.debug("Getting VM CONSOLE from VIM")
998 try:
999 self._reload_connection()
1000 server = self.nova.servers.find(id=vm_id)
1001 if console_type == None or console_type == "novnc":
1002 console_dict = server.get_vnc_console("novnc")
1003 elif console_type == "xvpvnc":
1004 console_dict = server.get_vnc_console(console_type)
1005 elif console_type == "rdp-html5":
1006 console_dict = server.get_rdp_console(console_type)
1007 elif console_type == "spice-html5":
1008 console_dict = server.get_spice_console(console_type)
1009 else:
1010 raise vimconn.vimconnException("console type '{}' not allowed".format(console_type), http_code=vimconn.HTTP_Bad_Request)
1011
1012 console_dict1 = console_dict.get("console")
1013 if console_dict1:
1014 console_url = console_dict1.get("url")
1015 if console_url:
1016 #parse console_url
1017 protocol_index = console_url.find("//")
1018 suffix_index = console_url[protocol_index+2:].find("/") + protocol_index+2
1019 port_index = console_url[protocol_index+2:suffix_index].find(":") + protocol_index+2
1020 if protocol_index < 0 or port_index<0 or suffix_index<0:
1021 return -vimconn.HTTP_Internal_Server_Error, "Unexpected response from VIM"
1022 console_dict={"protocol": console_url[0:protocol_index],
1023 "server": console_url[protocol_index+2:port_index],
1024 "port": console_url[port_index:suffix_index],
1025 "suffix": console_url[suffix_index+1:]
1026 }
1027 protocol_index += 2
1028 return console_dict
1029 raise vimconn.vimconnUnexpectedResponse("Unexpected response from VIM")
1030
1031 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.BadRequest, ConnectionError) as e:
1032 self._format_exception(e)
1033
1034 def delete_vminstance(self, vm_id):
1035 '''Removes a VM instance from VIM. Returns the old identifier
1036 '''
1037 #print "osconnector: Getting VM from VIM"
1038 try:
1039 self._reload_connection()
1040 #delete VM ports attached to this networks before the virtual machine
1041 ports = self.neutron.list_ports(device_id=vm_id)
1042 for p in ports['ports']:
1043 try:
1044 self.neutron.delete_port(p["id"])
1045 except Exception as e:
1046 self.logger.error("Error deleting port: " + type(e).__name__ + ": "+ str(e))
1047
1048 #commented because detaching the volumes makes the servers.delete not work properly ?!?
1049 #dettach volumes attached
1050 server = self.nova.servers.get(vm_id)
1051 volumes_attached_dict = server._info['os-extended-volumes:volumes_attached']
1052 #for volume in volumes_attached_dict:
1053 # self.cinder.volumes.detach(volume['id'])
1054
1055 self.nova.servers.delete(vm_id)
1056
1057 #delete volumes.
1058 #Although having detached them should have them in active status
1059 #we ensure in this loop
1060 keep_waiting = True
1061 elapsed_time = 0
1062 while keep_waiting and elapsed_time < volume_timeout:
1063 keep_waiting = False
1064 for volume in volumes_attached_dict:
1065 if self.cinder.volumes.get(volume['id']).status != 'available':
1066 keep_waiting = True
1067 else:
1068 self.cinder.volumes.delete(volume['id'])
1069 if keep_waiting:
1070 time.sleep(1)
1071 elapsed_time += 1
1072
1073 return vm_id
1074 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e:
1075 self._format_exception(e)
1076 #TODO insert exception vimconn.HTTP_Unauthorized
1077 #if reaching here is because an exception
1078
1079 def refresh_vms_status(self, vm_list):
1080 '''Get the status of the virtual machines and their interfaces/ports
1081 Params: the list of VM identifiers
1082 Returns a dictionary with:
1083 vm_id: #VIM id of this Virtual Machine
1084 status: #Mandatory. Text with one of:
1085 # DELETED (not found at vim)
1086 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
1087 # OTHER (Vim reported other status not understood)
1088 # ERROR (VIM indicates an ERROR status)
1089 # ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running),
1090 # CREATING (on building process), ERROR
1091 # ACTIVE:NoMgmtIP (Active but any of its interface has an IP address
1092 #
1093 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
1094 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
1095 interfaces:
1096 - vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
1097 mac_address: #Text format XX:XX:XX:XX:XX:XX
1098 vim_net_id: #network id where this interface is connected
1099 vim_interface_id: #interface/port VIM id
1100 ip_address: #null, or text with IPv4, IPv6 address
1101 compute_node: #identification of compute node where PF,VF interface is allocated
1102 pci: #PCI address of the NIC that hosts the PF,VF
1103 vlan: #physical VLAN used for VF
1104 '''
1105 vm_dict={}
1106 self.logger.debug("refresh_vms status: Getting tenant VM instance information from VIM")
1107 for vm_id in vm_list:
1108 vm={}
1109 try:
1110 vm_vim = self.get_vminstance(vm_id)
1111 if vm_vim['status'] in vmStatus2manoFormat:
1112 vm['status'] = vmStatus2manoFormat[ vm_vim['status'] ]
1113 else:
1114 vm['status'] = "OTHER"
1115 vm['error_msg'] = "VIM status reported " + vm_vim['status']
1116 try:
1117 vm['vim_info'] = yaml.safe_dump(vm_vim, default_flow_style=True, width=256)
1118 except yaml.representer.RepresenterError:
1119 vm['vim_info'] = str(vm_vim)
1120 vm["interfaces"] = []
1121 if vm_vim.get('fault'):
1122 vm['error_msg'] = str(vm_vim['fault'])
1123 #get interfaces
1124 try:
1125 self._reload_connection()
1126 port_dict=self.neutron.list_ports(device_id=vm_id)
1127 for port in port_dict["ports"]:
1128 interface={}
1129 try:
1130 interface['vim_info'] = yaml.safe_dump(port, default_flow_style=True, width=256)
1131 except yaml.representer.RepresenterError:
1132 interface['vim_info'] = str(port)
1133 interface["mac_address"] = port.get("mac_address")
1134 interface["vim_net_id"] = port["network_id"]
1135 interface["vim_interface_id"] = port["id"]
1136 # check if OS-EXT-SRV-ATTR:host is there,
1137 # in case of non-admin credentials, it will be missing
1138 if vm_vim.get('OS-EXT-SRV-ATTR:host'):
1139 interface["compute_node"] = vm_vim['OS-EXT-SRV-ATTR:host']
1140 interface["pci"] = None
1141
1142 # check if binding:profile is there,
1143 # in case of non-admin credentials, it will be missing
1144 if port.get('binding:profile'):
1145 if port['binding:profile'].get('pci_slot'):
1146 # TODO: At the moment sr-iov pci addresses are converted to PF pci addresses by setting the slot to 0x00
1147 # TODO: This is just a workaround valid for niantinc. Find a better way to do so
1148 # CHANGE DDDD:BB:SS.F to DDDD:BB:00.(F%2) assuming there are 2 ports per nic
1149 pci = port['binding:profile']['pci_slot']
1150 # interface["pci"] = pci[:-4] + "00." + str(int(pci[-1]) % 2)
1151 interface["pci"] = pci
1152 interface["vlan"] = None
1153 #if network is of type vlan and port is of type direct (sr-iov) then set vlan id
1154 network = self.neutron.show_network(port["network_id"])
1155 if network['network'].get('provider:network_type') == 'vlan' and \
1156 port.get("binding:vnic_type") == "direct":
1157 interface["vlan"] = network['network'].get('provider:segmentation_id')
1158 ips=[]
1159 #look for floating ip address
1160 floating_ip_dict = self.neutron.list_floatingips(port_id=port["id"])
1161 if floating_ip_dict.get("floatingips"):
1162 ips.append(floating_ip_dict["floatingips"][0].get("floating_ip_address") )
1163
1164 for subnet in port["fixed_ips"]:
1165 ips.append(subnet["ip_address"])
1166 interface["ip_address"] = ";".join(ips)
1167 vm["interfaces"].append(interface)
1168 except Exception as e:
1169 self.logger.error("Error getting vm interface information " + type(e).__name__ + ": "+ str(e))
1170 except vimconn.vimconnNotFoundException as e:
1171 self.logger.error("Exception getting vm status: %s", str(e))
1172 vm['status'] = "DELETED"
1173 vm['error_msg'] = str(e)
1174 except vimconn.vimconnException as e:
1175 self.logger.error("Exception getting vm status: %s", str(e))
1176 vm['status'] = "VIM_ERROR"
1177 vm['error_msg'] = str(e)
1178 vm_dict[vm_id] = vm
1179 return vm_dict
1180
1181 def action_vminstance(self, vm_id, action_dict):
1182 '''Send and action over a VM instance from VIM
1183 Returns the vm_id if the action was successfully sent to the VIM'''
1184 self.logger.debug("Action over VM '%s': %s", vm_id, str(action_dict))
1185 try:
1186 self._reload_connection()
1187 server = self.nova.servers.find(id=vm_id)
1188 if "start" in action_dict:
1189 if action_dict["start"]=="rebuild":
1190 server.rebuild()
1191 else:
1192 if server.status=="PAUSED":
1193 server.unpause()
1194 elif server.status=="SUSPENDED":
1195 server.resume()
1196 elif server.status=="SHUTOFF":
1197 server.start()
1198 elif "pause" in action_dict:
1199 server.pause()
1200 elif "resume" in action_dict:
1201 server.resume()
1202 elif "shutoff" in action_dict or "shutdown" in action_dict:
1203 server.stop()
1204 elif "forceOff" in action_dict:
1205 server.stop() #TODO
1206 elif "terminate" in action_dict:
1207 server.delete()
1208 elif "createImage" in action_dict:
1209 server.create_image()
1210 #"path":path_schema,
1211 #"description":description_schema,
1212 #"name":name_schema,
1213 #"metadata":metadata_schema,
1214 #"imageRef": id_schema,
1215 #"disk": {"oneOf":[{"type": "null"}, {"type":"string"}] },
1216 elif "rebuild" in action_dict:
1217 server.rebuild(server.image['id'])
1218 elif "reboot" in action_dict:
1219 server.reboot() #reboot_type='SOFT'
1220 elif "console" in action_dict:
1221 console_type = action_dict["console"]
1222 if console_type == None or console_type == "novnc":
1223 console_dict = server.get_vnc_console("novnc")
1224 elif console_type == "xvpvnc":
1225 console_dict = server.get_vnc_console(console_type)
1226 elif console_type == "rdp-html5":
1227 console_dict = server.get_rdp_console(console_type)
1228 elif console_type == "spice-html5":
1229 console_dict = server.get_spice_console(console_type)
1230 else:
1231 raise vimconn.vimconnException("console type '{}' not allowed".format(console_type),
1232 http_code=vimconn.HTTP_Bad_Request)
1233 try:
1234 console_url = console_dict["console"]["url"]
1235 #parse console_url
1236 protocol_index = console_url.find("//")
1237 suffix_index = console_url[protocol_index+2:].find("/") + protocol_index+2
1238 port_index = console_url[protocol_index+2:suffix_index].find(":") + protocol_index+2
1239 if protocol_index < 0 or port_index<0 or suffix_index<0:
1240 raise vimconn.vimconnException("Unexpected response from VIM " + str(console_dict))
1241 console_dict2={"protocol": console_url[0:protocol_index],
1242 "server": console_url[protocol_index+2 : port_index],
1243 "port": int(console_url[port_index+1 : suffix_index]),
1244 "suffix": console_url[suffix_index+1:]
1245 }
1246 return console_dict2
1247 except Exception as e:
1248 raise vimconn.vimconnException("Unexpected response from VIM " + str(console_dict))
1249
1250 return vm_id
1251 except (ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.NotFound, ConnectionError) as e:
1252 self._format_exception(e)
1253 #TODO insert exception vimconn.HTTP_Unauthorized
1254
1255 #NOT USED FUNCTIONS
1256
1257 def new_external_port(self, port_data):
1258 #TODO openstack if needed
1259 '''Adds a external port to VIM'''
1260 '''Returns the port identifier'''
1261 return -vimconn.HTTP_Internal_Server_Error, "osconnector.new_external_port() not implemented"
1262
1263 def connect_port_network(self, port_id, network_id, admin=False):
1264 #TODO openstack if needed
1265 '''Connects a external port to a network'''
1266 '''Returns status code of the VIM response'''
1267 return -vimconn.HTTP_Internal_Server_Error, "osconnector.connect_port_network() not implemented"
1268
1269 def new_user(self, user_name, user_passwd, tenant_id=None):
1270 '''Adds a new user to openstack VIM'''
1271 '''Returns the user identifier'''
1272 self.logger.debug("osconnector: Adding a new user to VIM")
1273 try:
1274 self._reload_connection()
1275 user=self.keystone.users.create(user_name, user_passwd, tenant_id=tenant_id)
1276 #self.keystone.tenants.add_user(self.k_creds["username"], #role)
1277 return user.id
1278 except ksExceptions.ConnectionError as e:
1279 error_value=-vimconn.HTTP_Bad_Request
1280 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1281 except ksExceptions.ClientException as e: #TODO remove
1282 error_value=-vimconn.HTTP_Bad_Request
1283 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1284 #TODO insert exception vimconn.HTTP_Unauthorized
1285 #if reaching here is because an exception
1286 if self.debug:
1287 self.logger.debug("new_user " + error_text)
1288 return error_value, error_text
1289
1290 def delete_user(self, user_id):
1291 '''Delete a user from openstack VIM'''
1292 '''Returns the user identifier'''
1293 if self.debug:
1294 print "osconnector: Deleting a user from VIM"
1295 try:
1296 self._reload_connection()
1297 self.keystone.users.delete(user_id)
1298 return 1, user_id
1299 except ksExceptions.ConnectionError as e:
1300 error_value=-vimconn.HTTP_Bad_Request
1301 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1302 except ksExceptions.NotFound as e:
1303 error_value=-vimconn.HTTP_Not_Found
1304 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1305 except ksExceptions.ClientException as e: #TODO remove
1306 error_value=-vimconn.HTTP_Bad_Request
1307 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1308 #TODO insert exception vimconn.HTTP_Unauthorized
1309 #if reaching here is because an exception
1310 if self.debug:
1311 print "delete_tenant " + error_text
1312 return error_value, error_text
1313
1314 def get_hosts_info(self):
1315 '''Get the information of deployed hosts
1316 Returns the hosts content'''
1317 if self.debug:
1318 print "osconnector: Getting Host info from VIM"
1319 try:
1320 h_list=[]
1321 self._reload_connection()
1322 hypervisors = self.nova.hypervisors.list()
1323 for hype in hypervisors:
1324 h_list.append( hype.to_dict() )
1325 return 1, {"hosts":h_list}
1326 except nvExceptions.NotFound as e:
1327 error_value=-vimconn.HTTP_Not_Found
1328 error_text= (str(e) if len(e.args)==0 else str(e.args[0]))
1329 except (ksExceptions.ClientException, nvExceptions.ClientException) as e:
1330 error_value=-vimconn.HTTP_Bad_Request
1331 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1332 #TODO insert exception vimconn.HTTP_Unauthorized
1333 #if reaching here is because an exception
1334 if self.debug:
1335 print "get_hosts_info " + error_text
1336 return error_value, error_text
1337
1338 def get_hosts(self, vim_tenant):
1339 '''Get the hosts and deployed instances
1340 Returns the hosts content'''
1341 r, hype_dict = self.get_hosts_info()
1342 if r<0:
1343 return r, hype_dict
1344 hypervisors = hype_dict["hosts"]
1345 try:
1346 servers = self.nova.servers.list()
1347 for hype in hypervisors:
1348 for server in servers:
1349 if server.to_dict()['OS-EXT-SRV-ATTR:hypervisor_hostname']==hype['hypervisor_hostname']:
1350 if 'vm' in hype:
1351 hype['vm'].append(server.id)
1352 else:
1353 hype['vm'] = [server.id]
1354 return 1, hype_dict
1355 except nvExceptions.NotFound as e:
1356 error_value=-vimconn.HTTP_Not_Found
1357 error_text= (str(e) if len(e.args)==0 else str(e.args[0]))
1358 except (ksExceptions.ClientException, nvExceptions.ClientException) as e:
1359 error_value=-vimconn.HTTP_Bad_Request
1360 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1361 #TODO insert exception vimconn.HTTP_Unauthorized
1362 #if reaching here is because an exception
1363 if self.debug:
1364 print "get_hosts " + error_text
1365 return error_value, error_text
1366
1367