blob: a1146413e8f2131c30e9a291820a04d7e427168f [file] [log] [blame]
tierno7edb6752016-03-21 17:37:52 +01001# -*- 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'''
25osconnector implements all the methods to interact with openstack using the python-client.
26'''
montesmoreno0c8def02016-12-22 12:16:23 +000027__author__="Alfonso Tierno, Gerardo Garcia, Pablo Montes, xFlow Research"
28__date__ ="$22-jun-2014 11:19:29$"
tierno7edb6752016-03-21 17:37:52 +010029
30import vimconn
31import json
32import yaml
tiernoae4a8d12016-07-08 12:30:39 +020033import logging
garciadeblas9f8456e2016-09-05 05:02:59 +020034import netaddr
montesmoreno0c8def02016-12-22 12:16:23 +000035import time
tierno36c0b172017-01-12 18:32:28 +010036import yaml
tierno7edb6752016-03-21 17:37:52 +010037
ahmadsa96af9f42017-01-31 16:17:14 +050038from novaclient import client as nClient_v2, exceptions as nvExceptions
39from novaclient import api_versions
ahmadsa95baa272016-11-30 09:14:11 +050040import keystoneclient.v2_0.client as ksClient_v2
41from novaclient.v2.client import Client as nClient
42import keystoneclient.v3.client as ksClient
tierno7edb6752016-03-21 17:37:52 +010043import keystoneclient.exceptions as ksExceptions
44import glanceclient.v2.client as glClient
45import glanceclient.client as gl1Client
46import glanceclient.exc as gl1Exceptions
montesmoreno0c8def02016-12-22 12:16:23 +000047import cinderclient.v2.client as cClient_v2
tierno7edb6752016-03-21 17:37:52 +010048from httplib import HTTPException
ahmadsa95baa272016-11-30 09:14:11 +050049from neutronclient.neutron import client as neClient_v2
50from neutronclient.v2_0 import client as neClient
tierno7edb6752016-03-21 17:37:52 +010051from neutronclient.common import exceptions as neExceptions
52from requests.exceptions import ConnectionError
53
54'''contain the openstack virtual machine status to openmano status'''
55vmStatus2manoFormat={'ACTIVE':'ACTIVE',
56 'PAUSED':'PAUSED',
57 'SUSPENDED': 'SUSPENDED',
58 'SHUTOFF':'INACTIVE',
59 'BUILD':'BUILD',
60 'ERROR':'ERROR','DELETED':'DELETED'
61 }
62netStatus2manoFormat={'ACTIVE':'ACTIVE','PAUSED':'PAUSED','INACTIVE':'INACTIVE','BUILD':'BUILD','ERROR':'ERROR','DELETED':'DELETED'
63 }
64
montesmoreno0c8def02016-12-22 12:16:23 +000065#global var to have a timeout creating and deleting volumes
66volume_timeout = 60
montesmoreno2a1fc4e2017-01-09 16:46:04 +000067server_timeout = 60
montesmoreno0c8def02016-12-22 12:16:23 +000068
tierno7edb6752016-03-21 17:37:52 +010069class vimconnector(vimconn.vimconnector):
tiernofe789902016-09-29 14:20:44 +000070 def __init__(self, uuid, name, tenant_id, tenant_name, url, url_admin=None, user=None, passwd=None, log_level=None, config={}):
ahmadsa96af9f42017-01-31 16:17:14 +050071 '''using common constructor parameters. In this case
tierno7edb6752016-03-21 17:37:52 +010072 'url' is the keystone authorization url,
73 'url_admin' is not use
74 '''
ahmadsa95baa272016-11-30 09:14:11 +050075 self.osc_api_version = 'v2.0'
76 if config.get('APIversion') == 'v3.3':
77 self.osc_api_version = 'v3.3'
tiernoae4a8d12016-07-08 12:30:39 +020078 vimconn.vimconnector.__init__(self, uuid, name, tenant_id, tenant_name, url, url_admin, user, passwd, log_level, config)
tierno7edb6752016-03-21 17:37:52 +010079
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
tierno392f2852016-05-13 12:28:55 +020086 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
tierno7edb6752016-03-21 17:37:52 +010092 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
ahmadsa95baa272016-11-30 09:14:11 +050098 if self.osc_api_version == 'v3.3':
99 self.k_creds['project_name'] = tenant_name
100 self.k_creds['project_id'] = tenant_id
montesmorenocf227142017-01-12 12:24:21 +0000101 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')
montesmoreno0c8def02016-12-22 12:16:23 +0000104
tierno7edb6752016-03-21 17:37:52 +0100105 self.reload_client = True
tierno73ad9e42016-09-12 18:11:11 +0200106 self.logger = logging.getLogger('openmano.vim.openstack')
tiernofe789902016-09-29 14:20:44 +0000107 if log_level:
108 self.logger.setLevel( getattr(logging, log_level) )
tierno7edb6752016-03-21 17:37:52 +0100109
110 def __setitem__(self,index, value):
111 '''Set individuals parameters
112 Throw TypeError, KeyError
113 '''
tierno392f2852016-05-13 12:28:55 +0200114 if index=='tenant_id':
tierno7edb6752016-03-21 17:37:52 +0100115 self.reload_client=True
tierno392f2852016-05-13 12:28:55 +0200116 self.tenant_id = value
ahmadsa95baa272016-11-30 09:14:11 +0500117 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']
tierno392f2852016-05-13 12:28:55 +0200124 else:
ahmadsa95baa272016-11-30 09:14:11 +0500125 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']
tierno392f2852016-05-13 12:28:55 +0200131 elif index=='tenant_name':
132 self.reload_client=True
133 self.tenant_name = value
ahmadsa95baa272016-11-30 09:14:11 +0500134 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']
tierno7edb6752016-03-21 17:37:52 +0100141 else:
ahmadsa95baa272016-11-30 09:14:11 +0500142 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']
tierno7edb6752016-03-21 17:37:52 +0100148 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")
ahmadsa95baa272016-11-30 09:14:11 +0500186 if self.osc_api_version == 'v3.3':
ahmadsa96af9f42017-01-31 16:17:14 +0500187 self.nova = nClient(api_version=api_versions.APIVersion(version_str='2.0'), **self.n_creds)
montesmoreno0c8def02016-12-22 12:16:23 +0000188 #TODO To be updated for v3
189 #self.cinder = cClient.Client(**self.n_creds)
ahmadsa95baa272016-11-30 09:14:11 +0500190 self.keystone = ksClient.Client(**self.k_creds)
191 self.ne_endpoint=self.keystone.service_catalog.url_for(service_type='network', endpoint_type='publicURL')
ahmadsa96af9f42017-01-31 16:17:14 +0500192 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)
ahmadsa95baa272016-11-30 09:14:11 +0500193 else:
ahmadsa96af9f42017-01-31 16:17:14 +0500194 self.nova = nClient_v2.Client(version='2', **self.n_creds)
montesmoreno0c8def02016-12-22 12:16:23 +0000195 self.cinder = cClient_v2.Client(**self.n_creds)
ahmadsa95baa272016-11-30 09:14:11 +0500196 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)
tierno7edb6752016-03-21 17:37:52 +0100199 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
tierno7edb6752016-03-21 17:37:52 +0100201 self.reload_client = False
ahmadsa95baa272016-11-30 09:14:11 +0500202
tierno7edb6752016-03-21 17:37:52 +0100203 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'
tiernoae4a8d12016-07-08 12:30:39 +0200217
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,
tierno8e995ce2016-09-22 08:13:00 +0000223 ConnectionError, ksExceptions.ConnectionError, neExceptions.ConnectionFailed
224 )):
tiernoae4a8d12016-07-08 12:30:39 +0200225 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 '''
ahmadsa95baa272016-11-30 09:14:11 +0500244 self.logger.debug("Getting tenants from VIM filter: '%s'", str(filter_dict))
tiernoae4a8d12016-07-08 12:30:39 +0200245 try:
246 self._reload_connection()
montesmoreno0c8def02016-12-22 12:16:23 +0000247 if self.osc_api_version == 'v3.3':
ahmadsa95baa272016-11-30 09:14:11 +0500248 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
tierno8e995ce2016-09-22 08:13:00 +0000255 except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200256 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()
ahmadsa95baa272016-11-30 09:14:11 +0500263 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
tierno8e995ce2016-09-22 08:13:00 +0000268 except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200269 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()
montesmoreno0c8def02016-12-22 12:16:23 +0000276 if self.osc_api_version == 'v3.3':
ahmadsa95baa272016-11-30 09:14:11 +0500277 self.keystone.projects.delete(tenant_id)
278 else:
279 self.keystone.tenants.delete(tenant_id)
tiernoae4a8d12016-07-08 12:30:39 +0200280 return tenant_id
tierno8e995ce2016-09-22 08:13:00 +0000281 except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200282 self._format_exception(e)
ahmadsa95baa272016-11-30 09:14:11 +0500283
garciadeblas9f8456e2016-09-05 05:02:59 +0200284 def new_network(self,net_name, net_type, ip_profile=None, shared=False, vlan=None):
tiernoae4a8d12016-07-08 12:30:39 +0200285 '''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)
garciadeblasedca7b32016-09-29 14:01:52 +0000287 #self.logger.debug(">>>>>>>>>>>>>>>>>> IP profile %s", str(ip_profile))
tierno7edb6752016-03-21 17:37:52 +0100288 try:
garciadeblasedca7b32016-09-29 14:01:52 +0000289 new_net = None
tierno7edb6752016-03-21 17:37:52 +0100290 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:
tiernoae4a8d12016-07-08 12:30:39 +0200294 raise vimconn.vimconnConflictException("You must provide a 'dataplane_physical_net' at config value before creating sriov network")
tierno7edb6752016-03-21 17:37:52 +0100295 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
tiernoae4a8d12016-07-08 12:30:39 +0200299 network_dict["shared"]=shared
tierno7edb6752016-03-21 17:37:52 +0100300 new_net=self.neutron.create_network({'network':network_dict})
301 #print new_net
garciadeblas9f8456e2016-09-05 05:02:59 +0200302 #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"
tierno7edb6752016-03-21 17:37:52 +0100310 subnet={"name":net_name+"-subnet",
311 "network_id": new_net["network"]["id"],
garciadeblas9f8456e2016-09-05 05:02:59 +0200312 "ip_version": 4 if ip_profile['ip_version']=="IPv4" else 6,
313 "cidr": ip_profile['subnet_address']
tierno7edb6752016-03-21 17:37:52 +0100314 }
garciadeblas9f8456e2016-09-05 05:02:59 +0200315 if 'gateway_address' in ip_profile:
316 subnet['gateway_ip'] = ip_profile['gateway_address']
garciadeblasedca7b32016-09-29 14:01:52 +0000317 if ip_profile.get('dns_address'):
garciadeblas9f8456e2016-09-05 05:02:59 +0200318 #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']))
garciadeblas21d795b2016-09-29 17:31:46 +0200331 ip_int += ip_profile['dhcp_count'] - 1
garciadeblas9f8456e2016-09-05 05:02:59 +0200332 ip_str = str(netaddr.IPAddress(ip_int))
333 subnet['allocation_pools'][0]['end'] = ip_str
garciadeblasedca7b32016-09-29 14:01:52 +0000334 #self.logger.debug(">>>>>>>>>>>>>>>>>> Subnet: %s", str(subnet))
tierno7edb6752016-03-21 17:37:52 +0100335 self.neutron.create_subnet({"subnet": subnet} )
tiernoae4a8d12016-07-08 12:30:39 +0200336 return new_net["network"]["id"]
tierno8e995ce2016-09-22 08:13:00 +0000337 except (neExceptions.ConnectionFailed, ksExceptions.ClientException, neExceptions.NeutronException, ConnectionError) as e:
garciadeblasedca7b32016-09-29 14:01:52 +0000338 if new_net:
339 self.neutron.delete_network(new_net['network']['id'])
tiernoae4a8d12016-07-08 12:30:39 +0200340 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100341
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 '''
tiernoae4a8d12016-07-08 12:30:39 +0200353 self.logger.debug("Getting network from VIM filter: '%s'", str(filter_dict))
tierno7edb6752016-03-21 17:37:52 +0100354 try:
355 self._reload_connection()
montesmoreno0c8def02016-12-22 12:16:23 +0000356 if self.osc_api_version == 'v3.3' and "tenant_id" in filter_dict:
ahmadsa95baa272016-11-30 09:14:11 +0500357 filter_dict['project_id'] = filter_dict.pop('tenant_id')
tierno7edb6752016-03-21 17:37:52 +0100358 net_dict=self.neutron.list_networks(**filter_dict)
359 net_list=net_dict["networks"]
360 self.__net_os2mano(net_list)
tiernoae4a8d12016-07-08 12:30:39 +0200361 return net_list
tierno8e995ce2016-09-22 08:13:00 +0000362 except (neExceptions.ConnectionFailed, ksExceptions.ClientException, neExceptions.NeutronException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200363 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100364
tiernoae4a8d12016-07-08 12:30:39 +0200365 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)
tierno7edb6752016-03-21 17:37:52 +0100369 filter_dict={"id": net_id}
tiernoae4a8d12016-07-08 12:30:39 +0200370 net_list = self.get_network_list(filter_dict)
tierno7edb6752016-03-21 17:37:52 +0100371 if len(net_list)==0:
tiernoae4a8d12016-07-08 12:30:39 +0200372 raise vimconn.vimconnNotFoundException("Network '{}' not found".format(net_id))
tierno7edb6752016-03-21 17:37:52 +0100373 elif len(net_list)>1:
tiernoae4a8d12016-07-08 12:30:39 +0200374 raise vimconn.vimconnConflictException("Found more than one network with this criteria")
tierno7edb6752016-03-21 17:37:52 +0100375 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:
tiernoae4a8d12016-07-08 12:30:39 +0200381 self.logger.error("osconnector.get_network(): Error getting subnet %s %s" % (net_id, str(e)))
382 subnet = {"id": subnet_id, "fault": str(e)}
tierno7edb6752016-03-21 17:37:52 +0100383 subnets.append(subnet)
384 net["subnets"] = subnets
tiernoae4a8d12016-07-08 12:30:39 +0200385 return net
tierno7edb6752016-03-21 17:37:52 +0100386
tiernoae4a8d12016-07-08 12:30:39 +0200387 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)
tierno7edb6752016-03-21 17:37:52 +0100390 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:
tiernoae4a8d12016-07-08 12:30:39 +0200398 self.logger.error("Error deleting port %s: %s", p["id"], str(e))
tierno7edb6752016-03-21 17:37:52 +0100399 self.neutron.delete_network(net_id)
tiernoae4a8d12016-07-08 12:30:39 +0200400 return net_id
401 except (neExceptions.ConnectionFailed, neExceptions.NetworkNotFoundClient, neExceptions.NeutronException,
tierno8e995ce2016-09-22 08:13:00 +0000402 ksExceptions.ClientException, neExceptions.NeutronException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200403 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100404
tiernoae4a8d12016-07-08 12:30:39 +0200405 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
tierno8e995ce2016-09-22 08:13:00 +0000433 if net['status'] == "ACTIVE" and not net_vim['admin_state_up']:
tiernoae4a8d12016-07-08 12:30:39 +0200434 net['status'] = 'DOWN'
tierno8e995ce2016-09-22 08:13:00 +0000435 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)
tiernoae4a8d12016-07-08 12:30:39 +0200439 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)
tierno7edb6752016-03-21 17:37:52 +0100455 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)
tiernoae4a8d12016-07-08 12:30:39 +0200459 return flavor.to_dict()
tierno8e995ce2016-09-22 08:13:00 +0000460 except (nvExceptions.NotFound, nvExceptions.ClientException, ksExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200461 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100462
tiernoae4a8d12016-07-08 12:30:39 +0200463 def new_flavor(self, flavor_data, change_name_if_used=True):
tierno7edb6752016-03-21 17:37:52 +0100464 '''Adds a tenant flavor to openstack VIM
tiernoae4a8d12016-07-08 12:30:39 +0200465 if change_name_if_used is True, it will change name in case of conflict, because it is not supported name repetition
tierno7edb6752016-03-21 17:37:52 +0100466 Returns the flavor identifier
467 '''
tiernoae4a8d12016-07-08 12:30:39 +0200468 self.logger.debug("Adding flavor '%s'", str(flavor_data))
tierno7edb6752016-03-21 17:37:52 +0100469 retry=0
tiernoae4a8d12016-07-08 12:30:39 +0200470 max_retries=3
tierno7edb6752016-03-21 17:37:52 +0100471 name_suffix = 0
tiernoae4a8d12016-07-08 12:30:39 +0200472 name=flavor_data['name']
473 while retry<max_retries:
tierno7edb6752016-03-21 17:37:52 +0100474 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
tiernoae4a8d12016-07-08 12:30:39 +0200485 name = flavor_data['name']+"-" + str(name_suffix)
tierno7edb6752016-03-21 17:37:52 +0100486
tiernoae4a8d12016-07-08 12:30:39 +0200487 ram = flavor_data.get('ram',64)
488 vcpus = flavor_data.get('vcpus',1)
tierno7edb6752016-03-21 17:37:52 +0100489 numa_properties=None
490
tiernoae4a8d12016-07-08 12:30:39 +0200491 extended = flavor_data.get("extended")
tierno7edb6752016-03-21 17:37:52 +0100492 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":
tierno809a7802016-07-08 13:31:24 +0200516 raise vimconn.vimconnException("Passthrough interfaces are not supported for the openstack connector", http_code=vimconn.HTTP_Service_Unavailable)
tierno7edb6752016-03-21 17:37:52 +0100517 #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,
tiernoae4a8d12016-07-08 12:30:39 +0200523 flavor_data.get('disk',1),
524 is_public=flavor_data.get('is_public', True)
tierno7edb6752016-03-21 17:37:52 +0100525 )
526 #add metadata
527 if numa_properties:
528 new_flavor.set_keys(numa_properties)
tiernoae4a8d12016-07-08 12:30:39 +0200529 return new_flavor.id
tierno7edb6752016-03-21 17:37:52 +0100530 except nvExceptions.Conflict as e:
tiernoae4a8d12016-07-08 12:30:39 +0200531 if change_name_if_used and retry < max_retries:
tierno7edb6752016-03-21 17:37:52 +0100532 continue
tiernoae4a8d12016-07-08 12:30:39 +0200533 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100534 #except nvExceptions.BadRequest as e:
535 except (ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200536 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100537
tiernoae4a8d12016-07-08 12:30:39 +0200538 def delete_flavor(self,flavor_id):
539 '''Deletes a tenant flavor from openstack VIM. Returns the old flavor_id
tierno7edb6752016-03-21 17:37:52 +0100540 '''
tiernoae4a8d12016-07-08 12:30:39 +0200541 try:
542 self._reload_connection()
543 self.nova.flavors.delete(flavor_id)
544 return flavor_id
545 #except nvExceptions.BadRequest as e:
tierno8e995ce2016-09-22 08:13:00 +0000546 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200547 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100548
tiernoae4a8d12016-07-08 12:30:39 +0200549 def new_image(self,image_dict):
tierno7edb6752016-03-21 17:37:52 +0100550 '''
tiernoae4a8d12016-07-08 12:30:39 +0200551 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
tierno7edb6752016-03-21 17:37:52 +0100558 '''
tierno7edb6752016-03-21 17:37:52 +0100559 #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
tiernoae4a8d12016-07-08 12:30:39 +0200561 retry=0
562 max_retries=3
563 while retry<max_retries:
tierno7edb6752016-03-21 17:37:52 +0100564 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"]
garciadeblas14480452017-01-10 13:08:07 +0100570 else: #autodiscover based on extension
tierno7edb6752016-03-21 17:37:52 +0100571 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"
tiernoae4a8d12016-07-08 12:30:39 +0200589 self.logger.debug("new_image: '%s' loading from '%s'", image_dict['name'], image_dict['location'])
tierno7edb6752016-03-21 17:37:52 +0100590 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)
tiernoae4a8d12016-07-08 12:30:39 +0200605 return new_image.id
606 except (nvExceptions.Conflict, ksExceptions.ClientException, nvExceptions.ClientException) as e:
607 self._format_exception(e)
tierno8e995ce2016-09-22 08:13:00 +0000608 except (HTTPException, gl1Exceptions.HTTPException, gl1Exceptions.CommunicationError, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200609 if retry==max_retries:
610 continue
611 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100612 except IOError as e: #can not open the file
tiernoae4a8d12016-07-08 12:30:39 +0200613 raise vimconn.vimconnConnectionException(type(e).__name__ + ": " + str(e)+ " for " + image_dict['location'],
614 http_code=vimconn.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100615
tiernoae4a8d12016-07-08 12:30:39 +0200616 def delete_image(self, image_id):
617 '''Deletes a tenant image from openstack VIM. Returns the old id
tierno7edb6752016-03-21 17:37:52 +0100618 '''
tiernoae4a8d12016-07-08 12:30:39 +0200619 try:
620 self._reload_connection()
621 self.nova.images.delete(image_id)
622 return image_id
tierno8e995ce2016-09-22 08:13:00 +0000623 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e: #TODO remove
tiernoae4a8d12016-07-08 12:30:39 +0200624 self._format_exception(e)
625
626 def get_image_id_from_path(self, path):
garciadeblasb69fa9f2016-09-28 12:04:10 +0200627 '''Get the image id from image path in the VIM database. Returns the image_id'''
tiernoae4a8d12016-07-08 12:30:39 +0200628 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))
tierno8e995ce2016-09-22 08:13:00 +0000635 except (ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200636 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100637
garciadeblasb69fa9f2016-09-28 12:04:10 +0200638 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:
garciadeblasbb6a1ed2016-09-30 14:02:09 +0000660 image_dict=self.glance.images.get(image.id)
garciadeblas14480452017-01-10 13:08:07 +0100661 if 'checksum' not in filter_dict or image_dict['checksum']==filter_dict.get('checksum'):
662 filtered_list.append(image_dict)
garciadeblasb69fa9f2016-09-28 12:04:10 +0200663 return filtered_list
664 except (ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e:
665 self._format_exception(e)
666
montesmoreno0c8def02016-12-22 12:16:23 +0000667 def new_vminstance(self,name,description,start,image_id,flavor_id,net_list,cloud_config=None,disk_list=None):
tierno7edb6752016-03-21 17:37:52 +0100668 '''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
ahmadsaf853d452016-12-22 11:33:47 +0500681 floating_ip: True/False (or it can be None)
tierno7edb6752016-03-21 17:37:52 +0100682 #TODO ip, security groups
tiernoae4a8d12016-07-08 12:30:39 +0200683 Returns the instance identifier
tierno7edb6752016-03-21 17:37:52 +0100684 '''
tiernoae4a8d12016-07-08 12:30:39 +0200685 self.logger.debug("Creating VM image '%s' flavor '%s' nics='%s'",image_id, flavor_id,str(net_list))
tierno7edb6752016-03-21 17:37:52 +0100686 try:
tierno6e116232016-07-18 13:01:40 +0200687 metadata={}
tierno7edb6752016-03-21 17:37:52 +0100688 net_list_vim=[]
ahmadsaf853d452016-12-22 11:33:47 +0500689 external_network=[] #list of external networks to be connected to instance, later on used to create floating_ip
tierno7edb6752016-03-21 17:37:52 +0100690 self._reload_connection()
tiernoae4a8d12016-07-08 12:30:39 +0200691 metadata_vpci={} #For a specific neutron plugin
tierno7edb6752016-03-21 17:37:52 +0100692 for net in net_list:
693 if not net.get("net_id"): #skip non connected iface
694 continue
ahmadsaf853d452016-12-22 11:33:47 +0500695 if net["type"]=="virtual" or net["type"]=="VF":
tierno7edb6752016-03-21 17:37:52 +0100696 port_dict={
ahmadsaf853d452016-12-22 11:33:47 +0500697 "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"
tierno7edb6752016-03-21 17:37:52 +0100710 if not port_dict["name"]:
ahmadsaf853d452016-12-22 11:33:47 +0500711 port_dict["name"]=name
tierno7edb6752016-03-21 17:37:52 +0100712 if net.get("mac_address"):
713 port_dict["mac_address"]=net["mac_address"]
montesmorenocf227142017-01-12 12:24:21 +0000714 if net.get("port_security") == False:
montesmoreno2a1fc4e2017-01-09 16:46:04 +0000715 port_dict["port_security_enabled"]=net["port_security"]
tierno7edb6752016-03-21 17:37:52 +0100716 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"]
ahmadsaf853d452016-12-22 11:33:47 +0500719 net["ip"] = new_port["port"].get("fixed_ips", [{}])[0].get("ip_address")
tierno7edb6752016-03-21 17:37:52 +0100720 net_list_vim.append({"port-id": new_port["port"]["id"]})
ahmadsaf853d452016-12-22 11:33:47 +0500721 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
tierno7edb6752016-03-21 17:37:52 +0100727 if metadata_vpci:
728 metadata = {"pci_assignement": json.dumps(metadata_vpci)}
tiernoafbced42016-07-23 01:43:53 +0200729 if len(metadata["pci_assignement"]) >255:
tierno6e116232016-07-18 13:01:40 +0200730 #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 = {}
tierno7edb6752016-03-21 17:37:52 +0100734
tiernoae4a8d12016-07-08 12:30:39 +0200735 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))
tierno7edb6752016-03-21 17:37:52 +0100737
738 security_groups = self.config.get('security_groups')
739 if type(security_groups) is str:
740 security_groups = ( security_groups, )
tierno36c0b172017-01-12 18:32:28 +0100741 #cloud config
742 userdata=None
743 config_drive = None
tiernoa4e1a6e2016-08-31 14:19:40 +0200744 if isinstance(cloud_config, dict):
tierno36c0b172017-01-12 18:32:28 +0100745 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)
tiernoa4e1a6e2016-08-31 14:19:40 +0200787 self.logger.debug("userdata: %s", userdata)
788 elif isinstance(cloud_config, str):
789 userdata = cloud_config
montesmoreno0c8def02016-12-22 12:16:23 +0000790
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:
montesmorenocf227142017-01-12 12:24:21 +0000827 self.neutron.delete_port(net_item['port-id'])
montesmoreno0c8def02016-12-22 12:16:23 +0000828
829 raise vimconn.vimconnException('Timeout creating volumes for instance ' + name,
830 http_code=vimconn.HTTP_Request_Timeout)
831
tierno7edb6752016-03-21 17:37:52 +0100832 server = self.nova.servers.create(name, image_id, flavor_id, nics=net_list_vim, meta=metadata,
montesmoreno0c8def02016-12-22 12:16:23 +0000833 security_groups=security_groups,
834 availability_zone=self.config.get('availability_zone'),
835 key_name=self.config.get('keypair'),
836 userdata=userdata,
tierno36c0b172017-01-12 18:32:28 +0100837 config_drive = config_drive,
montesmoreno0c8def02016-12-22 12:16:23 +0000838 block_device_mapping = block_device_mapping
839 ) # , description=description)
tiernoae4a8d12016-07-08 12:30:39 +0200840 #print "DONE :-)", server
ahmadsaf853d452016-12-22 11:33:47 +0500841 pool_id = None
842 floating_ips = self.neutron.list_floatingips().get("floatingips", ())
843 for floating_network in external_network:
montesmoreno2a1fc4e2017-01-09 16:46:04 +0000844 # 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
ahmadsaf853d452016-12-22 11:33:47 +0500859 assigned = False
860 while(assigned == False):
861 if floating_ips:
862 ip = floating_ips.pop(0)
montesmoreno2a1fc4e2017-01-09 16:46:04 +0000863 if not ip.get("port_id", False) and ip.get('tenant_id') == server.tenant_id:
ahmadsaf853d452016-12-22 11:33:47 +0500864 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:
montesmoreno2a1fc4e2017-01-09 16:46:04 +0000873 #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}}
ahmadsaf853d452016-12-22 11:33:47 +0500892 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)
tierno7edb6752016-03-21 17:37:52 +0100902
tiernoae4a8d12016-07-08 12:30:39 +0200903 return server.id
tierno7edb6752016-03-21 17:37:52 +0100904# except nvExceptions.NotFound as e:
905# error_value=-vimconn.HTTP_Not_Found
906# error_text= "vm instance %s not found" % vm_id
tierno8e995ce2016-09-22 08:13:00 +0000907 except (ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError
908 ) as e:
montesmoreno2a1fc4e2017-01-09 16:46:04 +0000909 # 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:
montesmorenocf227142017-01-12 12:24:21 +0000917 self.neutron.delete_port(net_item['port-id'])
tiernoae4a8d12016-07-08 12:30:39 +0200918 self._format_exception(e)
919 except TypeError as e:
920 raise vimconn.vimconnException(type(e).__name__ + ": "+ str(e), http_code=vimconn.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100921
tiernoae4a8d12016-07-08 12:30:39 +0200922 def get_vminstance(self,vm_id):
tierno7edb6752016-03-21 17:37:52 +0100923 '''Returns the VM instance information from VIM'''
tiernoae4a8d12016-07-08 12:30:39 +0200924 #self.logger.debug("Getting VM from VIM")
tierno7edb6752016-03-21 17:37:52 +0100925 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)
tiernoae4a8d12016-07-08 12:30:39 +0200929 return server.to_dict()
tierno8e995ce2016-09-22 08:13:00 +0000930 except (ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.NotFound, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200931 self._format_exception(e)
932
933 def get_vminstance_console(self,vm_id, console_type="vnc"):
tierno7edb6752016-03-21 17:37:52 +0100934 '''
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
tiernoae4a8d12016-07-08 12:30:39 +0200941 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
tierno7edb6752016-03-21 17:37:52 +0100946 '''
tiernoae4a8d12016-07-08 12:30:39 +0200947 self.logger.debug("Getting VM CONSOLE from VIM")
tierno7edb6752016-03-21 17:37:52 +0100948 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:
tiernoae4a8d12016-07-08 12:30:39 +0200960 raise vimconn.vimconnException("console type '{}' not allowed".format(console_type), http_code=vimconn.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100961
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
tiernoae4a8d12016-07-08 12:30:39 +0200978 return console_dict
979 raise vimconn.vimconnUnexpectedResponse("Unexpected response from VIM")
tierno7edb6752016-03-21 17:37:52 +0100980
tierno8e995ce2016-09-22 08:13:00 +0000981 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.BadRequest, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200982 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100983
tiernoae4a8d12016-07-08 12:30:39 +0200984 def delete_vminstance(self, vm_id):
985 '''Removes a VM instance from VIM. Returns the old identifier
tierno7edb6752016-03-21 17:37:52 +0100986 '''
tiernoae4a8d12016-07-08 12:30:39 +0200987 #print "osconnector: Getting VM from VIM"
tierno7edb6752016-03-21 17:37:52 +0100988 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:
tiernoae4a8d12016-07-08 12:30:39 +0200996 self.logger.error("Error deleting port: " + type(e).__name__ + ": "+ str(e))
montesmoreno0c8def02016-12-22 12:16:23 +0000997
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
tierno7edb6752016-03-21 17:37:52 +01001005 self.nova.servers.delete(vm_id)
montesmoreno0c8def02016-12-22 12:16:23 +00001006
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
tiernoae4a8d12016-07-08 12:30:39 +02001023 return vm_id
tierno8e995ce2016-09-22 08:13:00 +00001024 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001025 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001026 #TODO insert exception vimconn.HTTP_Unauthorized
1027 #if reaching here is because an exception
tierno7edb6752016-03-21 17:37:52 +01001028
tiernoae4a8d12016-07-08 12:30:39 +02001029 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
tierno7edb6752016-03-21 17:37:52 +01001051 '''
tiernoae4a8d12016-07-08 12:30:39 +02001052 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'] ]
tierno7edb6752016-03-21 17:37:52 +01001060 else:
tiernoae4a8d12016-07-08 12:30:39 +02001061 vm['status'] = "OTHER"
1062 vm['error_msg'] = "VIM status reported " + vm_vim['status']
tierno8e995ce2016-09-22 08:13:00 +00001063 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)
tiernoae4a8d12016-07-08 12:30:39 +02001067 vm["interfaces"] = []
1068 if vm_vim.get('fault'):
1069 vm['error_msg'] = str(vm_vim['fault'])
1070 #get interfaces
tierno7edb6752016-03-21 17:37:52 +01001071 try:
tiernoae4a8d12016-07-08 12:30:39 +02001072 self._reload_connection()
1073 port_dict=self.neutron.list_ports(device_id=vm_id)
1074 for port in port_dict["ports"]:
1075 interface={}
tierno8e995ce2016-09-22 08:13:00 +00001076 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)
tiernoae4a8d12016-07-08 12:30:39 +02001080 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") )
tierno7edb6752016-03-21 17:37:52 +01001088
tiernoae4a8d12016-07-08 12:30:39 +02001089 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
tierno7edb6752016-03-21 17:37:52 +01001105
tiernoae4a8d12016-07-08 12:30:39 +02001106 def action_vminstance(self, vm_id, action_dict):
tierno7edb6752016-03-21 17:37:52 +01001107 '''Send and action over a VM instance from VIM
tiernoae4a8d12016-07-08 12:30:39 +02001108 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))
tierno7edb6752016-03-21 17:37:52 +01001110 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:
tiernoae4a8d12016-07-08 12:30:39 +02001156 raise vimconn.vimconnException("console type '{}' not allowed".format(console_type),
1157 http_code=vimconn.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001158 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:
tiernoae4a8d12016-07-08 12:30:39 +02001165 raise vimconn.vimconnException("Unexpected response from VIM " + str(console_dict))
tierno7edb6752016-03-21 17:37:52 +01001166 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 }
tiernoae4a8d12016-07-08 12:30:39 +02001171 return console_dict2
1172 except Exception as e:
1173 raise vimconn.vimconnException("Unexpected response from VIM " + str(console_dict))
tierno7edb6752016-03-21 17:37:52 +01001174
tiernoae4a8d12016-07-08 12:30:39 +02001175 return vm_id
tierno8e995ce2016-09-22 08:13:00 +00001176 except (ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.NotFound, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001177 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
tierno7edb6752016-03-21 17:37:52 +01001207 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:
tiernoae4a8d12016-07-08 12:30:39 +02001212 self.logger.debug("new_user " + error_text)
tierno7edb6752016-03-21 17:37:52 +01001213 return error_value, error_text
tiernoae4a8d12016-07-08 12:30:39 +02001214
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
tierno7edb6752016-03-21 17:37:52 +01001239 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
tierno7edb6752016-03-21 17:37:52 +01001292