blob: de94fff00bd15d82c7e52b374cd833380e3ffbce [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
garciadeblas2299e3b2017-01-26 14:35:55 +000037import random
tierno7edb6752016-03-21 17:37:52 +010038
ahmadsa96af9f42017-01-31 16:17:14 +050039from novaclient import client as nClient_v2, exceptions as nvExceptions
40from novaclient import api_versions
ahmadsa95baa272016-11-30 09:14:11 +050041import keystoneclient.v2_0.client as ksClient_v2
42from novaclient.v2.client import Client as nClient
43import keystoneclient.v3.client as ksClient
tierno7edb6752016-03-21 17:37:52 +010044import keystoneclient.exceptions as ksExceptions
45import glanceclient.v2.client as glClient
46import glanceclient.client as gl1Client
47import glanceclient.exc as gl1Exceptions
montesmoreno0c8def02016-12-22 12:16:23 +000048import cinderclient.v2.client as cClient_v2
tierno7edb6752016-03-21 17:37:52 +010049from httplib import HTTPException
ahmadsa95baa272016-11-30 09:14:11 +050050from neutronclient.neutron import client as neClient_v2
51from neutronclient.v2_0 import client as neClient
tierno7edb6752016-03-21 17:37:52 +010052from neutronclient.common import exceptions as neExceptions
53from requests.exceptions import ConnectionError
54
55'''contain the openstack virtual machine status to openmano status'''
56vmStatus2manoFormat={'ACTIVE':'ACTIVE',
57 'PAUSED':'PAUSED',
58 'SUSPENDED': 'SUSPENDED',
59 'SHUTOFF':'INACTIVE',
60 'BUILD':'BUILD',
61 'ERROR':'ERROR','DELETED':'DELETED'
62 }
63netStatus2manoFormat={'ACTIVE':'ACTIVE','PAUSED':'PAUSED','INACTIVE':'INACTIVE','BUILD':'BUILD','ERROR':'ERROR','DELETED':'DELETED'
64 }
65
montesmoreno0c8def02016-12-22 12:16:23 +000066#global var to have a timeout creating and deleting volumes
67volume_timeout = 60
montesmoreno2a1fc4e2017-01-09 16:46:04 +000068server_timeout = 60
montesmoreno0c8def02016-12-22 12:16:23 +000069
tierno7edb6752016-03-21 17:37:52 +010070class vimconnector(vimconn.vimconnector):
tiernob3d36742017-03-03 23:51:05 +010071 def __init__(self, uuid, name, tenant_id, tenant_name, url, url_admin=None, user=None, passwd=None,
72 log_level=None, config={}, persistent_info={}):
ahmadsa96af9f42017-01-31 16:17:14 +050073 '''using common constructor parameters. In this case
tierno7edb6752016-03-21 17:37:52 +010074 'url' is the keystone authorization url,
75 'url_admin' is not use
76 '''
ahmadsa95baa272016-11-30 09:14:11 +050077 self.osc_api_version = 'v2.0'
78 if config.get('APIversion') == 'v3.3':
79 self.osc_api_version = 'v3.3'
tiernoae4a8d12016-07-08 12:30:39 +020080 vimconn.vimconnector.__init__(self, uuid, name, tenant_id, tenant_name, url, url_admin, user, passwd, log_level, config)
tiernob3d36742017-03-03 23:51:05 +010081
82 self.persistent_info = persistent_info
tierno7edb6752016-03-21 17:37:52 +010083 self.k_creds={}
84 self.n_creds={}
tiernoc75a5dc2017-01-18 15:53:44 +010085 if self.config.get("insecure"):
86 self.k_creds["insecure"] = True
87 self.n_creds["insecure"] = True
tierno7edb6752016-03-21 17:37:52 +010088 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
tierno392f2852016-05-13 12:28:55 +020092 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
tierno7edb6752016-03-21 17:37:52 +010098 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
ahmadsa95baa272016-11-30 09:14:11 +0500104 if self.osc_api_version == 'v3.3':
105 self.k_creds['project_name'] = tenant_name
106 self.k_creds['project_id'] = tenant_id
montesmorenocf227142017-01-12 12:24:21 +0000107 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')
montesmoreno0c8def02016-12-22 12:16:23 +0000110
tierno7edb6752016-03-21 17:37:52 +0100111 self.reload_client = True
tierno73ad9e42016-09-12 18:11:11 +0200112 self.logger = logging.getLogger('openmano.vim.openstack')
tiernofe789902016-09-29 14:20:44 +0000113 if log_level:
114 self.logger.setLevel( getattr(logging, log_level) )
tierno7edb6752016-03-21 17:37:52 +0100115
116 def __setitem__(self,index, value):
117 '''Set individuals parameters
118 Throw TypeError, KeyError
119 '''
tierno392f2852016-05-13 12:28:55 +0200120 if index=='tenant_id':
tierno7edb6752016-03-21 17:37:52 +0100121 self.reload_client=True
tierno392f2852016-05-13 12:28:55 +0200122 self.tenant_id = value
ahmadsa95baa272016-11-30 09:14:11 +0500123 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']
tierno392f2852016-05-13 12:28:55 +0200130 else:
ahmadsa95baa272016-11-30 09:14:11 +0500131 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']
tierno392f2852016-05-13 12:28:55 +0200137 elif index=='tenant_name':
138 self.reload_client=True
139 self.tenant_name = value
ahmadsa95baa272016-11-30 09:14:11 +0500140 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']
tierno7edb6752016-03-21 17:37:52 +0100147 else:
ahmadsa95baa272016-11-30 09:14:11 +0500148 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']
tierno7edb6752016-03-21 17:37:52 +0100154 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")
ahmadsa95baa272016-11-30 09:14:11 +0500192 if self.osc_api_version == 'v3.3':
ahmadsa96af9f42017-01-31 16:17:14 +0500193 self.nova = nClient(api_version=api_versions.APIVersion(version_str='2.0'), **self.n_creds)
montesmoreno0c8def02016-12-22 12:16:23 +0000194 #TODO To be updated for v3
195 #self.cinder = cClient.Client(**self.n_creds)
ahmadsa95baa272016-11-30 09:14:11 +0500196 self.keystone = ksClient.Client(**self.k_creds)
197 self.ne_endpoint=self.keystone.service_catalog.url_for(service_type='network', endpoint_type='publicURL')
ahmadsa96af9f42017-01-31 16:17:14 +0500198 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 +0500199 else:
ahmadsa96af9f42017-01-31 16:17:14 +0500200 self.nova = nClient_v2.Client(version='2', **self.n_creds)
montesmoreno0c8def02016-12-22 12:16:23 +0000201 self.cinder = cClient_v2.Client(**self.n_creds)
ahmadsa95baa272016-11-30 09:14:11 +0500202 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)
tierno7edb6752016-03-21 17:37:52 +0100205 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
tierno7edb6752016-03-21 17:37:52 +0100207 self.reload_client = False
ahmadsa95baa272016-11-30 09:14:11 +0500208
tierno7edb6752016-03-21 17:37:52 +0100209 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'
tiernoae4a8d12016-07-08 12:30:39 +0200223
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,
tierno8e995ce2016-09-22 08:13:00 +0000229 ConnectionError, ksExceptions.ConnectionError, neExceptions.ConnectionFailed
230 )):
tiernoae4a8d12016-07-08 12:30:39 +0200231 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 '''
ahmadsa95baa272016-11-30 09:14:11 +0500250 self.logger.debug("Getting tenants from VIM filter: '%s'", str(filter_dict))
tiernoae4a8d12016-07-08 12:30:39 +0200251 try:
252 self._reload_connection()
montesmoreno0c8def02016-12-22 12:16:23 +0000253 if self.osc_api_version == 'v3.3':
ahmadsa95baa272016-11-30 09:14:11 +0500254 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
tierno8e995ce2016-09-22 08:13:00 +0000261 except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200262 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()
ahmadsa95baa272016-11-30 09:14:11 +0500269 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
tierno8e995ce2016-09-22 08:13:00 +0000274 except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200275 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()
montesmoreno0c8def02016-12-22 12:16:23 +0000282 if self.osc_api_version == 'v3.3':
ahmadsa95baa272016-11-30 09:14:11 +0500283 self.keystone.projects.delete(tenant_id)
284 else:
285 self.keystone.tenants.delete(tenant_id)
tiernoae4a8d12016-07-08 12:30:39 +0200286 return tenant_id
tierno8e995ce2016-09-22 08:13:00 +0000287 except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200288 self._format_exception(e)
ahmadsa95baa272016-11-30 09:14:11 +0500289
garciadeblas9f8456e2016-09-05 05:02:59 +0200290 def new_network(self,net_name, net_type, ip_profile=None, shared=False, vlan=None):
tiernoae4a8d12016-07-08 12:30:39 +0200291 '''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)
garciadeblasedca7b32016-09-29 14:01:52 +0000293 #self.logger.debug(">>>>>>>>>>>>>>>>>> IP profile %s", str(ip_profile))
tierno7edb6752016-03-21 17:37:52 +0100294 try:
garciadeblasedca7b32016-09-29 14:01:52 +0000295 new_net = None
tierno7edb6752016-03-21 17:37:52 +0100296 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:
tiernoae4a8d12016-07-08 12:30:39 +0200300 raise vimconn.vimconnConflictException("You must provide a 'dataplane_physical_net' at config value before creating sriov network")
tierno7edb6752016-03-21 17:37:52 +0100301 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
tiernoae4a8d12016-07-08 12:30:39 +0200305 network_dict["shared"]=shared
tierno7edb6752016-03-21 17:37:52 +0100306 new_net=self.neutron.create_network({'network':network_dict})
307 #print new_net
garciadeblas9f8456e2016-09-05 05:02:59 +0200308 #create subnetwork, even if there is no profile
309 if not ip_profile:
310 ip_profile = {}
311 if 'subnet_address' not in ip_profile:
garciadeblas2299e3b2017-01-26 14:35:55 +0000312 #Fake subnet is required
313 subnet_rand = random.randint(0, 255)
314 ip_profile['subnet_address'] = "192.168.{}.0/24".format(subnet_rand)
garciadeblas9f8456e2016-09-05 05:02:59 +0200315 if 'ip_version' not in ip_profile:
316 ip_profile['ip_version'] = "IPv4"
tierno7edb6752016-03-21 17:37:52 +0100317 subnet={"name":net_name+"-subnet",
318 "network_id": new_net["network"]["id"],
garciadeblas9f8456e2016-09-05 05:02:59 +0200319 "ip_version": 4 if ip_profile['ip_version']=="IPv4" else 6,
320 "cidr": ip_profile['subnet_address']
tierno7edb6752016-03-21 17:37:52 +0100321 }
garciadeblas9f8456e2016-09-05 05:02:59 +0200322 if 'gateway_address' in ip_profile:
323 subnet['gateway_ip'] = ip_profile['gateway_address']
garciadeblasedca7b32016-09-29 14:01:52 +0000324 if ip_profile.get('dns_address'):
garciadeblas9f8456e2016-09-05 05:02:59 +0200325 #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']))
garciadeblas21d795b2016-09-29 17:31:46 +0200338 ip_int += ip_profile['dhcp_count'] - 1
garciadeblas9f8456e2016-09-05 05:02:59 +0200339 ip_str = str(netaddr.IPAddress(ip_int))
340 subnet['allocation_pools'][0]['end'] = ip_str
garciadeblasedca7b32016-09-29 14:01:52 +0000341 #self.logger.debug(">>>>>>>>>>>>>>>>>> Subnet: %s", str(subnet))
tierno7edb6752016-03-21 17:37:52 +0100342 self.neutron.create_subnet({"subnet": subnet} )
tiernoae4a8d12016-07-08 12:30:39 +0200343 return new_net["network"]["id"]
tierno8e995ce2016-09-22 08:13:00 +0000344 except (neExceptions.ConnectionFailed, ksExceptions.ClientException, neExceptions.NeutronException, ConnectionError) as e:
garciadeblasedca7b32016-09-29 14:01:52 +0000345 if new_net:
346 self.neutron.delete_network(new_net['network']['id'])
tiernoae4a8d12016-07-08 12:30:39 +0200347 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100348
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 '''
tiernoae4a8d12016-07-08 12:30:39 +0200360 self.logger.debug("Getting network from VIM filter: '%s'", str(filter_dict))
tierno7edb6752016-03-21 17:37:52 +0100361 try:
362 self._reload_connection()
montesmoreno0c8def02016-12-22 12:16:23 +0000363 if self.osc_api_version == 'v3.3' and "tenant_id" in filter_dict:
ahmadsa95baa272016-11-30 09:14:11 +0500364 filter_dict['project_id'] = filter_dict.pop('tenant_id')
tierno7edb6752016-03-21 17:37:52 +0100365 net_dict=self.neutron.list_networks(**filter_dict)
366 net_list=net_dict["networks"]
367 self.__net_os2mano(net_list)
tiernoae4a8d12016-07-08 12:30:39 +0200368 return net_list
tierno8e995ce2016-09-22 08:13:00 +0000369 except (neExceptions.ConnectionFailed, ksExceptions.ClientException, neExceptions.NeutronException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200370 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100371
tiernoae4a8d12016-07-08 12:30:39 +0200372 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)
tierno7edb6752016-03-21 17:37:52 +0100376 filter_dict={"id": net_id}
tiernoae4a8d12016-07-08 12:30:39 +0200377 net_list = self.get_network_list(filter_dict)
tierno7edb6752016-03-21 17:37:52 +0100378 if len(net_list)==0:
tiernoae4a8d12016-07-08 12:30:39 +0200379 raise vimconn.vimconnNotFoundException("Network '{}' not found".format(net_id))
tierno7edb6752016-03-21 17:37:52 +0100380 elif len(net_list)>1:
tiernoae4a8d12016-07-08 12:30:39 +0200381 raise vimconn.vimconnConflictException("Found more than one network with this criteria")
tierno7edb6752016-03-21 17:37:52 +0100382 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:
tiernoae4a8d12016-07-08 12:30:39 +0200388 self.logger.error("osconnector.get_network(): Error getting subnet %s %s" % (net_id, str(e)))
389 subnet = {"id": subnet_id, "fault": str(e)}
tierno7edb6752016-03-21 17:37:52 +0100390 subnets.append(subnet)
391 net["subnets"] = subnets
Pablo Montes Moreno51e553b2017-03-23 16:39:12 +0100392 net["encapsulation"] = net.get('provider:network_type')
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100393 net["segmentation_id"] = net.get('provider:segmentation_id')
tiernoae4a8d12016-07-08 12:30:39 +0200394 return net
tierno7edb6752016-03-21 17:37:52 +0100395
tiernoae4a8d12016-07-08 12:30:39 +0200396 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)
tierno7edb6752016-03-21 17:37:52 +0100399 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:
tiernoae4a8d12016-07-08 12:30:39 +0200407 self.logger.error("Error deleting port %s: %s", p["id"], str(e))
tierno7edb6752016-03-21 17:37:52 +0100408 self.neutron.delete_network(net_id)
tiernoae4a8d12016-07-08 12:30:39 +0200409 return net_id
410 except (neExceptions.ConnectionFailed, neExceptions.NetworkNotFoundClient, neExceptions.NeutronException,
tierno8e995ce2016-09-22 08:13:00 +0000411 ksExceptions.ClientException, neExceptions.NeutronException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200412 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100413
tiernoae4a8d12016-07-08 12:30:39 +0200414 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
tierno8e995ce2016-09-22 08:13:00 +0000442 if net['status'] == "ACTIVE" and not net_vim['admin_state_up']:
tiernoae4a8d12016-07-08 12:30:39 +0200443 net['status'] = 'DOWN'
tierno8e995ce2016-09-22 08:13:00 +0000444 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)
tiernoae4a8d12016-07-08 12:30:39 +0200448 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)
tierno7edb6752016-03-21 17:37:52 +0100464 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)
tiernoae4a8d12016-07-08 12:30:39 +0200468 return flavor.to_dict()
tierno8e995ce2016-09-22 08:13:00 +0000469 except (nvExceptions.NotFound, nvExceptions.ClientException, ksExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200470 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100471
tiernocf157a82017-01-30 14:07:06 +0100472 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
tiernoae4a8d12016-07-08 12:30:39 +0200504 def new_flavor(self, flavor_data, change_name_if_used=True):
tierno7edb6752016-03-21 17:37:52 +0100505 '''Adds a tenant flavor to openstack VIM
tiernoae4a8d12016-07-08 12:30:39 +0200506 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 +0100507 Returns the flavor identifier
508 '''
tiernoae4a8d12016-07-08 12:30:39 +0200509 self.logger.debug("Adding flavor '%s'", str(flavor_data))
tierno7edb6752016-03-21 17:37:52 +0100510 retry=0
tiernoae4a8d12016-07-08 12:30:39 +0200511 max_retries=3
tierno7edb6752016-03-21 17:37:52 +0100512 name_suffix = 0
tiernoae4a8d12016-07-08 12:30:39 +0200513 name=flavor_data['name']
514 while retry<max_retries:
tierno7edb6752016-03-21 17:37:52 +0100515 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
tiernoae4a8d12016-07-08 12:30:39 +0200526 name = flavor_data['name']+"-" + str(name_suffix)
tierno7edb6752016-03-21 17:37:52 +0100527
tiernoae4a8d12016-07-08 12:30:39 +0200528 ram = flavor_data.get('ram',64)
529 vcpus = flavor_data.get('vcpus',1)
tierno7edb6752016-03-21 17:37:52 +0100530 numa_properties=None
531
tiernoae4a8d12016-07-08 12:30:39 +0200532 extended = flavor_data.get("extended")
tierno7edb6752016-03-21 17:37:52 +0100533 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
Pablo Montes Morenoea1d6232017-05-24 11:33:24 +0200546 #See for reference: https://specs.openstack.org/openstack/nova-specs/specs/mitaka/implemented/virt-driver-cpu-thread-pinning.html
tierno7edb6752016-03-21 17:37:52 +0100547 if 'paired-threads' in numa:
548 vcpus = numa['paired-threads']*2
Pablo Montes Morenoea1d6232017-05-24 11:33:24 +0200549 #cpu_thread_policy "require" implies that the compute node must have an STM architecture
550 numa_properties["hw:cpu_thread_policy"] = "require"
551 numa_properties["hw:cpu_policy"] = "dedicated"
tierno7edb6752016-03-21 17:37:52 +0100552 elif 'cores' in numa:
553 vcpus = numa['cores']
Pablo Montes Morenoea1d6232017-05-24 11:33:24 +0200554 # cpu_thread_policy "prefer" implies that the host must not have an SMT architecture, or a non-SMT architecture will be emulated
555 numa_properties["hw:cpu_thread_policy"] = "isolate"
556 numa_properties["hw:cpu_policy"] = "dedicated"
tierno7edb6752016-03-21 17:37:52 +0100557 elif 'threads' in numa:
558 vcpus = numa['threads']
Pablo Montes Morenoea1d6232017-05-24 11:33:24 +0200559 # cpu_thread_policy "prefer" implies that the host may or may not have an SMT architecture
560 numa_properties["hw:cpu_thread_policy"] = "prefer"
561 numa_properties["hw:cpu_policy"] = "dedicated"
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +0200562 # for interface in numa.get("interfaces",() ):
563 # if interface["dedicated"]=="yes":
564 # raise vimconn.vimconnException("Passthrough interfaces are not supported for the openstack connector", http_code=vimconn.HTTP_Service_Unavailable)
565 # #TODO, add the key 'pci_passthrough:alias"="<label at config>:<number ifaces>"' when a way to connect it is available
tierno7edb6752016-03-21 17:37:52 +0100566
567 #create flavor
568 new_flavor=self.nova.flavors.create(name,
569 ram,
570 vcpus,
tiernoae4a8d12016-07-08 12:30:39 +0200571 flavor_data.get('disk',1),
572 is_public=flavor_data.get('is_public', True)
tierno7edb6752016-03-21 17:37:52 +0100573 )
574 #add metadata
575 if numa_properties:
576 new_flavor.set_keys(numa_properties)
tiernoae4a8d12016-07-08 12:30:39 +0200577 return new_flavor.id
tierno7edb6752016-03-21 17:37:52 +0100578 except nvExceptions.Conflict as e:
tiernoae4a8d12016-07-08 12:30:39 +0200579 if change_name_if_used and retry < max_retries:
tierno7edb6752016-03-21 17:37:52 +0100580 continue
tiernoae4a8d12016-07-08 12:30:39 +0200581 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100582 #except nvExceptions.BadRequest as e:
583 except (ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200584 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100585
tiernoae4a8d12016-07-08 12:30:39 +0200586 def delete_flavor(self,flavor_id):
587 '''Deletes a tenant flavor from openstack VIM. Returns the old flavor_id
tierno7edb6752016-03-21 17:37:52 +0100588 '''
tiernoae4a8d12016-07-08 12:30:39 +0200589 try:
590 self._reload_connection()
591 self.nova.flavors.delete(flavor_id)
592 return flavor_id
593 #except nvExceptions.BadRequest as e:
tierno8e995ce2016-09-22 08:13:00 +0000594 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200595 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100596
tiernoae4a8d12016-07-08 12:30:39 +0200597 def new_image(self,image_dict):
tierno7edb6752016-03-21 17:37:52 +0100598 '''
tiernoae4a8d12016-07-08 12:30:39 +0200599 Adds a tenant image to VIM. imge_dict is a dictionary with:
600 name: name
601 disk_format: qcow2, vhd, vmdk, raw (by default), ...
602 location: path or URI
603 public: "yes" or "no"
604 metadata: metadata of the image
605 Returns the image_id
tierno7edb6752016-03-21 17:37:52 +0100606 '''
tierno7edb6752016-03-21 17:37:52 +0100607 #using version 1 of glance client
608 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 +0200609 retry=0
610 max_retries=3
611 while retry<max_retries:
tierno7edb6752016-03-21 17:37:52 +0100612 retry+=1
613 try:
614 self._reload_connection()
615 #determine format http://docs.openstack.org/developer/glance/formats.html
616 if "disk_format" in image_dict:
617 disk_format=image_dict["disk_format"]
garciadeblas14480452017-01-10 13:08:07 +0100618 else: #autodiscover based on extension
tierno7edb6752016-03-21 17:37:52 +0100619 if image_dict['location'][-6:]==".qcow2":
620 disk_format="qcow2"
621 elif image_dict['location'][-4:]==".vhd":
622 disk_format="vhd"
623 elif image_dict['location'][-5:]==".vmdk":
624 disk_format="vmdk"
625 elif image_dict['location'][-4:]==".vdi":
626 disk_format="vdi"
627 elif image_dict['location'][-4:]==".iso":
628 disk_format="iso"
629 elif image_dict['location'][-4:]==".aki":
630 disk_format="aki"
631 elif image_dict['location'][-4:]==".ari":
632 disk_format="ari"
633 elif image_dict['location'][-4:]==".ami":
634 disk_format="ami"
635 else:
636 disk_format="raw"
tiernoae4a8d12016-07-08 12:30:39 +0200637 self.logger.debug("new_image: '%s' loading from '%s'", image_dict['name'], image_dict['location'])
tierno7edb6752016-03-21 17:37:52 +0100638 if image_dict['location'][0:4]=="http":
639 new_image = glancev1.images.create(name=image_dict['name'], is_public=image_dict.get('public',"yes")=="yes",
640 container_format="bare", location=image_dict['location'], disk_format=disk_format)
641 else: #local path
642 with open(image_dict['location']) as fimage:
643 new_image = glancev1.images.create(name=image_dict['name'], is_public=image_dict.get('public',"yes")=="yes",
644 container_format="bare", data=fimage, disk_format=disk_format)
645 #insert metadata. We cannot use 'new_image.properties.setdefault'
646 #because nova and glance are "INDEPENDENT" and we are using nova for reading metadata
647 new_image_nova=self.nova.images.find(id=new_image.id)
648 new_image_nova.metadata.setdefault('location',image_dict['location'])
649 metadata_to_load = image_dict.get('metadata')
650 if metadata_to_load:
651 for k,v in yaml.load(metadata_to_load).iteritems():
652 new_image_nova.metadata.setdefault(k,v)
tiernoae4a8d12016-07-08 12:30:39 +0200653 return new_image.id
654 except (nvExceptions.Conflict, ksExceptions.ClientException, nvExceptions.ClientException) as e:
655 self._format_exception(e)
tierno8e995ce2016-09-22 08:13:00 +0000656 except (HTTPException, gl1Exceptions.HTTPException, gl1Exceptions.CommunicationError, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200657 if retry==max_retries:
658 continue
659 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100660 except IOError as e: #can not open the file
tiernoae4a8d12016-07-08 12:30:39 +0200661 raise vimconn.vimconnConnectionException(type(e).__name__ + ": " + str(e)+ " for " + image_dict['location'],
662 http_code=vimconn.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100663
tiernoae4a8d12016-07-08 12:30:39 +0200664 def delete_image(self, image_id):
665 '''Deletes a tenant image from openstack VIM. Returns the old id
tierno7edb6752016-03-21 17:37:52 +0100666 '''
tiernoae4a8d12016-07-08 12:30:39 +0200667 try:
668 self._reload_connection()
669 self.nova.images.delete(image_id)
670 return image_id
tierno8e995ce2016-09-22 08:13:00 +0000671 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e: #TODO remove
tiernoae4a8d12016-07-08 12:30:39 +0200672 self._format_exception(e)
673
674 def get_image_id_from_path(self, path):
garciadeblasb69fa9f2016-09-28 12:04:10 +0200675 '''Get the image id from image path in the VIM database. Returns the image_id'''
tiernoae4a8d12016-07-08 12:30:39 +0200676 try:
677 self._reload_connection()
678 images = self.nova.images.list()
679 for image in images:
680 if image.metadata.get("location")==path:
681 return image.id
682 raise vimconn.vimconnNotFoundException("image with location '{}' not found".format( path))
tierno8e995ce2016-09-22 08:13:00 +0000683 except (ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200684 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100685
garciadeblasb69fa9f2016-09-28 12:04:10 +0200686 def get_image_list(self, filter_dict={}):
687 '''Obtain tenant images from VIM
688 Filter_dict can be:
689 id: image id
690 name: image name
691 checksum: image checksum
692 Returns the image list of dictionaries:
693 [{<the fields at Filter_dict plus some VIM specific>}, ...]
694 List can be empty
695 '''
696 self.logger.debug("Getting image list from VIM filter: '%s'", str(filter_dict))
697 try:
698 self._reload_connection()
699 filter_dict_os=filter_dict.copy()
700 #First we filter by the available filter fields: name, id. The others are removed.
701 filter_dict_os.pop('checksum',None)
702 image_list=self.nova.images.findall(**filter_dict_os)
703 if len(image_list)==0:
704 return []
705 #Then we filter by the rest of filter fields: checksum
706 filtered_list = []
707 for image in image_list:
tierno4540ea52017-01-18 17:44:32 +0100708 image_class=self.glance.images.get(image.id)
709 if 'checksum' not in filter_dict or image_class['checksum']==filter_dict.get('checksum'):
710 filtered_list.append(image_class.copy())
garciadeblasb69fa9f2016-09-28 12:04:10 +0200711 return filtered_list
712 except (ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e:
713 self._format_exception(e)
714
montesmoreno0c8def02016-12-22 12:16:23 +0000715 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 +0100716 '''Adds a VM instance to VIM
717 Params:
718 start: indicates if VM must start or boot in pause mode. Ignored
719 image_id,flavor_id: iamge and flavor uuid
720 net_list: list of interfaces, each one is a dictionary with:
721 name:
722 net_id: network uuid to connect
723 vpci: virtual vcpi to assign, ignored because openstack lack #TODO
724 model: interface model, ignored #TODO
725 mac_address: used for SR-IOV ifaces #TODO for other types
726 use: 'data', 'bridge', 'mgmt'
727 type: 'virtual', 'PF', 'VF', 'VFnotShared'
728 vim_id: filled/added by this function
ahmadsaf853d452016-12-22 11:33:47 +0500729 floating_ip: True/False (or it can be None)
tierno7edb6752016-03-21 17:37:52 +0100730 #TODO ip, security groups
tiernoae4a8d12016-07-08 12:30:39 +0200731 Returns the instance identifier
tierno7edb6752016-03-21 17:37:52 +0100732 '''
tiernofa51c202017-01-27 14:58:17 +0100733 self.logger.debug("new_vminstance input: image='%s' flavor='%s' nics='%s'",image_id, flavor_id,str(net_list))
tierno7edb6752016-03-21 17:37:52 +0100734 try:
tierno6e116232016-07-18 13:01:40 +0200735 metadata={}
tierno7edb6752016-03-21 17:37:52 +0100736 net_list_vim=[]
ahmadsaf853d452016-12-22 11:33:47 +0500737 external_network=[] #list of external networks to be connected to instance, later on used to create floating_ip
tierno7edb6752016-03-21 17:37:52 +0100738 self._reload_connection()
tiernoae4a8d12016-07-08 12:30:39 +0200739 metadata_vpci={} #For a specific neutron plugin
tierno7edb6752016-03-21 17:37:52 +0100740 for net in net_list:
741 if not net.get("net_id"): #skip non connected iface
742 continue
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +0200743
744 port_dict={
745 "network_id": net["net_id"],
746 "name": net.get("name"),
747 "admin_state_up": True
748 }
749 if net["type"]=="virtual":
750 if "vpci" in net:
751 metadata_vpci[ net["net_id"] ] = [[ net["vpci"], "" ]]
752 elif net["type"]=="VF": # for VF
753 if "vpci" in net:
754 if "VF" not in metadata_vpci:
755 metadata_vpci["VF"]=[]
756 metadata_vpci["VF"].append([ net["vpci"], "" ])
757 port_dict["binding:vnic_type"]="direct"
758 else: #For PT
759 if "vpci" in net:
760 if "PF" not in metadata_vpci:
761 metadata_vpci["PF"]=[]
762 metadata_vpci["PF"].append([ net["vpci"], "" ])
763 port_dict["binding:vnic_type"]="direct-physical"
764 if not port_dict["name"]:
765 port_dict["name"]=name
766 if net.get("mac_address"):
767 port_dict["mac_address"]=net["mac_address"]
768 if net.get("port_security") == False:
769 port_dict["port_security_enabled"]=net["port_security"]
770 new_port = self.neutron.create_port({"port": port_dict })
771 net["mac_adress"] = new_port["port"]["mac_address"]
772 net["vim_id"] = new_port["port"]["id"]
773 net["ip"] = new_port["port"].get("fixed_ips", [{}])[0].get("ip_address")
774 net_list_vim.append({"port-id": new_port["port"]["id"]})
775
ahmadsaf853d452016-12-22 11:33:47 +0500776 if net.get('floating_ip', False):
tiernof8383b82017-01-18 15:49:48 +0100777 net['exit_on_floating_ip_error'] = True
ahmadsaf853d452016-12-22 11:33:47 +0500778 external_network.append(net)
tiernof8383b82017-01-18 15:49:48 +0100779 elif net['use'] == 'mgmt' and self.config.get('use_floating_ip'):
780 net['exit_on_floating_ip_error'] = False
781 external_network.append(net)
782
tierno7edb6752016-03-21 17:37:52 +0100783 if metadata_vpci:
784 metadata = {"pci_assignement": json.dumps(metadata_vpci)}
tiernoafbced42016-07-23 01:43:53 +0200785 if len(metadata["pci_assignement"]) >255:
tierno6e116232016-07-18 13:01:40 +0200786 #limit the metadata size
787 #metadata["pci_assignement"] = metadata["pci_assignement"][0:255]
788 self.logger.warn("Metadata deleted since it exceeds the expected length (255) ")
789 metadata = {}
tierno7edb6752016-03-21 17:37:52 +0100790
tiernoae4a8d12016-07-08 12:30:39 +0200791 self.logger.debug("name '%s' image_id '%s'flavor_id '%s' net_list_vim '%s' description '%s' metadata %s",
792 name, image_id, flavor_id, str(net_list_vim), description, str(metadata))
tierno7edb6752016-03-21 17:37:52 +0100793
794 security_groups = self.config.get('security_groups')
795 if type(security_groups) is str:
796 security_groups = ( security_groups, )
tierno36c0b172017-01-12 18:32:28 +0100797 #cloud config
798 userdata=None
799 config_drive = None
tiernoa4e1a6e2016-08-31 14:19:40 +0200800 if isinstance(cloud_config, dict):
tierno36c0b172017-01-12 18:32:28 +0100801 if cloud_config.get("user-data"):
802 userdata=cloud_config["user-data"]
803 if cloud_config.get("boot-data-drive") != None:
804 config_drive = cloud_config["boot-data-drive"]
805 if cloud_config.get("config-files") or cloud_config.get("users") or cloud_config.get("key-pairs"):
806 if userdata:
807 raise vimconn.vimconnConflictException("Cloud-config cannot contain both 'userdata' and 'config-files'/'users'/'key-pairs'")
808 userdata_dict={}
809 #default user
810 if cloud_config.get("key-pairs"):
811 userdata_dict["ssh-authorized-keys"] = cloud_config["key-pairs"]
812 userdata_dict["users"] = [{"default": None, "ssh-authorized-keys": cloud_config["key-pairs"] }]
813 if cloud_config.get("users"):
tierno01d0bf52017-01-25 14:27:20 +0100814 if "users" not in userdata_dict:
tierno36c0b172017-01-12 18:32:28 +0100815 userdata_dict["users"] = [ "default" ]
816 for user in cloud_config["users"]:
817 user_info = {
818 "name" : user["name"],
819 "sudo": "ALL = (ALL)NOPASSWD:ALL"
820 }
821 if "user-info" in user:
822 user_info["gecos"] = user["user-info"]
823 if user.get("key-pairs"):
824 user_info["ssh-authorized-keys"] = user["key-pairs"]
825 userdata_dict["users"].append(user_info)
826
827 if cloud_config.get("config-files"):
828 userdata_dict["write_files"] = []
829 for file in cloud_config["config-files"]:
830 file_info = {
831 "path" : file["dest"],
832 "content": file["content"]
833 }
834 if file.get("encoding"):
835 file_info["encoding"] = file["encoding"]
836 if file.get("permissions"):
837 file_info["permissions"] = file["permissions"]
838 if file.get("owner"):
839 file_info["owner"] = file["owner"]
840 userdata_dict["write_files"].append(file_info)
841 userdata = "#cloud-config\n"
842 userdata += yaml.safe_dump(userdata_dict, indent=4, default_flow_style=False)
tiernoa4e1a6e2016-08-31 14:19:40 +0200843 self.logger.debug("userdata: %s", userdata)
844 elif isinstance(cloud_config, str):
845 userdata = cloud_config
montesmoreno0c8def02016-12-22 12:16:23 +0000846
847 #Create additional volumes in case these are present in disk_list
848 block_device_mapping = None
849 base_disk_index = ord('b')
850 if disk_list != None:
851 block_device_mapping = dict()
852 for disk in disk_list:
853 if 'image_id' in disk:
854 volume = self.cinder.volumes.create(size = disk['size'],name = name + '_vd' +
855 chr(base_disk_index), imageRef = disk['image_id'])
856 else:
857 volume = self.cinder.volumes.create(size=disk['size'], name=name + '_vd' +
858 chr(base_disk_index))
859 block_device_mapping['_vd' + chr(base_disk_index)] = volume.id
860 base_disk_index += 1
861
862 #wait until volumes are with status available
863 keep_waiting = True
864 elapsed_time = 0
865 while keep_waiting and elapsed_time < volume_timeout:
866 keep_waiting = False
867 for volume_id in block_device_mapping.itervalues():
868 if self.cinder.volumes.get(volume_id).status != 'available':
869 keep_waiting = True
870 if keep_waiting:
871 time.sleep(1)
872 elapsed_time += 1
873
874 #if we exceeded the timeout rollback
875 if elapsed_time >= volume_timeout:
876 #delete the volumes we just created
877 for volume_id in block_device_mapping.itervalues():
878 self.cinder.volumes.delete(volume_id)
879
880 #delete ports we just created
881 for net_item in net_list_vim:
882 if 'port-id' in net_item:
montesmorenocf227142017-01-12 12:24:21 +0000883 self.neutron.delete_port(net_item['port-id'])
montesmoreno0c8def02016-12-22 12:16:23 +0000884
885 raise vimconn.vimconnException('Timeout creating volumes for instance ' + name,
886 http_code=vimconn.HTTP_Request_Timeout)
887
tierno7edb6752016-03-21 17:37:52 +0100888 server = self.nova.servers.create(name, image_id, flavor_id, nics=net_list_vim, meta=metadata,
montesmoreno0c8def02016-12-22 12:16:23 +0000889 security_groups=security_groups,
890 availability_zone=self.config.get('availability_zone'),
891 key_name=self.config.get('keypair'),
892 userdata=userdata,
tierno36c0b172017-01-12 18:32:28 +0100893 config_drive = config_drive,
montesmoreno0c8def02016-12-22 12:16:23 +0000894 block_device_mapping = block_device_mapping
895 ) # , description=description)
tiernoae4a8d12016-07-08 12:30:39 +0200896 #print "DONE :-)", server
ahmadsaf853d452016-12-22 11:33:47 +0500897 pool_id = None
898 floating_ips = self.neutron.list_floatingips().get("floatingips", ())
899 for floating_network in external_network:
tiernof8383b82017-01-18 15:49:48 +0100900 try:
901 # wait until vm is active
902 elapsed_time = 0
903 while elapsed_time < server_timeout:
904 status = self.nova.servers.get(server.id).status
905 if status == 'ACTIVE':
906 break
907 time.sleep(1)
908 elapsed_time += 1
montesmoreno2a1fc4e2017-01-09 16:46:04 +0000909
tiernof8383b82017-01-18 15:49:48 +0100910 #if we exceeded the timeout rollback
911 if elapsed_time >= server_timeout:
912 raise vimconn.vimconnException('Timeout creating instance ' + name,
913 http_code=vimconn.HTTP_Request_Timeout)
montesmoreno2a1fc4e2017-01-09 16:46:04 +0000914
tiernof8383b82017-01-18 15:49:48 +0100915 assigned = False
916 while(assigned == False):
917 if floating_ips:
918 ip = floating_ips.pop(0)
919 if not ip.get("port_id", False) and ip.get('tenant_id') == server.tenant_id:
920 free_floating_ip = ip.get("floating_ip_address")
921 try:
922 fix_ip = floating_network.get('ip')
923 server.add_floating_ip(free_floating_ip, fix_ip)
924 assigned = True
925 except Exception as e:
926 raise vimconn.vimconnException(type(e).__name__ + ": Cannot create floating_ip "+ str(e), http_code=vimconn.HTTP_Conflict)
927 else:
928 #Find the external network
929 external_nets = list()
930 for net in self.neutron.list_networks()['networks']:
931 if net['router:external']:
932 external_nets.append(net)
933
934 if len(external_nets) == 0:
935 raise vimconn.vimconnException("Cannot create floating_ip automatically since no external "
936 "network is present",
937 http_code=vimconn.HTTP_Conflict)
938 if len(external_nets) > 1:
939 raise vimconn.vimconnException("Cannot create floating_ip automatically since multiple "
940 "external networks are present",
941 http_code=vimconn.HTTP_Conflict)
942
943 pool_id = external_nets[0].get('id')
944 param = {'floatingip': {'floating_network_id': pool_id, 'tenant_id': server.tenant_id}}
ahmadsaf853d452016-12-22 11:33:47 +0500945 try:
tiernof8383b82017-01-18 15:49:48 +0100946 #self.logger.debug("Creating floating IP")
947 new_floating_ip = self.neutron.create_floatingip(param)
948 free_floating_ip = new_floating_ip['floatingip']['floating_ip_address']
ahmadsaf853d452016-12-22 11:33:47 +0500949 fix_ip = floating_network.get('ip')
950 server.add_floating_ip(free_floating_ip, fix_ip)
tiernof8383b82017-01-18 15:49:48 +0100951 assigned=True
ahmadsaf853d452016-12-22 11:33:47 +0500952 except Exception as e:
tiernof8383b82017-01-18 15:49:48 +0100953 raise vimconn.vimconnException(type(e).__name__ + ": Cannot assign floating_ip "+ str(e), http_code=vimconn.HTTP_Conflict)
954 except Exception as e:
955 if not floating_network['exit_on_floating_ip_error']:
956 self.logger.warn("Cannot create floating_ip. %s", str(e))
957 continue
958 self.delete_vminstance(server.id)
959 raise
montesmoreno2a1fc4e2017-01-09 16:46:04 +0000960
tiernoae4a8d12016-07-08 12:30:39 +0200961 return server.id
tierno7edb6752016-03-21 17:37:52 +0100962# except nvExceptions.NotFound as e:
963# error_value=-vimconn.HTTP_Not_Found
964# error_text= "vm instance %s not found" % vm_id
tiernof8383b82017-01-18 15:49:48 +0100965 except (ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e:
montesmoreno2a1fc4e2017-01-09 16:46:04 +0000966 # delete the volumes we just created
967 if block_device_mapping != None:
968 for volume_id in block_device_mapping.itervalues():
969 self.cinder.volumes.delete(volume_id)
970
971 # delete ports we just created
972 for net_item in net_list_vim:
973 if 'port-id' in net_item:
montesmorenocf227142017-01-12 12:24:21 +0000974 self.neutron.delete_port(net_item['port-id'])
tiernoae4a8d12016-07-08 12:30:39 +0200975 self._format_exception(e)
976 except TypeError as e:
977 raise vimconn.vimconnException(type(e).__name__ + ": "+ str(e), http_code=vimconn.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100978
tiernoae4a8d12016-07-08 12:30:39 +0200979 def get_vminstance(self,vm_id):
tierno7edb6752016-03-21 17:37:52 +0100980 '''Returns the VM instance information from VIM'''
tiernoae4a8d12016-07-08 12:30:39 +0200981 #self.logger.debug("Getting VM from VIM")
tierno7edb6752016-03-21 17:37:52 +0100982 try:
983 self._reload_connection()
984 server = self.nova.servers.find(id=vm_id)
985 #TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
tiernoae4a8d12016-07-08 12:30:39 +0200986 return server.to_dict()
tierno8e995ce2016-09-22 08:13:00 +0000987 except (ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.NotFound, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200988 self._format_exception(e)
989
990 def get_vminstance_console(self,vm_id, console_type="vnc"):
tierno7edb6752016-03-21 17:37:52 +0100991 '''
992 Get a console for the virtual machine
993 Params:
994 vm_id: uuid of the VM
995 console_type, can be:
996 "novnc" (by default), "xvpvnc" for VNC types,
997 "rdp-html5" for RDP types, "spice-html5" for SPICE types
tiernoae4a8d12016-07-08 12:30:39 +0200998 Returns dict with the console parameters:
999 protocol: ssh, ftp, http, https, ...
1000 server: usually ip address
1001 port: the http, ssh, ... port
1002 suffix: extra text, e.g. the http path and query string
tierno7edb6752016-03-21 17:37:52 +01001003 '''
tiernoae4a8d12016-07-08 12:30:39 +02001004 self.logger.debug("Getting VM CONSOLE from VIM")
tierno7edb6752016-03-21 17:37:52 +01001005 try:
1006 self._reload_connection()
1007 server = self.nova.servers.find(id=vm_id)
1008 if console_type == None or console_type == "novnc":
1009 console_dict = server.get_vnc_console("novnc")
1010 elif console_type == "xvpvnc":
1011 console_dict = server.get_vnc_console(console_type)
1012 elif console_type == "rdp-html5":
1013 console_dict = server.get_rdp_console(console_type)
1014 elif console_type == "spice-html5":
1015 console_dict = server.get_spice_console(console_type)
1016 else:
tiernoae4a8d12016-07-08 12:30:39 +02001017 raise vimconn.vimconnException("console type '{}' not allowed".format(console_type), http_code=vimconn.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001018
1019 console_dict1 = console_dict.get("console")
1020 if console_dict1:
1021 console_url = console_dict1.get("url")
1022 if console_url:
1023 #parse console_url
1024 protocol_index = console_url.find("//")
1025 suffix_index = console_url[protocol_index+2:].find("/") + protocol_index+2
1026 port_index = console_url[protocol_index+2:suffix_index].find(":") + protocol_index+2
1027 if protocol_index < 0 or port_index<0 or suffix_index<0:
1028 return -vimconn.HTTP_Internal_Server_Error, "Unexpected response from VIM"
1029 console_dict={"protocol": console_url[0:protocol_index],
1030 "server": console_url[protocol_index+2:port_index],
1031 "port": console_url[port_index:suffix_index],
1032 "suffix": console_url[suffix_index+1:]
1033 }
1034 protocol_index += 2
tiernoae4a8d12016-07-08 12:30:39 +02001035 return console_dict
1036 raise vimconn.vimconnUnexpectedResponse("Unexpected response from VIM")
tierno7edb6752016-03-21 17:37:52 +01001037
tierno8e995ce2016-09-22 08:13:00 +00001038 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.BadRequest, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001039 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001040
tiernoae4a8d12016-07-08 12:30:39 +02001041 def delete_vminstance(self, vm_id):
1042 '''Removes a VM instance from VIM. Returns the old identifier
tierno7edb6752016-03-21 17:37:52 +01001043 '''
tiernoae4a8d12016-07-08 12:30:39 +02001044 #print "osconnector: Getting VM from VIM"
tierno7edb6752016-03-21 17:37:52 +01001045 try:
1046 self._reload_connection()
1047 #delete VM ports attached to this networks before the virtual machine
1048 ports = self.neutron.list_ports(device_id=vm_id)
1049 for p in ports['ports']:
1050 try:
1051 self.neutron.delete_port(p["id"])
1052 except Exception as e:
tiernoae4a8d12016-07-08 12:30:39 +02001053 self.logger.error("Error deleting port: " + type(e).__name__ + ": "+ str(e))
montesmoreno0c8def02016-12-22 12:16:23 +00001054
1055 #commented because detaching the volumes makes the servers.delete not work properly ?!?
1056 #dettach volumes attached
1057 server = self.nova.servers.get(vm_id)
1058 volumes_attached_dict = server._info['os-extended-volumes:volumes_attached']
1059 #for volume in volumes_attached_dict:
1060 # self.cinder.volumes.detach(volume['id'])
1061
tierno7edb6752016-03-21 17:37:52 +01001062 self.nova.servers.delete(vm_id)
montesmoreno0c8def02016-12-22 12:16:23 +00001063
1064 #delete volumes.
1065 #Although having detached them should have them in active status
1066 #we ensure in this loop
1067 keep_waiting = True
1068 elapsed_time = 0
1069 while keep_waiting and elapsed_time < volume_timeout:
1070 keep_waiting = False
1071 for volume in volumes_attached_dict:
1072 if self.cinder.volumes.get(volume['id']).status != 'available':
1073 keep_waiting = True
1074 else:
1075 self.cinder.volumes.delete(volume['id'])
1076 if keep_waiting:
1077 time.sleep(1)
1078 elapsed_time += 1
1079
tiernoae4a8d12016-07-08 12:30:39 +02001080 return vm_id
tierno8e995ce2016-09-22 08:13:00 +00001081 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001082 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001083 #TODO insert exception vimconn.HTTP_Unauthorized
1084 #if reaching here is because an exception
tierno7edb6752016-03-21 17:37:52 +01001085
tiernoae4a8d12016-07-08 12:30:39 +02001086 def refresh_vms_status(self, vm_list):
1087 '''Get the status of the virtual machines and their interfaces/ports
1088 Params: the list of VM identifiers
1089 Returns a dictionary with:
1090 vm_id: #VIM id of this Virtual Machine
1091 status: #Mandatory. Text with one of:
1092 # DELETED (not found at vim)
1093 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
1094 # OTHER (Vim reported other status not understood)
1095 # ERROR (VIM indicates an ERROR status)
1096 # ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running),
1097 # CREATING (on building process), ERROR
1098 # ACTIVE:NoMgmtIP (Active but any of its interface has an IP address
1099 #
1100 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
1101 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
1102 interfaces:
1103 - vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
1104 mac_address: #Text format XX:XX:XX:XX:XX:XX
1105 vim_net_id: #network id where this interface is connected
1106 vim_interface_id: #interface/port VIM id
1107 ip_address: #null, or text with IPv4, IPv6 address
tierno867ffe92017-03-27 12:50:34 +02001108 compute_node: #identification of compute node where PF,VF interface is allocated
1109 pci: #PCI address of the NIC that hosts the PF,VF
1110 vlan: #physical VLAN used for VF
tierno7edb6752016-03-21 17:37:52 +01001111 '''
tiernoae4a8d12016-07-08 12:30:39 +02001112 vm_dict={}
1113 self.logger.debug("refresh_vms status: Getting tenant VM instance information from VIM")
1114 for vm_id in vm_list:
1115 vm={}
1116 try:
1117 vm_vim = self.get_vminstance(vm_id)
1118 if vm_vim['status'] in vmStatus2manoFormat:
1119 vm['status'] = vmStatus2manoFormat[ vm_vim['status'] ]
tierno7edb6752016-03-21 17:37:52 +01001120 else:
tiernoae4a8d12016-07-08 12:30:39 +02001121 vm['status'] = "OTHER"
1122 vm['error_msg'] = "VIM status reported " + vm_vim['status']
tierno8e995ce2016-09-22 08:13:00 +00001123 try:
1124 vm['vim_info'] = yaml.safe_dump(vm_vim, default_flow_style=True, width=256)
1125 except yaml.representer.RepresenterError:
1126 vm['vim_info'] = str(vm_vim)
tiernoae4a8d12016-07-08 12:30:39 +02001127 vm["interfaces"] = []
1128 if vm_vim.get('fault'):
1129 vm['error_msg'] = str(vm_vim['fault'])
1130 #get interfaces
tierno7edb6752016-03-21 17:37:52 +01001131 try:
tiernoae4a8d12016-07-08 12:30:39 +02001132 self._reload_connection()
1133 port_dict=self.neutron.list_ports(device_id=vm_id)
1134 for port in port_dict["ports"]:
1135 interface={}
tierno8e995ce2016-09-22 08:13:00 +00001136 try:
1137 interface['vim_info'] = yaml.safe_dump(port, default_flow_style=True, width=256)
1138 except yaml.representer.RepresenterError:
1139 interface['vim_info'] = str(port)
tiernoae4a8d12016-07-08 12:30:39 +02001140 interface["mac_address"] = port.get("mac_address")
1141 interface["vim_net_id"] = port["network_id"]
1142 interface["vim_interface_id"] = port["id"]
Mike Marchetti5b9da422017-05-02 15:35:47 -04001143 # check if OS-EXT-SRV-ATTR:host is there,
1144 # in case of non-admin credentials, it will be missing
1145 if vm_vim.get('OS-EXT-SRV-ATTR:host'):
1146 interface["compute_node"] = vm_vim['OS-EXT-SRV-ATTR:host']
tierno867ffe92017-03-27 12:50:34 +02001147 interface["pci"] = None
Mike Marchetti5b9da422017-05-02 15:35:47 -04001148
1149 # check if binding:profile is there,
1150 # in case of non-admin credentials, it will be missing
1151 if port.get('binding:profile'):
1152 if port['binding:profile'].get('pci_slot'):
1153 # TODO: At the moment sr-iov pci addresses are converted to PF pci addresses by setting the slot to 0x00
1154 # TODO: This is just a workaround valid for niantinc. Find a better way to do so
1155 # CHANGE DDDD:BB:SS.F to DDDD:BB:00.(F%2) assuming there are 2 ports per nic
1156 pci = port['binding:profile']['pci_slot']
1157 # interface["pci"] = pci[:-4] + "00." + str(int(pci[-1]) % 2)
1158 interface["pci"] = pci
tierno867ffe92017-03-27 12:50:34 +02001159 interface["vlan"] = None
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001160 #if network is of type vlan and port is of type direct (sr-iov) then set vlan id
Pablo Montes Moreno51e553b2017-03-23 16:39:12 +01001161 network = self.neutron.show_network(port["network_id"])
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001162 if network['network'].get('provider:network_type') == 'vlan' and \
1163 port.get("binding:vnic_type") == "direct":
tierno867ffe92017-03-27 12:50:34 +02001164 interface["vlan"] = network['network'].get('provider:segmentation_id')
tiernoae4a8d12016-07-08 12:30:39 +02001165 ips=[]
1166 #look for floating ip address
1167 floating_ip_dict = self.neutron.list_floatingips(port_id=port["id"])
1168 if floating_ip_dict.get("floatingips"):
1169 ips.append(floating_ip_dict["floatingips"][0].get("floating_ip_address") )
tierno7edb6752016-03-21 17:37:52 +01001170
tiernoae4a8d12016-07-08 12:30:39 +02001171 for subnet in port["fixed_ips"]:
1172 ips.append(subnet["ip_address"])
1173 interface["ip_address"] = ";".join(ips)
1174 vm["interfaces"].append(interface)
1175 except Exception as e:
1176 self.logger.error("Error getting vm interface information " + type(e).__name__ + ": "+ str(e))
1177 except vimconn.vimconnNotFoundException as e:
1178 self.logger.error("Exception getting vm status: %s", str(e))
1179 vm['status'] = "DELETED"
1180 vm['error_msg'] = str(e)
1181 except vimconn.vimconnException as e:
1182 self.logger.error("Exception getting vm status: %s", str(e))
1183 vm['status'] = "VIM_ERROR"
1184 vm['error_msg'] = str(e)
1185 vm_dict[vm_id] = vm
1186 return vm_dict
tierno7edb6752016-03-21 17:37:52 +01001187
tiernoae4a8d12016-07-08 12:30:39 +02001188 def action_vminstance(self, vm_id, action_dict):
tierno7edb6752016-03-21 17:37:52 +01001189 '''Send and action over a VM instance from VIM
tiernoae4a8d12016-07-08 12:30:39 +02001190 Returns the vm_id if the action was successfully sent to the VIM'''
1191 self.logger.debug("Action over VM '%s': %s", vm_id, str(action_dict))
tierno7edb6752016-03-21 17:37:52 +01001192 try:
1193 self._reload_connection()
1194 server = self.nova.servers.find(id=vm_id)
1195 if "start" in action_dict:
1196 if action_dict["start"]=="rebuild":
1197 server.rebuild()
1198 else:
1199 if server.status=="PAUSED":
1200 server.unpause()
1201 elif server.status=="SUSPENDED":
1202 server.resume()
1203 elif server.status=="SHUTOFF":
1204 server.start()
1205 elif "pause" in action_dict:
1206 server.pause()
1207 elif "resume" in action_dict:
1208 server.resume()
1209 elif "shutoff" in action_dict or "shutdown" in action_dict:
1210 server.stop()
1211 elif "forceOff" in action_dict:
1212 server.stop() #TODO
1213 elif "terminate" in action_dict:
1214 server.delete()
1215 elif "createImage" in action_dict:
1216 server.create_image()
1217 #"path":path_schema,
1218 #"description":description_schema,
1219 #"name":name_schema,
1220 #"metadata":metadata_schema,
1221 #"imageRef": id_schema,
1222 #"disk": {"oneOf":[{"type": "null"}, {"type":"string"}] },
1223 elif "rebuild" in action_dict:
1224 server.rebuild(server.image['id'])
1225 elif "reboot" in action_dict:
1226 server.reboot() #reboot_type='SOFT'
1227 elif "console" in action_dict:
1228 console_type = action_dict["console"]
1229 if console_type == None or console_type == "novnc":
1230 console_dict = server.get_vnc_console("novnc")
1231 elif console_type == "xvpvnc":
1232 console_dict = server.get_vnc_console(console_type)
1233 elif console_type == "rdp-html5":
1234 console_dict = server.get_rdp_console(console_type)
1235 elif console_type == "spice-html5":
1236 console_dict = server.get_spice_console(console_type)
1237 else:
tiernoae4a8d12016-07-08 12:30:39 +02001238 raise vimconn.vimconnException("console type '{}' not allowed".format(console_type),
1239 http_code=vimconn.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001240 try:
1241 console_url = console_dict["console"]["url"]
1242 #parse console_url
1243 protocol_index = console_url.find("//")
1244 suffix_index = console_url[protocol_index+2:].find("/") + protocol_index+2
1245 port_index = console_url[protocol_index+2:suffix_index].find(":") + protocol_index+2
1246 if protocol_index < 0 or port_index<0 or suffix_index<0:
tiernoae4a8d12016-07-08 12:30:39 +02001247 raise vimconn.vimconnException("Unexpected response from VIM " + str(console_dict))
tierno7edb6752016-03-21 17:37:52 +01001248 console_dict2={"protocol": console_url[0:protocol_index],
1249 "server": console_url[protocol_index+2 : port_index],
1250 "port": int(console_url[port_index+1 : suffix_index]),
1251 "suffix": console_url[suffix_index+1:]
1252 }
tiernoae4a8d12016-07-08 12:30:39 +02001253 return console_dict2
1254 except Exception as e:
1255 raise vimconn.vimconnException("Unexpected response from VIM " + str(console_dict))
tierno7edb6752016-03-21 17:37:52 +01001256
tiernoae4a8d12016-07-08 12:30:39 +02001257 return vm_id
tierno8e995ce2016-09-22 08:13:00 +00001258 except (ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.NotFound, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001259 self._format_exception(e)
1260 #TODO insert exception vimconn.HTTP_Unauthorized
1261
1262#NOT USED FUNCTIONS
1263
1264 def new_external_port(self, port_data):
1265 #TODO openstack if needed
1266 '''Adds a external port to VIM'''
1267 '''Returns the port identifier'''
1268 return -vimconn.HTTP_Internal_Server_Error, "osconnector.new_external_port() not implemented"
1269
1270 def connect_port_network(self, port_id, network_id, admin=False):
1271 #TODO openstack if needed
1272 '''Connects a external port to a network'''
1273 '''Returns status code of the VIM response'''
1274 return -vimconn.HTTP_Internal_Server_Error, "osconnector.connect_port_network() not implemented"
1275
1276 def new_user(self, user_name, user_passwd, tenant_id=None):
1277 '''Adds a new user to openstack VIM'''
1278 '''Returns the user identifier'''
1279 self.logger.debug("osconnector: Adding a new user to VIM")
1280 try:
1281 self._reload_connection()
1282 user=self.keystone.users.create(user_name, user_passwd, tenant_id=tenant_id)
1283 #self.keystone.tenants.add_user(self.k_creds["username"], #role)
1284 return user.id
1285 except ksExceptions.ConnectionError as e:
1286 error_value=-vimconn.HTTP_Bad_Request
1287 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1288 except ksExceptions.ClientException as e: #TODO remove
tierno7edb6752016-03-21 17:37:52 +01001289 error_value=-vimconn.HTTP_Bad_Request
1290 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1291 #TODO insert exception vimconn.HTTP_Unauthorized
1292 #if reaching here is because an exception
1293 if self.debug:
tiernoae4a8d12016-07-08 12:30:39 +02001294 self.logger.debug("new_user " + error_text)
tierno7edb6752016-03-21 17:37:52 +01001295 return error_value, error_text
tiernoae4a8d12016-07-08 12:30:39 +02001296
1297 def delete_user(self, user_id):
1298 '''Delete a user from openstack VIM'''
1299 '''Returns the user identifier'''
1300 if self.debug:
1301 print "osconnector: Deleting a user from VIM"
1302 try:
1303 self._reload_connection()
1304 self.keystone.users.delete(user_id)
1305 return 1, user_id
1306 except ksExceptions.ConnectionError as e:
1307 error_value=-vimconn.HTTP_Bad_Request
1308 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1309 except ksExceptions.NotFound as e:
1310 error_value=-vimconn.HTTP_Not_Found
1311 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1312 except ksExceptions.ClientException as e: #TODO remove
1313 error_value=-vimconn.HTTP_Bad_Request
1314 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1315 #TODO insert exception vimconn.HTTP_Unauthorized
1316 #if reaching here is because an exception
1317 if self.debug:
1318 print "delete_tenant " + error_text
1319 return error_value, error_text
1320
tierno7edb6752016-03-21 17:37:52 +01001321 def get_hosts_info(self):
1322 '''Get the information of deployed hosts
1323 Returns the hosts content'''
1324 if self.debug:
1325 print "osconnector: Getting Host info from VIM"
1326 try:
1327 h_list=[]
1328 self._reload_connection()
1329 hypervisors = self.nova.hypervisors.list()
1330 for hype in hypervisors:
1331 h_list.append( hype.to_dict() )
1332 return 1, {"hosts":h_list}
1333 except nvExceptions.NotFound as e:
1334 error_value=-vimconn.HTTP_Not_Found
1335 error_text= (str(e) if len(e.args)==0 else str(e.args[0]))
1336 except (ksExceptions.ClientException, nvExceptions.ClientException) as e:
1337 error_value=-vimconn.HTTP_Bad_Request
1338 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1339 #TODO insert exception vimconn.HTTP_Unauthorized
1340 #if reaching here is because an exception
1341 if self.debug:
1342 print "get_hosts_info " + error_text
1343 return error_value, error_text
1344
1345 def get_hosts(self, vim_tenant):
1346 '''Get the hosts and deployed instances
1347 Returns the hosts content'''
1348 r, hype_dict = self.get_hosts_info()
1349 if r<0:
1350 return r, hype_dict
1351 hypervisors = hype_dict["hosts"]
1352 try:
1353 servers = self.nova.servers.list()
1354 for hype in hypervisors:
1355 for server in servers:
1356 if server.to_dict()['OS-EXT-SRV-ATTR:hypervisor_hostname']==hype['hypervisor_hostname']:
1357 if 'vm' in hype:
1358 hype['vm'].append(server.id)
1359 else:
1360 hype['vm'] = [server.id]
1361 return 1, hype_dict
1362 except nvExceptions.NotFound as e:
1363 error_value=-vimconn.HTTP_Not_Found
1364 error_text= (str(e) if len(e.args)==0 else str(e.args[0]))
1365 except (ksExceptions.ClientException, nvExceptions.ClientException) as e:
1366 error_value=-vimconn.HTTP_Bad_Request
1367 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1368 #TODO insert exception vimconn.HTTP_Unauthorized
1369 #if reaching here is because an exception
1370 if self.debug:
1371 print "get_hosts " + error_text
1372 return error_value, error_text
1373
tierno7edb6752016-03-21 17:37:52 +01001374