blob: 319f8c1a0e2a3fbcafb5f1cad7cb7abc9e3a77ca [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
tierno40e1bce2017-08-09 09:12:04 +020038import sys
kate721d79b2017-06-24 04:21:38 -070039import re
tierno7edb6752016-03-21 17:37:52 +010040
tiernob5cef372017-06-19 15:52:22 +020041from novaclient import client as nClient, exceptions as nvExceptions
42from keystoneauth1.identity import v2, v3
43from keystoneauth1 import session
tierno7edb6752016-03-21 17:37:52 +010044import keystoneclient.exceptions as ksExceptions
tiernof716aea2017-06-21 18:01:40 +020045import keystoneclient.v3.client as ksClient_v3
46import keystoneclient.v2_0.client as ksClient_v2
tiernob5cef372017-06-19 15:52:22 +020047from glanceclient import client as glClient
tierno7edb6752016-03-21 17:37:52 +010048import glanceclient.client as gl1Client
49import glanceclient.exc as gl1Exceptions
tiernob5cef372017-06-19 15:52:22 +020050from cinderclient import client as cClient
tierno7edb6752016-03-21 17:37:52 +010051from httplib import HTTPException
tiernob5cef372017-06-19 15:52:22 +020052from neutronclient.neutron import client as neClient
tierno7edb6752016-03-21 17:37:52 +010053from neutronclient.common import exceptions as neExceptions
54from requests.exceptions import ConnectionError
tierno40e1bce2017-08-09 09:12:04 +020055from email.mime.multipart import MIMEMultipart
56from email.mime.text import MIMEText
tierno7edb6752016-03-21 17:37:52 +010057
tierno40e1bce2017-08-09 09:12:04 +020058
59"""contain the openstack virtual machine status to openmano status"""
tierno7edb6752016-03-21 17:37:52 +010060vmStatus2manoFormat={'ACTIVE':'ACTIVE',
61 'PAUSED':'PAUSED',
62 'SUSPENDED': 'SUSPENDED',
63 'SHUTOFF':'INACTIVE',
64 'BUILD':'BUILD',
65 'ERROR':'ERROR','DELETED':'DELETED'
66 }
67netStatus2manoFormat={'ACTIVE':'ACTIVE','PAUSED':'PAUSED','INACTIVE':'INACTIVE','BUILD':'BUILD','ERROR':'ERROR','DELETED':'DELETED'
68 }
69
montesmoreno0c8def02016-12-22 12:16:23 +000070#global var to have a timeout creating and deleting volumes
71volume_timeout = 60
garciadeblas05a1a612017-07-23 20:26:28 +020072server_timeout = 300
montesmoreno0c8def02016-12-22 12:16:23 +000073
tierno7edb6752016-03-21 17:37:52 +010074class vimconnector(vimconn.vimconnector):
tiernob3d36742017-03-03 23:51:05 +010075 def __init__(self, uuid, name, tenant_id, tenant_name, url, url_admin=None, user=None, passwd=None,
76 log_level=None, config={}, persistent_info={}):
ahmadsa96af9f42017-01-31 16:17:14 +050077 '''using common constructor parameters. In this case
tierno7edb6752016-03-21 17:37:52 +010078 'url' is the keystone authorization url,
79 'url_admin' is not use
80 '''
tiernof716aea2017-06-21 18:01:40 +020081 api_version = config.get('APIversion')
82 if api_version and api_version not in ('v3.3', 'v2.0', '2', '3'):
tiernob5cef372017-06-19 15:52:22 +020083 raise vimconn.vimconnException("Invalid value '{}' for config:APIversion. "
tiernof716aea2017-06-21 18:01:40 +020084 "Allowed values are 'v3.3', 'v2.0', '2' or '3'".format(api_version))
kate721d79b2017-06-24 04:21:38 -070085 vim_type = config.get('vim_type')
86 if vim_type and vim_type not in ('vio', 'VIO'):
87 raise vimconn.vimconnException("Invalid value '{}' for config:vim_type."
88 "Allowed values are 'vio' or 'VIO'".format(vim_type))
89
90 if config.get('dataplane_net_vlan_range') is not None:
91 #validate vlan ranges provided by user
92 self._validate_vlan_ranges(config.get('dataplane_net_vlan_range'))
93
tiernob5cef372017-06-19 15:52:22 +020094 vimconn.vimconnector.__init__(self, uuid, name, tenant_id, tenant_name, url, url_admin, user, passwd, log_level,
95 config)
tiernob3d36742017-03-03 23:51:05 +010096
tiernob5cef372017-06-19 15:52:22 +020097 self.insecure = self.config.get("insecure", False)
tierno7edb6752016-03-21 17:37:52 +010098 if not url:
99 raise TypeError, 'url param can not be NoneType'
tiernob5cef372017-06-19 15:52:22 +0200100 self.persistent_info = persistent_info
mirabal29356312017-07-27 12:21:22 +0200101 self.availability_zone = persistent_info.get('availability_zone', None)
tiernob5cef372017-06-19 15:52:22 +0200102 self.session = persistent_info.get('session', {'reload_client': True})
103 self.nova = self.session.get('nova')
104 self.neutron = self.session.get('neutron')
105 self.cinder = self.session.get('cinder')
106 self.glance = self.session.get('glance')
tiernob39d49e2017-08-02 14:02:15 +0200107 self.glancev1 = self.session.get('glancev1')
tiernof716aea2017-06-21 18:01:40 +0200108 self.keystone = self.session.get('keystone')
109 self.api_version3 = self.session.get('api_version3')
kate721d79b2017-06-24 04:21:38 -0700110 self.vim_type = self.config.get("vim_type")
111 if self.vim_type:
112 self.vim_type = self.vim_type.upper()
113 if self.config.get("use_internal_endpoint"):
114 self.endpoint_type = "internalURL"
115 else:
116 self.endpoint_type = None
montesmoreno0c8def02016-12-22 12:16:23 +0000117
tierno73ad9e42016-09-12 18:11:11 +0200118 self.logger = logging.getLogger('openmano.vim.openstack')
kate721d79b2017-06-24 04:21:38 -0700119
120 ####### VIO Specific Changes #########
121 if self.vim_type == "VIO":
122 self.logger = logging.getLogger('openmano.vim.vio')
123
tiernofe789902016-09-29 14:20:44 +0000124 if log_level:
kate54616752017-09-05 23:26:28 -0700125 self.logger.setLevel( getattr(logging, log_level))
tiernof716aea2017-06-21 18:01:40 +0200126
127 def __getitem__(self, index):
128 """Get individuals parameters.
129 Throw KeyError"""
130 if index == 'project_domain_id':
131 return self.config.get("project_domain_id")
132 elif index == 'user_domain_id':
133 return self.config.get("user_domain_id")
134 else:
tierno76a3c312017-06-29 16:42:15 +0200135 return vimconn.vimconnector.__getitem__(self, index)
tiernof716aea2017-06-21 18:01:40 +0200136
137 def __setitem__(self, index, value):
138 """Set individuals parameters and it is marked as dirty so to force connection reload.
139 Throw KeyError"""
140 if index == 'project_domain_id':
141 self.config["project_domain_id"] = value
142 elif index == 'user_domain_id':
143 self.config["user_domain_id"] = value
144 else:
145 vimconn.vimconnector.__setitem__(self, index, value)
tiernob5cef372017-06-19 15:52:22 +0200146 self.session['reload_client'] = True
tiernof716aea2017-06-21 18:01:40 +0200147
tierno7edb6752016-03-21 17:37:52 +0100148 def _reload_connection(self):
149 '''Called before any operation, it check if credentials has changed
150 Throw keystoneclient.apiclient.exceptions.AuthorizationFailure
151 '''
152 #TODO control the timing and possible token timeout, but it seams that python client does this task for us :-)
tiernob5cef372017-06-19 15:52:22 +0200153 if self.session['reload_client']:
tiernof716aea2017-06-21 18:01:40 +0200154 if self.config.get('APIversion'):
155 self.api_version3 = self.config['APIversion'] == 'v3.3' or self.config['APIversion'] == '3'
156 else: # get from ending auth_url that end with v3 or with v2.0
157 self.api_version3 = self.url.split("/")[-1] == "v3"
158 self.session['api_version3'] = self.api_version3
159 if self.api_version3:
160 auth = v3.Password(auth_url=self.url,
tiernob5cef372017-06-19 15:52:22 +0200161 username=self.user,
162 password=self.passwd,
163 project_name=self.tenant_name,
164 project_id=self.tenant_id,
165 project_domain_id=self.config.get('project_domain_id', 'default'),
166 user_domain_id=self.config.get('user_domain_id', 'default'))
ahmadsa95baa272016-11-30 09:14:11 +0500167 else:
tiernof716aea2017-06-21 18:01:40 +0200168 auth = v2.Password(auth_url=self.url,
tiernob5cef372017-06-19 15:52:22 +0200169 username=self.user,
170 password=self.passwd,
171 tenant_name=self.tenant_name,
172 tenant_id=self.tenant_id)
173 sess = session.Session(auth=auth, verify=not self.insecure)
tiernof716aea2017-06-21 18:01:40 +0200174 if self.api_version3:
kate721d79b2017-06-24 04:21:38 -0700175 self.keystone = ksClient_v3.Client(session=sess, endpoint_type=self.endpoint_type)
tiernof716aea2017-06-21 18:01:40 +0200176 else:
kate721d79b2017-06-24 04:21:38 -0700177 self.keystone = ksClient_v2.Client(session=sess, endpoint_type=self.endpoint_type)
tiernof716aea2017-06-21 18:01:40 +0200178 self.session['keystone'] = self.keystone
montesmoreno9317d302017-08-16 12:48:23 +0200179 # In order to enable microversion functionality an explicit microversion must be specified in 'config'.
180 # This implementation approach is due to the warning message in
181 # https://developer.openstack.org/api-guide/compute/microversions.html
182 # where it is stated that microversion backwards compatibility is not guaranteed and clients should
183 # always require an specific microversion.
184 # To be able to use 'device role tagging' functionality define 'microversion: 2.32' in datacenter config
185 version = self.config.get("microversion")
186 if not version:
187 version = "2.1"
kate54616752017-09-05 23:26:28 -0700188 self.nova = self.session['nova'] = nClient.Client(str(version), session=sess, endpoint_type=self.endpoint_type)
kate721d79b2017-06-24 04:21:38 -0700189 self.neutron = self.session['neutron'] = neClient.Client('2.0', session=sess, endpoint_type=self.endpoint_type)
190 self.cinder = self.session['cinder'] = cClient.Client(2, session=sess, endpoint_type=self.endpoint_type)
191 if self.endpoint_type == "internalURL":
192 glance_service_id = self.keystone.services.list(name="glance")[0].id
193 glance_endpoint = self.keystone.endpoints.list(glance_service_id, interface="internal")[0].url
194 else:
195 glance_endpoint = None
196 self.glance = self.session['glance'] = glClient.Client(2, session=sess, endpoint=glance_endpoint)
197 #using version 1 of glance client in new_image()
198 self.glancev1 = self.session['glancev1'] = glClient.Client('1', session=sess,
199 endpoint=glance_endpoint)
tiernob5cef372017-06-19 15:52:22 +0200200 self.session['reload_client'] = False
201 self.persistent_info['session'] = self.session
mirabal29356312017-07-27 12:21:22 +0200202 # add availablity zone info inside self.persistent_info
203 self._set_availablity_zones()
204 self.persistent_info['availability_zone'] = self.availability_zone
ahmadsa95baa272016-11-30 09:14:11 +0500205
tierno7edb6752016-03-21 17:37:52 +0100206 def __net_os2mano(self, net_list_dict):
207 '''Transform the net openstack format to mano format
208 net_list_dict can be a list of dict or a single dict'''
209 if type(net_list_dict) is dict:
210 net_list_=(net_list_dict,)
211 elif type(net_list_dict) is list:
212 net_list_=net_list_dict
213 else:
214 raise TypeError("param net_list_dict must be a list or a dictionary")
215 for net in net_list_:
216 if net.get('provider:network_type') == "vlan":
217 net['type']='data'
218 else:
219 net['type']='bridge'
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +0200220
tiernoae4a8d12016-07-08 12:30:39 +0200221 def _format_exception(self, exception):
222 '''Transform a keystone, nova, neutron exception into a vimconn exception'''
223 if isinstance(exception, (HTTPException, gl1Exceptions.HTTPException, gl1Exceptions.CommunicationError,
tierno8e995ce2016-09-22 08:13:00 +0000224 ConnectionError, ksExceptions.ConnectionError, neExceptions.ConnectionFailed
225 )):
tiernoae4a8d12016-07-08 12:30:39 +0200226 raise vimconn.vimconnConnectionException(type(exception).__name__ + ": " + str(exception))
227 elif isinstance(exception, (nvExceptions.ClientException, ksExceptions.ClientException,
228 neExceptions.NeutronException, nvExceptions.BadRequest)):
229 raise vimconn.vimconnUnexpectedResponse(type(exception).__name__ + ": " + str(exception))
230 elif isinstance(exception, (neExceptions.NetworkNotFoundClient, nvExceptions.NotFound)):
231 raise vimconn.vimconnNotFoundException(type(exception).__name__ + ": " + str(exception))
232 elif isinstance(exception, nvExceptions.Conflict):
233 raise vimconn.vimconnConflictException(type(exception).__name__ + ": " + str(exception))
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +0200234 elif isinstance(exception, vimconn.vimconnException):
235 raise
tiernof716aea2017-06-21 18:01:40 +0200236 else: # ()
tiernob84cbdc2017-07-07 14:30:30 +0200237 self.logger.error("General Exception " + str(exception), exc_info=True)
tiernoae4a8d12016-07-08 12:30:39 +0200238 raise vimconn.vimconnConnectionException(type(exception).__name__ + ": " + str(exception))
239
240 def get_tenant_list(self, filter_dict={}):
241 '''Obtain tenants of VIM
242 filter_dict can contain the following keys:
243 name: filter by tenant name
244 id: filter by tenant uuid/id
245 <other VIM specific>
246 Returns the tenant list of dictionaries: [{'name':'<name>, 'id':'<id>, ...}, ...]
247 '''
ahmadsa95baa272016-11-30 09:14:11 +0500248 self.logger.debug("Getting tenants from VIM filter: '%s'", str(filter_dict))
tiernoae4a8d12016-07-08 12:30:39 +0200249 try:
250 self._reload_connection()
tiernof716aea2017-06-21 18:01:40 +0200251 if self.api_version3:
252 project_class_list = self.keystone.projects.list(name=filter_dict.get("name"))
ahmadsa95baa272016-11-30 09:14:11 +0500253 else:
tiernof716aea2017-06-21 18:01:40 +0200254 project_class_list = self.keystone.tenants.findall(**filter_dict)
ahmadsa95baa272016-11-30 09:14:11 +0500255 project_list=[]
256 for project in project_class_list:
tiernof716aea2017-06-21 18:01:40 +0200257 if filter_dict.get('id') and filter_dict["id"] != project.id:
258 continue
ahmadsa95baa272016-11-30 09:14:11 +0500259 project_list.append(project.to_dict())
260 return project_list
tiernof716aea2017-06-21 18:01:40 +0200261 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()
tiernof716aea2017-06-21 18:01:40 +0200269 if self.api_version3:
270 project = self.keystone.projects.create(tenant_name, self.config.get("project_domain_id", "default"),
271 description=tenant_description, is_domain=False)
ahmadsa95baa272016-11-30 09:14:11 +0500272 else:
tiernof716aea2017-06-21 18:01:40 +0200273 project = self.keystone.tenants.create(tenant_name, tenant_description)
ahmadsa95baa272016-11-30 09:14:11 +0500274 return project.id
tierno8e995ce2016-09-22 08:13:00 +0000275 except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200276 self._format_exception(e)
277
278 def delete_tenant(self, tenant_id):
279 '''Delete a tenant from openstack VIM. Returns the old tenant identifier'''
280 self.logger.debug("Deleting tenant %s from VIM", tenant_id)
281 try:
282 self._reload_connection()
tiernof716aea2017-06-21 18:01:40 +0200283 if self.api_version3:
ahmadsa95baa272016-11-30 09:14:11 +0500284 self.keystone.projects.delete(tenant_id)
285 else:
286 self.keystone.tenants.delete(tenant_id)
tiernoae4a8d12016-07-08 12:30:39 +0200287 return tenant_id
tierno8e995ce2016-09-22 08:13:00 +0000288 except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200289 self._format_exception(e)
ahmadsa95baa272016-11-30 09:14:11 +0500290
garciadeblas9f8456e2016-09-05 05:02:59 +0200291 def new_network(self,net_name, net_type, ip_profile=None, shared=False, vlan=None):
tiernoae4a8d12016-07-08 12:30:39 +0200292 '''Adds a tenant network to VIM. Returns the network identifier'''
293 self.logger.debug("Adding a new network to VIM name '%s', type '%s'", net_name, net_type)
garciadeblasedca7b32016-09-29 14:01:52 +0000294 #self.logger.debug(">>>>>>>>>>>>>>>>>> IP profile %s", str(ip_profile))
tierno7edb6752016-03-21 17:37:52 +0100295 try:
garciadeblasedca7b32016-09-29 14:01:52 +0000296 new_net = None
tierno7edb6752016-03-21 17:37:52 +0100297 self._reload_connection()
298 network_dict = {'name': net_name, 'admin_state_up': True}
299 if net_type=="data" or net_type=="ptp":
300 if self.config.get('dataplane_physical_net') == None:
tiernoae4a8d12016-07-08 12:30:39 +0200301 raise vimconn.vimconnConflictException("You must provide a 'dataplane_physical_net' at config value before creating sriov network")
tierno7edb6752016-03-21 17:37:52 +0100302 network_dict["provider:physical_network"] = self.config['dataplane_physical_net'] #"physnet_sriov" #TODO physical
303 network_dict["provider:network_type"] = "vlan"
304 if vlan!=None:
305 network_dict["provider:network_type"] = vlan
kate721d79b2017-06-24 04:21:38 -0700306
307 ####### VIO Specific Changes #########
308 if self.vim_type == "VIO":
309 if vlan is not None:
310 network_dict["provider:segmentation_id"] = vlan
311 else:
312 if self.config.get('dataplane_net_vlan_range') is None:
313 raise vimconn.vimconnConflictException("You must provide "\
314 "'dataplane_net_vlan_range' in format [start_ID - end_ID]"\
315 "at config value before creating sriov network with vlan tag")
316
317 network_dict["provider:segmentation_id"] = self._genrate_vlanID()
318
tiernoae4a8d12016-07-08 12:30:39 +0200319 network_dict["shared"]=shared
tierno7edb6752016-03-21 17:37:52 +0100320 new_net=self.neutron.create_network({'network':network_dict})
321 #print new_net
garciadeblas9f8456e2016-09-05 05:02:59 +0200322 #create subnetwork, even if there is no profile
323 if not ip_profile:
324 ip_profile = {}
325 if 'subnet_address' not in ip_profile:
garciadeblas2299e3b2017-01-26 14:35:55 +0000326 #Fake subnet is required
327 subnet_rand = random.randint(0, 255)
328 ip_profile['subnet_address'] = "192.168.{}.0/24".format(subnet_rand)
garciadeblas9f8456e2016-09-05 05:02:59 +0200329 if 'ip_version' not in ip_profile:
330 ip_profile['ip_version'] = "IPv4"
tiernoa1fb4462017-06-30 12:25:50 +0200331 subnet = {"name":net_name+"-subnet",
tierno7edb6752016-03-21 17:37:52 +0100332 "network_id": new_net["network"]["id"],
garciadeblas9f8456e2016-09-05 05:02:59 +0200333 "ip_version": 4 if ip_profile['ip_version']=="IPv4" else 6,
334 "cidr": ip_profile['subnet_address']
tierno7edb6752016-03-21 17:37:52 +0100335 }
tiernoa1fb4462017-06-30 12:25:50 +0200336 # Gateway should be set to None if not needed. Otherwise openstack assigns one by default
337 subnet['gateway_ip'] = ip_profile.get('gateway_address')
garciadeblasedca7b32016-09-29 14:01:52 +0000338 if ip_profile.get('dns_address'):
tierno455612d2017-05-30 16:40:10 +0200339 subnet['dns_nameservers'] = ip_profile['dns_address'].split(";")
garciadeblas9f8456e2016-09-05 05:02:59 +0200340 if 'dhcp_enabled' in ip_profile:
341 subnet['enable_dhcp'] = False if ip_profile['dhcp_enabled']=="false" else True
342 if 'dhcp_start_address' in ip_profile:
tiernoa1fb4462017-06-30 12:25:50 +0200343 subnet['allocation_pools'] = []
garciadeblas9f8456e2016-09-05 05:02:59 +0200344 subnet['allocation_pools'].append(dict())
345 subnet['allocation_pools'][0]['start'] = ip_profile['dhcp_start_address']
346 if 'dhcp_count' in ip_profile:
347 #parts = ip_profile['dhcp_start_address'].split('.')
348 #ip_int = (int(parts[0]) << 24) + (int(parts[1]) << 16) + (int(parts[2]) << 8) + int(parts[3])
349 ip_int = int(netaddr.IPAddress(ip_profile['dhcp_start_address']))
garciadeblas21d795b2016-09-29 17:31:46 +0200350 ip_int += ip_profile['dhcp_count'] - 1
garciadeblas9f8456e2016-09-05 05:02:59 +0200351 ip_str = str(netaddr.IPAddress(ip_int))
352 subnet['allocation_pools'][0]['end'] = ip_str
garciadeblasedca7b32016-09-29 14:01:52 +0000353 #self.logger.debug(">>>>>>>>>>>>>>>>>> Subnet: %s", str(subnet))
tierno7edb6752016-03-21 17:37:52 +0100354 self.neutron.create_subnet({"subnet": subnet} )
tiernoae4a8d12016-07-08 12:30:39 +0200355 return new_net["network"]["id"]
tierno8e995ce2016-09-22 08:13:00 +0000356 except (neExceptions.ConnectionFailed, ksExceptions.ClientException, neExceptions.NeutronException, ConnectionError) as e:
garciadeblasedca7b32016-09-29 14:01:52 +0000357 if new_net:
358 self.neutron.delete_network(new_net['network']['id'])
tiernoae4a8d12016-07-08 12:30:39 +0200359 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100360
361 def get_network_list(self, filter_dict={}):
362 '''Obtain tenant networks of VIM
363 Filter_dict can be:
364 name: network name
365 id: network uuid
366 shared: boolean
367 tenant_id: tenant
368 admin_state_up: boolean
369 status: 'ACTIVE'
370 Returns the network list of dictionaries
371 '''
tiernoae4a8d12016-07-08 12:30:39 +0200372 self.logger.debug("Getting network from VIM filter: '%s'", str(filter_dict))
tierno7edb6752016-03-21 17:37:52 +0100373 try:
374 self._reload_connection()
tiernof716aea2017-06-21 18:01:40 +0200375 if self.api_version3 and "tenant_id" in filter_dict:
376 filter_dict['project_id'] = filter_dict.pop('tenant_id') #TODO check
tierno7edb6752016-03-21 17:37:52 +0100377 net_dict=self.neutron.list_networks(**filter_dict)
378 net_list=net_dict["networks"]
379 self.__net_os2mano(net_list)
tiernoae4a8d12016-07-08 12:30:39 +0200380 return net_list
tierno8e995ce2016-09-22 08:13:00 +0000381 except (neExceptions.ConnectionFailed, ksExceptions.ClientException, neExceptions.NeutronException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200382 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100383
tiernoae4a8d12016-07-08 12:30:39 +0200384 def get_network(self, net_id):
385 '''Obtain details of network from VIM
386 Returns the network information from a network id'''
387 self.logger.debug(" Getting tenant network %s from VIM", net_id)
tierno7edb6752016-03-21 17:37:52 +0100388 filter_dict={"id": net_id}
tiernoae4a8d12016-07-08 12:30:39 +0200389 net_list = self.get_network_list(filter_dict)
tierno7edb6752016-03-21 17:37:52 +0100390 if len(net_list)==0:
tiernoae4a8d12016-07-08 12:30:39 +0200391 raise vimconn.vimconnNotFoundException("Network '{}' not found".format(net_id))
tierno7edb6752016-03-21 17:37:52 +0100392 elif len(net_list)>1:
tiernoae4a8d12016-07-08 12:30:39 +0200393 raise vimconn.vimconnConflictException("Found more than one network with this criteria")
tierno7edb6752016-03-21 17:37:52 +0100394 net = net_list[0]
395 subnets=[]
396 for subnet_id in net.get("subnets", () ):
397 try:
398 subnet = self.neutron.show_subnet(subnet_id)
399 except Exception as e:
tiernoae4a8d12016-07-08 12:30:39 +0200400 self.logger.error("osconnector.get_network(): Error getting subnet %s %s" % (net_id, str(e)))
401 subnet = {"id": subnet_id, "fault": str(e)}
tierno7edb6752016-03-21 17:37:52 +0100402 subnets.append(subnet)
403 net["subnets"] = subnets
Pablo Montes Moreno51e553b2017-03-23 16:39:12 +0100404 net["encapsulation"] = net.get('provider:network_type')
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100405 net["segmentation_id"] = net.get('provider:segmentation_id')
tiernoae4a8d12016-07-08 12:30:39 +0200406 return net
tierno7edb6752016-03-21 17:37:52 +0100407
tiernoae4a8d12016-07-08 12:30:39 +0200408 def delete_network(self, net_id):
409 '''Deletes a tenant network from VIM. Returns the old network identifier'''
410 self.logger.debug("Deleting network '%s' from VIM", net_id)
tierno7edb6752016-03-21 17:37:52 +0100411 try:
412 self._reload_connection()
413 #delete VM ports attached to this networks before the network
414 ports = self.neutron.list_ports(network_id=net_id)
415 for p in ports['ports']:
416 try:
417 self.neutron.delete_port(p["id"])
418 except Exception as e:
tiernoae4a8d12016-07-08 12:30:39 +0200419 self.logger.error("Error deleting port %s: %s", p["id"], str(e))
tierno7edb6752016-03-21 17:37:52 +0100420 self.neutron.delete_network(net_id)
tiernoae4a8d12016-07-08 12:30:39 +0200421 return net_id
422 except (neExceptions.ConnectionFailed, neExceptions.NetworkNotFoundClient, neExceptions.NeutronException,
tierno8e995ce2016-09-22 08:13:00 +0000423 ksExceptions.ClientException, neExceptions.NeutronException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200424 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100425
tiernoae4a8d12016-07-08 12:30:39 +0200426 def refresh_nets_status(self, net_list):
427 '''Get the status of the networks
428 Params: the list of network identifiers
429 Returns a dictionary with:
430 net_id: #VIM id of this network
431 status: #Mandatory. Text with one of:
432 # DELETED (not found at vim)
433 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
434 # OTHER (Vim reported other status not understood)
435 # ERROR (VIM indicates an ERROR status)
436 # ACTIVE, INACTIVE, DOWN (admin down),
437 # BUILD (on building process)
438 #
439 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
440 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
441
442 '''
443 net_dict={}
444 for net_id in net_list:
445 net = {}
446 try:
447 net_vim = self.get_network(net_id)
448 if net_vim['status'] in netStatus2manoFormat:
449 net["status"] = netStatus2manoFormat[ net_vim['status'] ]
450 else:
451 net["status"] = "OTHER"
452 net["error_msg"] = "VIM status reported " + net_vim['status']
453
tierno8e995ce2016-09-22 08:13:00 +0000454 if net['status'] == "ACTIVE" and not net_vim['admin_state_up']:
tiernoae4a8d12016-07-08 12:30:39 +0200455 net['status'] = 'DOWN'
tierno8e995ce2016-09-22 08:13:00 +0000456 try:
457 net['vim_info'] = yaml.safe_dump(net_vim, default_flow_style=True, width=256)
458 except yaml.representer.RepresenterError:
459 net['vim_info'] = str(net_vim)
tiernoae4a8d12016-07-08 12:30:39 +0200460 if net_vim.get('fault'): #TODO
461 net['error_msg'] = str(net_vim['fault'])
462 except vimconn.vimconnNotFoundException as e:
463 self.logger.error("Exception getting net status: %s", str(e))
464 net['status'] = "DELETED"
465 net['error_msg'] = str(e)
466 except vimconn.vimconnException as e:
467 self.logger.error("Exception getting net status: %s", str(e))
468 net['status'] = "VIM_ERROR"
469 net['error_msg'] = str(e)
470 net_dict[net_id] = net
471 return net_dict
472
473 def get_flavor(self, flavor_id):
474 '''Obtain flavor details from the VIM. Returns the flavor dict details'''
475 self.logger.debug("Getting flavor '%s'", flavor_id)
tierno7edb6752016-03-21 17:37:52 +0100476 try:
477 self._reload_connection()
478 flavor = self.nova.flavors.find(id=flavor_id)
479 #TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
tiernoae4a8d12016-07-08 12:30:39 +0200480 return flavor.to_dict()
tierno8e995ce2016-09-22 08:13:00 +0000481 except (nvExceptions.NotFound, nvExceptions.ClientException, ksExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200482 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100483
tiernocf157a82017-01-30 14:07:06 +0100484 def get_flavor_id_from_data(self, flavor_dict):
485 """Obtain flavor id that match the flavor description
486 Returns the flavor_id or raises a vimconnNotFoundException
tiernoe26fc7a2017-05-30 14:43:03 +0200487 flavor_dict: contains the required ram, vcpus, disk
488 If 'use_existing_flavors' is set to True at config, the closer flavor that provides same or more ram, vcpus
489 and disk is returned. Otherwise a flavor with exactly same ram, vcpus and disk is returned or a
490 vimconnNotFoundException is raised
tiernocf157a82017-01-30 14:07:06 +0100491 """
tiernoe26fc7a2017-05-30 14:43:03 +0200492 exact_match = False if self.config.get('use_existing_flavors') else True
tiernocf157a82017-01-30 14:07:06 +0100493 try:
494 self._reload_connection()
tiernoe26fc7a2017-05-30 14:43:03 +0200495 flavor_candidate_id = None
496 flavor_candidate_data = (10000, 10000, 10000)
497 flavor_target = (flavor_dict["ram"], flavor_dict["vcpus"], flavor_dict["disk"])
498 # numa=None
499 numas = flavor_dict.get("extended", {}).get("numas")
tiernocf157a82017-01-30 14:07:06 +0100500 if numas:
501 #TODO
502 raise vimconn.vimconnNotFoundException("Flavor with EPA still not implemted")
503 # if len(numas) > 1:
504 # raise vimconn.vimconnNotFoundException("Cannot find any flavor with more than one numa")
505 # numa=numas[0]
506 # numas = extended.get("numas")
507 for flavor in self.nova.flavors.list():
508 epa = flavor.get_keys()
509 if epa:
510 continue
tiernoe26fc7a2017-05-30 14:43:03 +0200511 # TODO
512 flavor_data = (flavor.ram, flavor.vcpus, flavor.disk)
513 if flavor_data == flavor_target:
514 return flavor.id
515 elif not exact_match and flavor_target < flavor_data < flavor_candidate_data:
516 flavor_candidate_id = flavor.id
517 flavor_candidate_data = flavor_data
518 if not exact_match and flavor_candidate_id:
519 return flavor_candidate_id
tiernocf157a82017-01-30 14:07:06 +0100520 raise vimconn.vimconnNotFoundException("Cannot find any flavor matching '{}'".format(str(flavor_dict)))
521 except (nvExceptions.NotFound, nvExceptions.ClientException, ksExceptions.ClientException, ConnectionError) as e:
522 self._format_exception(e)
523
524
tiernoae4a8d12016-07-08 12:30:39 +0200525 def new_flavor(self, flavor_data, change_name_if_used=True):
tierno7edb6752016-03-21 17:37:52 +0100526 '''Adds a tenant flavor to openstack VIM
tiernoae4a8d12016-07-08 12:30:39 +0200527 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 +0100528 Returns the flavor identifier
529 '''
tiernoae4a8d12016-07-08 12:30:39 +0200530 self.logger.debug("Adding flavor '%s'", str(flavor_data))
tierno7edb6752016-03-21 17:37:52 +0100531 retry=0
tiernoae4a8d12016-07-08 12:30:39 +0200532 max_retries=3
tierno7edb6752016-03-21 17:37:52 +0100533 name_suffix = 0
tiernoae4a8d12016-07-08 12:30:39 +0200534 name=flavor_data['name']
535 while retry<max_retries:
tierno7edb6752016-03-21 17:37:52 +0100536 retry+=1
537 try:
538 self._reload_connection()
539 if change_name_if_used:
540 #get used names
541 fl_names=[]
542 fl=self.nova.flavors.list()
543 for f in fl:
544 fl_names.append(f.name)
545 while name in fl_names:
546 name_suffix += 1
tiernoae4a8d12016-07-08 12:30:39 +0200547 name = flavor_data['name']+"-" + str(name_suffix)
kate721d79b2017-06-24 04:21:38 -0700548
tiernoae4a8d12016-07-08 12:30:39 +0200549 ram = flavor_data.get('ram',64)
550 vcpus = flavor_data.get('vcpus',1)
tierno7edb6752016-03-21 17:37:52 +0100551 numa_properties=None
552
tiernoae4a8d12016-07-08 12:30:39 +0200553 extended = flavor_data.get("extended")
tierno7edb6752016-03-21 17:37:52 +0100554 if extended:
555 numas=extended.get("numas")
556 if numas:
557 numa_nodes = len(numas)
558 if numa_nodes > 1:
559 return -1, "Can not add flavor with more than one numa"
560 numa_properties = {"hw:numa_nodes":str(numa_nodes)}
561 numa_properties["hw:mem_page_size"] = "large"
562 numa_properties["hw:cpu_policy"] = "dedicated"
563 numa_properties["hw:numa_mempolicy"] = "strict"
kate721d79b2017-06-24 04:21:38 -0700564 if self.vim_type == "VIO":
565 numa_properties["vmware:extra_config"] = '{"numa.nodeAffinity":"0"}'
566 numa_properties["vmware:latency_sensitivity_level"] = "high"
tierno7edb6752016-03-21 17:37:52 +0100567 for numa in numas:
568 #overwrite ram and vcpus
569 ram = numa['memory']*1024
Pablo Montes Morenoea1d6232017-05-24 11:33:24 +0200570 #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 +0100571 if 'paired-threads' in numa:
572 vcpus = numa['paired-threads']*2
Pablo Montes Morenoea1d6232017-05-24 11:33:24 +0200573 #cpu_thread_policy "require" implies that the compute node must have an STM architecture
574 numa_properties["hw:cpu_thread_policy"] = "require"
575 numa_properties["hw:cpu_policy"] = "dedicated"
tierno7edb6752016-03-21 17:37:52 +0100576 elif 'cores' in numa:
577 vcpus = numa['cores']
Pablo Montes Morenoea1d6232017-05-24 11:33:24 +0200578 # cpu_thread_policy "prefer" implies that the host must not have an SMT architecture, or a non-SMT architecture will be emulated
579 numa_properties["hw:cpu_thread_policy"] = "isolate"
580 numa_properties["hw:cpu_policy"] = "dedicated"
tierno7edb6752016-03-21 17:37:52 +0100581 elif 'threads' in numa:
582 vcpus = numa['threads']
Pablo Montes Morenoea1d6232017-05-24 11:33:24 +0200583 # cpu_thread_policy "prefer" implies that the host may or may not have an SMT architecture
584 numa_properties["hw:cpu_thread_policy"] = "prefer"
585 numa_properties["hw:cpu_policy"] = "dedicated"
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +0200586 # for interface in numa.get("interfaces",() ):
587 # if interface["dedicated"]=="yes":
588 # raise vimconn.vimconnException("Passthrough interfaces are not supported for the openstack connector", http_code=vimconn.HTTP_Service_Unavailable)
589 # #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 +0100590
591 #create flavor
592 new_flavor=self.nova.flavors.create(name,
593 ram,
594 vcpus,
tiernoae4a8d12016-07-08 12:30:39 +0200595 flavor_data.get('disk',1),
596 is_public=flavor_data.get('is_public', True)
kate721d79b2017-06-24 04:21:38 -0700597 )
tierno7edb6752016-03-21 17:37:52 +0100598 #add metadata
599 if numa_properties:
600 new_flavor.set_keys(numa_properties)
tiernoae4a8d12016-07-08 12:30:39 +0200601 return new_flavor.id
tierno7edb6752016-03-21 17:37:52 +0100602 except nvExceptions.Conflict as e:
tiernoae4a8d12016-07-08 12:30:39 +0200603 if change_name_if_used and retry < max_retries:
tierno7edb6752016-03-21 17:37:52 +0100604 continue
tiernoae4a8d12016-07-08 12:30:39 +0200605 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100606 #except nvExceptions.BadRequest as e:
607 except (ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200608 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100609
tiernoae4a8d12016-07-08 12:30:39 +0200610 def delete_flavor(self,flavor_id):
611 '''Deletes a tenant flavor from openstack VIM. Returns the old flavor_id
tierno7edb6752016-03-21 17:37:52 +0100612 '''
tiernoae4a8d12016-07-08 12:30:39 +0200613 try:
614 self._reload_connection()
615 self.nova.flavors.delete(flavor_id)
616 return flavor_id
617 #except nvExceptions.BadRequest as e:
tierno8e995ce2016-09-22 08:13:00 +0000618 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200619 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100620
tiernoae4a8d12016-07-08 12:30:39 +0200621 def new_image(self,image_dict):
tierno7edb6752016-03-21 17:37:52 +0100622 '''
tiernoae4a8d12016-07-08 12:30:39 +0200623 Adds a tenant image to VIM. imge_dict is a dictionary with:
624 name: name
625 disk_format: qcow2, vhd, vmdk, raw (by default), ...
626 location: path or URI
627 public: "yes" or "no"
628 metadata: metadata of the image
629 Returns the image_id
tierno7edb6752016-03-21 17:37:52 +0100630 '''
tiernoae4a8d12016-07-08 12:30:39 +0200631 retry=0
632 max_retries=3
633 while retry<max_retries:
tierno7edb6752016-03-21 17:37:52 +0100634 retry+=1
635 try:
636 self._reload_connection()
637 #determine format http://docs.openstack.org/developer/glance/formats.html
638 if "disk_format" in image_dict:
639 disk_format=image_dict["disk_format"]
garciadeblas14480452017-01-10 13:08:07 +0100640 else: #autodiscover based on extension
tierno7edb6752016-03-21 17:37:52 +0100641 if image_dict['location'][-6:]==".qcow2":
642 disk_format="qcow2"
643 elif image_dict['location'][-4:]==".vhd":
644 disk_format="vhd"
645 elif image_dict['location'][-5:]==".vmdk":
646 disk_format="vmdk"
647 elif image_dict['location'][-4:]==".vdi":
648 disk_format="vdi"
649 elif image_dict['location'][-4:]==".iso":
650 disk_format="iso"
651 elif image_dict['location'][-4:]==".aki":
652 disk_format="aki"
653 elif image_dict['location'][-4:]==".ari":
654 disk_format="ari"
655 elif image_dict['location'][-4:]==".ami":
656 disk_format="ami"
657 else:
658 disk_format="raw"
tiernoae4a8d12016-07-08 12:30:39 +0200659 self.logger.debug("new_image: '%s' loading from '%s'", image_dict['name'], image_dict['location'])
tierno7edb6752016-03-21 17:37:52 +0100660 if image_dict['location'][0:4]=="http":
tiernob39d49e2017-08-02 14:02:15 +0200661 new_image = self.glancev1.images.create(name=image_dict['name'], is_public=image_dict.get('public',"yes")=="yes",
tierno7edb6752016-03-21 17:37:52 +0100662 container_format="bare", location=image_dict['location'], disk_format=disk_format)
663 else: #local path
664 with open(image_dict['location']) as fimage:
tiernob39d49e2017-08-02 14:02:15 +0200665 new_image = self.glancev1.images.create(name=image_dict['name'], is_public=image_dict.get('public',"yes")=="yes",
tierno7edb6752016-03-21 17:37:52 +0100666 container_format="bare", data=fimage, disk_format=disk_format)
667 #insert metadata. We cannot use 'new_image.properties.setdefault'
668 #because nova and glance are "INDEPENDENT" and we are using nova for reading metadata
669 new_image_nova=self.nova.images.find(id=new_image.id)
670 new_image_nova.metadata.setdefault('location',image_dict['location'])
671 metadata_to_load = image_dict.get('metadata')
672 if metadata_to_load:
673 for k,v in yaml.load(metadata_to_load).iteritems():
674 new_image_nova.metadata.setdefault(k,v)
tiernoae4a8d12016-07-08 12:30:39 +0200675 return new_image.id
676 except (nvExceptions.Conflict, ksExceptions.ClientException, nvExceptions.ClientException) as e:
677 self._format_exception(e)
tierno8e995ce2016-09-22 08:13:00 +0000678 except (HTTPException, gl1Exceptions.HTTPException, gl1Exceptions.CommunicationError, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200679 if retry==max_retries:
680 continue
681 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100682 except IOError as e: #can not open the file
tiernoae4a8d12016-07-08 12:30:39 +0200683 raise vimconn.vimconnConnectionException(type(e).__name__ + ": " + str(e)+ " for " + image_dict['location'],
684 http_code=vimconn.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100685
tiernoae4a8d12016-07-08 12:30:39 +0200686 def delete_image(self, image_id):
687 '''Deletes a tenant image from openstack VIM. Returns the old id
tierno7edb6752016-03-21 17:37:52 +0100688 '''
tiernoae4a8d12016-07-08 12:30:39 +0200689 try:
690 self._reload_connection()
691 self.nova.images.delete(image_id)
692 return image_id
tierno8e995ce2016-09-22 08:13:00 +0000693 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e: #TODO remove
tiernoae4a8d12016-07-08 12:30:39 +0200694 self._format_exception(e)
695
696 def get_image_id_from_path(self, path):
garciadeblasb69fa9f2016-09-28 12:04:10 +0200697 '''Get the image id from image path in the VIM database. Returns the image_id'''
tiernoae4a8d12016-07-08 12:30:39 +0200698 try:
699 self._reload_connection()
700 images = self.nova.images.list()
701 for image in images:
702 if image.metadata.get("location")==path:
703 return image.id
704 raise vimconn.vimconnNotFoundException("image with location '{}' not found".format( path))
tierno8e995ce2016-09-22 08:13:00 +0000705 except (ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200706 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100707
garciadeblasb69fa9f2016-09-28 12:04:10 +0200708 def get_image_list(self, filter_dict={}):
709 '''Obtain tenant images from VIM
710 Filter_dict can be:
711 id: image id
712 name: image name
713 checksum: image checksum
714 Returns the image list of dictionaries:
715 [{<the fields at Filter_dict plus some VIM specific>}, ...]
716 List can be empty
717 '''
718 self.logger.debug("Getting image list from VIM filter: '%s'", str(filter_dict))
719 try:
720 self._reload_connection()
721 filter_dict_os=filter_dict.copy()
722 #First we filter by the available filter fields: name, id. The others are removed.
723 filter_dict_os.pop('checksum',None)
724 image_list=self.nova.images.findall(**filter_dict_os)
725 if len(image_list)==0:
726 return []
727 #Then we filter by the rest of filter fields: checksum
728 filtered_list = []
729 for image in image_list:
tierno4540ea52017-01-18 17:44:32 +0100730 image_class=self.glance.images.get(image.id)
731 if 'checksum' not in filter_dict or image_class['checksum']==filter_dict.get('checksum'):
732 filtered_list.append(image_class.copy())
garciadeblasb69fa9f2016-09-28 12:04:10 +0200733 return filtered_list
734 except (ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e:
735 self._format_exception(e)
736
tierno40e1bce2017-08-09 09:12:04 +0200737 @staticmethod
738 def _create_mimemultipart(content_list):
739 """Creates a MIMEmultipart text combining the content_list
740 :param content_list: list of text scripts to be combined
741 :return: str of the created MIMEmultipart. If the list is empty returns None, if the list contains only one
742 element MIMEmultipart is not created and this content is returned
743 """
744 if not content_list:
745 return None
746 elif len(content_list) == 1:
747 return content_list[0]
748 combined_message = MIMEMultipart()
749 for content in content_list:
750 if content.startswith('#include'):
751 format = 'text/x-include-url'
752 elif content.startswith('#include-once'):
753 format = 'text/x-include-once-url'
754 elif content.startswith('#!'):
755 format = 'text/x-shellscript'
756 elif content.startswith('#cloud-config'):
757 format = 'text/cloud-config'
758 elif content.startswith('#cloud-config-archive'):
759 format = 'text/cloud-config-archive'
760 elif content.startswith('#upstart-job'):
761 format = 'text/upstart-job'
762 elif content.startswith('#part-handler'):
763 format = 'text/part-handler'
764 elif content.startswith('#cloud-boothook'):
765 format = 'text/cloud-boothook'
766 else: # by default
767 format = 'text/x-shellscript'
768 sub_message = MIMEText(content, format, sys.getdefaultencoding())
769 combined_message.attach(sub_message)
770 return combined_message.as_string()
771
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +0200772 def __wait_for_vm(self, vm_id, status):
773 """wait until vm is in the desired status and return True.
774 If the VM gets in ERROR status, return false.
775 If the timeout is reached generate an exception"""
776 elapsed_time = 0
777 while elapsed_time < server_timeout:
778 vm_status = self.nova.servers.get(vm_id).status
779 if vm_status == status:
780 return True
781 if vm_status == 'ERROR':
782 return False
783 time.sleep(1)
784 elapsed_time += 1
785
786 # if we exceeded the timeout rollback
787 if elapsed_time >= server_timeout:
788 raise vimconn.vimconnException('Timeout waiting for instance ' + vm_id + ' to get ' + status,
789 http_code=vimconn.HTTP_Request_Timeout)
790
mirabal29356312017-07-27 12:21:22 +0200791 def _get_openstack_availablity_zones(self):
792 """
793 Get from openstack availability zones available
794 :return:
795 """
796 try:
797 openstack_availability_zone = self.nova.availability_zones.list()
798 openstack_availability_zone = [str(zone.zoneName) for zone in openstack_availability_zone
799 if zone.zoneName != 'internal']
800 return openstack_availability_zone
801 except Exception as e:
802 return None
803
804 def _set_availablity_zones(self):
805 """
806 Set vim availablity zone
807 :return:
808 """
809
810 if 'availability_zone' in self.config:
811 vim_availability_zones = self.config.get('availability_zone')
812 if isinstance(vim_availability_zones, str):
813 self.availability_zone = [vim_availability_zones]
814 elif isinstance(vim_availability_zones, list):
815 self.availability_zone = vim_availability_zones
816 else:
817 self.availability_zone = self._get_openstack_availablity_zones()
818
tierno5a3273c2017-08-29 11:43:46 +0200819 def _get_vm_availability_zone(self, availability_zone_index, availability_zone_list):
mirabal29356312017-07-27 12:21:22 +0200820 """
tierno5a3273c2017-08-29 11:43:46 +0200821 Return thge availability zone to be used by the created VM.
822 :return: The VIM availability zone to be used or None
mirabal29356312017-07-27 12:21:22 +0200823 """
tierno5a3273c2017-08-29 11:43:46 +0200824 if availability_zone_index is None:
825 if not self.config.get('availability_zone'):
826 return None
827 elif isinstance(self.config.get('availability_zone'), str):
828 return self.config['availability_zone']
829 else:
830 # TODO consider using a different parameter at config for default AV and AV list match
831 return self.config['availability_zone'][0]
mirabal29356312017-07-27 12:21:22 +0200832
tierno5a3273c2017-08-29 11:43:46 +0200833 vim_availability_zones = self.availability_zone
834 # check if VIM offer enough availability zones describe in the VNFD
835 if vim_availability_zones and len(availability_zone_list) <= len(vim_availability_zones):
836 # check if all the names of NFV AV match VIM AV names
837 match_by_index = False
838 for av in availability_zone_list:
839 if av not in vim_availability_zones:
840 match_by_index = True
841 break
842 if match_by_index:
843 return vim_availability_zones[availability_zone_index]
844 else:
845 return availability_zone_list[availability_zone_index]
mirabal29356312017-07-27 12:21:22 +0200846 else:
tierno5a3273c2017-08-29 11:43:46 +0200847 raise vimconn.vimconnConflictException("No enough availability zones at VIM for this deployment")
mirabal29356312017-07-27 12:21:22 +0200848
tierno5a3273c2017-08-29 11:43:46 +0200849 def new_vminstance(self, name, description, start, image_id, flavor_id, net_list, cloud_config=None, disk_list=None,
850 availability_zone_index=None, availability_zone_list=None):
tierno7edb6752016-03-21 17:37:52 +0100851 '''Adds a VM instance to VIM
852 Params:
853 start: indicates if VM must start or boot in pause mode. Ignored
854 image_id,flavor_id: iamge and flavor uuid
855 net_list: list of interfaces, each one is a dictionary with:
856 name:
857 net_id: network uuid to connect
858 vpci: virtual vcpi to assign, ignored because openstack lack #TODO
859 model: interface model, ignored #TODO
860 mac_address: used for SR-IOV ifaces #TODO for other types
861 use: 'data', 'bridge', 'mgmt'
862 type: 'virtual', 'PF', 'VF', 'VFnotShared'
863 vim_id: filled/added by this function
ahmadsaf853d452016-12-22 11:33:47 +0500864 floating_ip: True/False (or it can be None)
mirabal29356312017-07-27 12:21:22 +0200865 'cloud_config': (optional) dictionary with:
866 'key-pairs': (optional) list of strings with the public key to be inserted to the default user
867 'users': (optional) list of users to be inserted, each item is a dict with:
868 'name': (mandatory) user name,
869 'key-pairs': (optional) list of strings with the public key to be inserted to the user
870 'user-data': (optional) string is a text script to be passed directly to cloud-init
871 'config-files': (optional). List of files to be transferred. Each item is a dict with:
872 'dest': (mandatory) string with the destination absolute path
873 'encoding': (optional, by default text). Can be one of:
874 'b64', 'base64', 'gz', 'gz+b64', 'gz+base64', 'gzip+b64', 'gzip+base64'
875 'content' (mandatory): string with the content of the file
876 'permissions': (optional) string with file permissions, typically octal notation '0644'
877 'owner': (optional) file owner, string with the format 'owner:group'
878 'boot-data-drive': boolean to indicate if user-data must be passed using a boot drive (hard disk)
879 'disk_list': (optional) list with additional disks to the VM. Each item is a dict with:
880 'image_id': (optional). VIM id of an existing image. If not provided an empty disk must be mounted
881 'size': (mandatory) string with the size of the disk in GB
tierno5a3273c2017-08-29 11:43:46 +0200882 availability_zone_index: Index of availability_zone_list to use for this this VM. None if not AV required
883 availability_zone_list: list of availability zones given by user in the VNFD descriptor. Ignore if
884 availability_zone_index is None
tierno7edb6752016-03-21 17:37:52 +0100885 #TODO ip, security groups
tiernoae4a8d12016-07-08 12:30:39 +0200886 Returns the instance identifier
tierno7edb6752016-03-21 17:37:52 +0100887 '''
tiernofa51c202017-01-27 14:58:17 +0100888 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 +0100889 try:
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +0200890 server = None
tierno6e116232016-07-18 13:01:40 +0200891 metadata={}
tierno7edb6752016-03-21 17:37:52 +0100892 net_list_vim=[]
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +0200893 external_network=[] # list of external networks to be connected to instance, later on used to create floating_ip
894 no_secured_ports = [] # List of port-is with port-security disabled
tierno7edb6752016-03-21 17:37:52 +0100895 self._reload_connection()
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +0200896 metadata_vpci={} # For a specific neutron plugin
tiernob84cbdc2017-07-07 14:30:30 +0200897 block_device_mapping = None
tierno7edb6752016-03-21 17:37:52 +0100898 for net in net_list:
899 if not net.get("net_id"): #skip non connected iface
900 continue
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +0200901
902 port_dict={
903 "network_id": net["net_id"],
904 "name": net.get("name"),
905 "admin_state_up": True
906 }
907 if net["type"]=="virtual":
908 if "vpci" in net:
909 metadata_vpci[ net["net_id"] ] = [[ net["vpci"], "" ]]
910 elif net["type"]=="VF": # for VF
911 if "vpci" in net:
912 if "VF" not in metadata_vpci:
913 metadata_vpci["VF"]=[]
914 metadata_vpci["VF"].append([ net["vpci"], "" ])
915 port_dict["binding:vnic_type"]="direct"
kate721d79b2017-06-24 04:21:38 -0700916 ########## VIO specific Changes #######
917 if self.vim_type == "VIO":
918 #Need to create port with port_security_enabled = False and no-security-groups
919 port_dict["port_security_enabled"]=False
920 port_dict["provider_security_groups"]=[]
921 port_dict["security_groups"]=[]
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +0200922 else: #For PT
kate721d79b2017-06-24 04:21:38 -0700923 ########## VIO specific Changes #######
924 #Current VIO release does not support port with type 'direct-physical'
925 #So no need to create virtual port in case of PCI-device.
926 #Will update port_dict code when support gets added in next VIO release
927 if self.vim_type == "VIO":
928 raise vimconn.vimconnNotSupportedException("Current VIO release does not support full passthrough (PT)")
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +0200929 if "vpci" in net:
930 if "PF" not in metadata_vpci:
931 metadata_vpci["PF"]=[]
932 metadata_vpci["PF"].append([ net["vpci"], "" ])
933 port_dict["binding:vnic_type"]="direct-physical"
934 if not port_dict["name"]:
935 port_dict["name"]=name
936 if net.get("mac_address"):
937 port_dict["mac_address"]=net["mac_address"]
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +0200938 new_port = self.neutron.create_port({"port": port_dict })
939 net["mac_adress"] = new_port["port"]["mac_address"]
940 net["vim_id"] = new_port["port"]["id"]
tiernob84cbdc2017-07-07 14:30:30 +0200941 # if try to use a network without subnetwork, it will return a emtpy list
942 fixed_ips = new_port["port"].get("fixed_ips")
943 if fixed_ips:
944 net["ip"] = fixed_ips[0].get("ip_address")
945 else:
946 net["ip"] = None
montesmoreno994a29d2017-08-22 11:23:06 +0200947
948 port = {"port-id": new_port["port"]["id"]}
949 if float(self.nova.api_version.get_string()) >= 2.32:
950 port["tag"] = new_port["port"]["name"]
951 net_list_vim.append(port)
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +0200952
ahmadsaf853d452016-12-22 11:33:47 +0500953 if net.get('floating_ip', False):
tiernof8383b82017-01-18 15:49:48 +0100954 net['exit_on_floating_ip_error'] = True
ahmadsaf853d452016-12-22 11:33:47 +0500955 external_network.append(net)
tiernof8383b82017-01-18 15:49:48 +0100956 elif net['use'] == 'mgmt' and self.config.get('use_floating_ip'):
957 net['exit_on_floating_ip_error'] = False
958 external_network.append(net)
959
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +0200960 # If port security is disabled when the port has not yet been attached to the VM, then all vm traffic is dropped.
961 # As a workaround we wait until the VM is active and then disable the port-security
962 if net.get("port_security") == False:
963 no_secured_ports.append(new_port["port"]["id"])
964
tierno7edb6752016-03-21 17:37:52 +0100965 if metadata_vpci:
966 metadata = {"pci_assignement": json.dumps(metadata_vpci)}
tiernoafbced42016-07-23 01:43:53 +0200967 if len(metadata["pci_assignement"]) >255:
tierno6e116232016-07-18 13:01:40 +0200968 #limit the metadata size
969 #metadata["pci_assignement"] = metadata["pci_assignement"][0:255]
970 self.logger.warn("Metadata deleted since it exceeds the expected length (255) ")
971 metadata = {}
tierno7edb6752016-03-21 17:37:52 +0100972
tiernoae4a8d12016-07-08 12:30:39 +0200973 self.logger.debug("name '%s' image_id '%s'flavor_id '%s' net_list_vim '%s' description '%s' metadata %s",
974 name, image_id, flavor_id, str(net_list_vim), description, str(metadata))
tierno7edb6752016-03-21 17:37:52 +0100975
976 security_groups = self.config.get('security_groups')
977 if type(security_groups) is str:
978 security_groups = ( security_groups, )
tierno36c0b172017-01-12 18:32:28 +0100979 #cloud config
980 userdata=None
981 config_drive = None
tierno40e1bce2017-08-09 09:12:04 +0200982 userdata_list = []
tiernoa4e1a6e2016-08-31 14:19:40 +0200983 if isinstance(cloud_config, dict):
tierno36c0b172017-01-12 18:32:28 +0100984 if cloud_config.get("user-data"):
tierno40e1bce2017-08-09 09:12:04 +0200985 if isinstance(cloud_config["user-data"], str):
986 userdata_list.append(cloud_config["user-data"])
987 else:
988 for u in cloud_config["user-data"]:
989 userdata_list.append(u)
tierno36c0b172017-01-12 18:32:28 +0100990 if cloud_config.get("boot-data-drive") != None:
991 config_drive = cloud_config["boot-data-drive"]
992 if cloud_config.get("config-files") or cloud_config.get("users") or cloud_config.get("key-pairs"):
tierno36c0b172017-01-12 18:32:28 +0100993 userdata_dict={}
994 #default user
995 if cloud_config.get("key-pairs"):
996 userdata_dict["ssh-authorized-keys"] = cloud_config["key-pairs"]
997 userdata_dict["users"] = [{"default": None, "ssh-authorized-keys": cloud_config["key-pairs"] }]
998 if cloud_config.get("users"):
tierno01d0bf52017-01-25 14:27:20 +0100999 if "users" not in userdata_dict:
tierno36c0b172017-01-12 18:32:28 +01001000 userdata_dict["users"] = [ "default" ]
1001 for user in cloud_config["users"]:
1002 user_info = {
1003 "name" : user["name"],
1004 "sudo": "ALL = (ALL)NOPASSWD:ALL"
1005 }
1006 if "user-info" in user:
1007 user_info["gecos"] = user["user-info"]
1008 if user.get("key-pairs"):
1009 user_info["ssh-authorized-keys"] = user["key-pairs"]
1010 userdata_dict["users"].append(user_info)
1011
1012 if cloud_config.get("config-files"):
1013 userdata_dict["write_files"] = []
1014 for file in cloud_config["config-files"]:
1015 file_info = {
1016 "path" : file["dest"],
1017 "content": file["content"]
1018 }
1019 if file.get("encoding"):
1020 file_info["encoding"] = file["encoding"]
1021 if file.get("permissions"):
1022 file_info["permissions"] = file["permissions"]
1023 if file.get("owner"):
1024 file_info["owner"] = file["owner"]
1025 userdata_dict["write_files"].append(file_info)
tierno40e1bce2017-08-09 09:12:04 +02001026 userdata_list.append("#cloud-config\n" + yaml.safe_dump(userdata_dict, indent=4,
1027 default_flow_style=False))
1028 userdata = self._create_mimemultipart(userdata_list)
tiernoa4e1a6e2016-08-31 14:19:40 +02001029 self.logger.debug("userdata: %s", userdata)
1030 elif isinstance(cloud_config, str):
1031 userdata = cloud_config
montesmoreno0c8def02016-12-22 12:16:23 +00001032
1033 #Create additional volumes in case these are present in disk_list
montesmoreno0c8def02016-12-22 12:16:23 +00001034 base_disk_index = ord('b')
1035 if disk_list != None:
tiernob84cbdc2017-07-07 14:30:30 +02001036 block_device_mapping = {}
montesmoreno0c8def02016-12-22 12:16:23 +00001037 for disk in disk_list:
1038 if 'image_id' in disk:
1039 volume = self.cinder.volumes.create(size = disk['size'],name = name + '_vd' +
1040 chr(base_disk_index), imageRef = disk['image_id'])
1041 else:
1042 volume = self.cinder.volumes.create(size=disk['size'], name=name + '_vd' +
1043 chr(base_disk_index))
1044 block_device_mapping['_vd' + chr(base_disk_index)] = volume.id
1045 base_disk_index += 1
1046
1047 #wait until volumes are with status available
1048 keep_waiting = True
1049 elapsed_time = 0
1050 while keep_waiting and elapsed_time < volume_timeout:
1051 keep_waiting = False
1052 for volume_id in block_device_mapping.itervalues():
1053 if self.cinder.volumes.get(volume_id).status != 'available':
1054 keep_waiting = True
1055 if keep_waiting:
1056 time.sleep(1)
1057 elapsed_time += 1
1058
1059 #if we exceeded the timeout rollback
1060 if elapsed_time >= volume_timeout:
1061 #delete the volumes we just created
1062 for volume_id in block_device_mapping.itervalues():
1063 self.cinder.volumes.delete(volume_id)
1064
1065 #delete ports we just created
1066 for net_item in net_list_vim:
1067 if 'port-id' in net_item:
montesmorenocf227142017-01-12 12:24:21 +00001068 self.neutron.delete_port(net_item['port-id'])
montesmoreno0c8def02016-12-22 12:16:23 +00001069
1070 raise vimconn.vimconnException('Timeout creating volumes for instance ' + name,
1071 http_code=vimconn.HTTP_Request_Timeout)
mirabal29356312017-07-27 12:21:22 +02001072 # get availability Zone
tierno5a3273c2017-08-29 11:43:46 +02001073 vm_av_zone = self._get_vm_availability_zone(availability_zone_index, availability_zone_list)
montesmoreno0c8def02016-12-22 12:16:23 +00001074
mirabal29356312017-07-27 12:21:22 +02001075 self.logger.debug("nova.servers.create({}, {}, {}, nics={}, meta={}, security_groups={}, "
1076 "availability_zone={}, key_name={}, userdata={}, config_drive={}, "
1077 "block_device_mapping={})".format(name, image_id, flavor_id, net_list_vim, metadata,
1078 security_groups, vm_av_zone, self.config.get('keypair'),
1079 userdata, config_drive, block_device_mapping))
tierno7edb6752016-03-21 17:37:52 +01001080 server = self.nova.servers.create(name, image_id, flavor_id, nics=net_list_vim, meta=metadata,
montesmoreno0c8def02016-12-22 12:16:23 +00001081 security_groups=security_groups,
mirabal29356312017-07-27 12:21:22 +02001082 availability_zone=vm_av_zone,
montesmoreno0c8def02016-12-22 12:16:23 +00001083 key_name=self.config.get('keypair'),
1084 userdata=userdata,
tiernob84cbdc2017-07-07 14:30:30 +02001085 config_drive=config_drive,
1086 block_device_mapping=block_device_mapping
montesmoreno0c8def02016-12-22 12:16:23 +00001087 ) # , description=description)
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001088
1089 # Previously mentioned workaround to wait until the VM is active and then disable the port-security
1090 if no_secured_ports:
1091 self.__wait_for_vm(server.id, 'ACTIVE')
1092
1093 for port_id in no_secured_ports:
1094 try:
1095 self.neutron.update_port(port_id, {"port": {"port_security_enabled": False, "security_groups": None} })
1096
1097 except Exception as e:
1098 self.logger.error("It was not possible to disable port security for port {}".format(port_id))
1099 self.delete_vminstance(server.id)
1100 raise
1101
tiernoae4a8d12016-07-08 12:30:39 +02001102 #print "DONE :-)", server
ahmadsaf853d452016-12-22 11:33:47 +05001103 pool_id = None
1104 floating_ips = self.neutron.list_floatingips().get("floatingips", ())
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001105
1106 if external_network:
1107 self.__wait_for_vm(server.id, 'ACTIVE')
1108
ahmadsaf853d452016-12-22 11:33:47 +05001109 for floating_network in external_network:
tiernof8383b82017-01-18 15:49:48 +01001110 try:
tiernof8383b82017-01-18 15:49:48 +01001111 assigned = False
1112 while(assigned == False):
1113 if floating_ips:
1114 ip = floating_ips.pop(0)
1115 if not ip.get("port_id", False) and ip.get('tenant_id') == server.tenant_id:
1116 free_floating_ip = ip.get("floating_ip_address")
1117 try:
1118 fix_ip = floating_network.get('ip')
1119 server.add_floating_ip(free_floating_ip, fix_ip)
1120 assigned = True
1121 except Exception as e:
1122 raise vimconn.vimconnException(type(e).__name__ + ": Cannot create floating_ip "+ str(e), http_code=vimconn.HTTP_Conflict)
1123 else:
1124 #Find the external network
1125 external_nets = list()
1126 for net in self.neutron.list_networks()['networks']:
1127 if net['router:external']:
1128 external_nets.append(net)
1129
1130 if len(external_nets) == 0:
1131 raise vimconn.vimconnException("Cannot create floating_ip automatically since no external "
1132 "network is present",
1133 http_code=vimconn.HTTP_Conflict)
1134 if len(external_nets) > 1:
1135 raise vimconn.vimconnException("Cannot create floating_ip automatically since multiple "
1136 "external networks are present",
1137 http_code=vimconn.HTTP_Conflict)
1138
1139 pool_id = external_nets[0].get('id')
1140 param = {'floatingip': {'floating_network_id': pool_id, 'tenant_id': server.tenant_id}}
ahmadsaf853d452016-12-22 11:33:47 +05001141 try:
tiernof8383b82017-01-18 15:49:48 +01001142 #self.logger.debug("Creating floating IP")
1143 new_floating_ip = self.neutron.create_floatingip(param)
1144 free_floating_ip = new_floating_ip['floatingip']['floating_ip_address']
ahmadsaf853d452016-12-22 11:33:47 +05001145 fix_ip = floating_network.get('ip')
1146 server.add_floating_ip(free_floating_ip, fix_ip)
tiernof8383b82017-01-18 15:49:48 +01001147 assigned=True
ahmadsaf853d452016-12-22 11:33:47 +05001148 except Exception as e:
tiernof8383b82017-01-18 15:49:48 +01001149 raise vimconn.vimconnException(type(e).__name__ + ": Cannot assign floating_ip "+ str(e), http_code=vimconn.HTTP_Conflict)
1150 except Exception as e:
1151 if not floating_network['exit_on_floating_ip_error']:
1152 self.logger.warn("Cannot create floating_ip. %s", str(e))
1153 continue
tiernof8383b82017-01-18 15:49:48 +01001154 raise
montesmoreno2a1fc4e2017-01-09 16:46:04 +00001155
tiernoae4a8d12016-07-08 12:30:39 +02001156 return server.id
tierno7edb6752016-03-21 17:37:52 +01001157# except nvExceptions.NotFound as e:
1158# error_value=-vimconn.HTTP_Not_Found
1159# error_text= "vm instance %s not found" % vm_id
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001160# except TypeError as e:
1161# raise vimconn.vimconnException(type(e).__name__ + ": "+ str(e), http_code=vimconn.HTTP_Bad_Request)
1162
1163 except Exception as e:
montesmoreno2a1fc4e2017-01-09 16:46:04 +00001164 # delete the volumes we just created
tiernob84cbdc2017-07-07 14:30:30 +02001165 if block_device_mapping:
montesmoreno2a1fc4e2017-01-09 16:46:04 +00001166 for volume_id in block_device_mapping.itervalues():
1167 self.cinder.volumes.delete(volume_id)
1168
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001169 # Delete the VM
1170 if server != None:
1171 self.delete_vminstance(server.id)
1172 else:
1173 # delete ports we just created
1174 for net_item in net_list_vim:
1175 if 'port-id' in net_item:
1176 self.neutron.delete_port(net_item['port-id'])
1177
tiernoae4a8d12016-07-08 12:30:39 +02001178 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001179
tiernoae4a8d12016-07-08 12:30:39 +02001180 def get_vminstance(self,vm_id):
tierno7edb6752016-03-21 17:37:52 +01001181 '''Returns the VM instance information from VIM'''
tiernoae4a8d12016-07-08 12:30:39 +02001182 #self.logger.debug("Getting VM from VIM")
tierno7edb6752016-03-21 17:37:52 +01001183 try:
1184 self._reload_connection()
1185 server = self.nova.servers.find(id=vm_id)
1186 #TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
tiernoae4a8d12016-07-08 12:30:39 +02001187 return server.to_dict()
tierno8e995ce2016-09-22 08:13:00 +00001188 except (ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.NotFound, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001189 self._format_exception(e)
1190
1191 def get_vminstance_console(self,vm_id, console_type="vnc"):
tierno7edb6752016-03-21 17:37:52 +01001192 '''
1193 Get a console for the virtual machine
1194 Params:
1195 vm_id: uuid of the VM
1196 console_type, can be:
1197 "novnc" (by default), "xvpvnc" for VNC types,
1198 "rdp-html5" for RDP types, "spice-html5" for SPICE types
tiernoae4a8d12016-07-08 12:30:39 +02001199 Returns dict with the console parameters:
1200 protocol: ssh, ftp, http, https, ...
1201 server: usually ip address
1202 port: the http, ssh, ... port
1203 suffix: extra text, e.g. the http path and query string
tierno7edb6752016-03-21 17:37:52 +01001204 '''
tiernoae4a8d12016-07-08 12:30:39 +02001205 self.logger.debug("Getting VM CONSOLE from VIM")
tierno7edb6752016-03-21 17:37:52 +01001206 try:
1207 self._reload_connection()
1208 server = self.nova.servers.find(id=vm_id)
1209 if console_type == None or console_type == "novnc":
1210 console_dict = server.get_vnc_console("novnc")
1211 elif console_type == "xvpvnc":
1212 console_dict = server.get_vnc_console(console_type)
1213 elif console_type == "rdp-html5":
1214 console_dict = server.get_rdp_console(console_type)
1215 elif console_type == "spice-html5":
1216 console_dict = server.get_spice_console(console_type)
1217 else:
tiernoae4a8d12016-07-08 12:30:39 +02001218 raise vimconn.vimconnException("console type '{}' not allowed".format(console_type), http_code=vimconn.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001219
1220 console_dict1 = console_dict.get("console")
1221 if console_dict1:
1222 console_url = console_dict1.get("url")
1223 if console_url:
1224 #parse console_url
1225 protocol_index = console_url.find("//")
1226 suffix_index = console_url[protocol_index+2:].find("/") + protocol_index+2
1227 port_index = console_url[protocol_index+2:suffix_index].find(":") + protocol_index+2
1228 if protocol_index < 0 or port_index<0 or suffix_index<0:
1229 return -vimconn.HTTP_Internal_Server_Error, "Unexpected response from VIM"
1230 console_dict={"protocol": console_url[0:protocol_index],
1231 "server": console_url[protocol_index+2:port_index],
1232 "port": console_url[port_index:suffix_index],
1233 "suffix": console_url[suffix_index+1:]
1234 }
1235 protocol_index += 2
tiernoae4a8d12016-07-08 12:30:39 +02001236 return console_dict
1237 raise vimconn.vimconnUnexpectedResponse("Unexpected response from VIM")
tierno7edb6752016-03-21 17:37:52 +01001238
tierno8e995ce2016-09-22 08:13:00 +00001239 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.BadRequest, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001240 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001241
tiernoae4a8d12016-07-08 12:30:39 +02001242 def delete_vminstance(self, vm_id):
1243 '''Removes a VM instance from VIM. Returns the old identifier
tierno7edb6752016-03-21 17:37:52 +01001244 '''
tiernoae4a8d12016-07-08 12:30:39 +02001245 #print "osconnector: Getting VM from VIM"
tierno7edb6752016-03-21 17:37:52 +01001246 try:
1247 self._reload_connection()
1248 #delete VM ports attached to this networks before the virtual machine
1249 ports = self.neutron.list_ports(device_id=vm_id)
1250 for p in ports['ports']:
1251 try:
1252 self.neutron.delete_port(p["id"])
1253 except Exception as e:
tiernoae4a8d12016-07-08 12:30:39 +02001254 self.logger.error("Error deleting port: " + type(e).__name__ + ": "+ str(e))
montesmoreno0c8def02016-12-22 12:16:23 +00001255
1256 #commented because detaching the volumes makes the servers.delete not work properly ?!?
1257 #dettach volumes attached
1258 server = self.nova.servers.get(vm_id)
1259 volumes_attached_dict = server._info['os-extended-volumes:volumes_attached']
1260 #for volume in volumes_attached_dict:
1261 # self.cinder.volumes.detach(volume['id'])
1262
tierno7edb6752016-03-21 17:37:52 +01001263 self.nova.servers.delete(vm_id)
montesmoreno0c8def02016-12-22 12:16:23 +00001264
1265 #delete volumes.
1266 #Although having detached them should have them in active status
1267 #we ensure in this loop
1268 keep_waiting = True
1269 elapsed_time = 0
1270 while keep_waiting and elapsed_time < volume_timeout:
1271 keep_waiting = False
1272 for volume in volumes_attached_dict:
1273 if self.cinder.volumes.get(volume['id']).status != 'available':
1274 keep_waiting = True
1275 else:
1276 self.cinder.volumes.delete(volume['id'])
1277 if keep_waiting:
1278 time.sleep(1)
1279 elapsed_time += 1
1280
tiernoae4a8d12016-07-08 12:30:39 +02001281 return vm_id
tierno8e995ce2016-09-22 08:13:00 +00001282 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001283 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001284 #TODO insert exception vimconn.HTTP_Unauthorized
1285 #if reaching here is because an exception
tierno7edb6752016-03-21 17:37:52 +01001286
tiernoae4a8d12016-07-08 12:30:39 +02001287 def refresh_vms_status(self, vm_list):
1288 '''Get the status of the virtual machines and their interfaces/ports
1289 Params: the list of VM identifiers
1290 Returns a dictionary with:
1291 vm_id: #VIM id of this Virtual Machine
1292 status: #Mandatory. Text with one of:
1293 # DELETED (not found at vim)
1294 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
1295 # OTHER (Vim reported other status not understood)
1296 # ERROR (VIM indicates an ERROR status)
1297 # ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running),
1298 # CREATING (on building process), ERROR
1299 # ACTIVE:NoMgmtIP (Active but any of its interface has an IP address
1300 #
1301 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
1302 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
1303 interfaces:
1304 - vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
1305 mac_address: #Text format XX:XX:XX:XX:XX:XX
1306 vim_net_id: #network id where this interface is connected
1307 vim_interface_id: #interface/port VIM id
1308 ip_address: #null, or text with IPv4, IPv6 address
tierno867ffe92017-03-27 12:50:34 +02001309 compute_node: #identification of compute node where PF,VF interface is allocated
1310 pci: #PCI address of the NIC that hosts the PF,VF
1311 vlan: #physical VLAN used for VF
tierno7edb6752016-03-21 17:37:52 +01001312 '''
tiernoae4a8d12016-07-08 12:30:39 +02001313 vm_dict={}
1314 self.logger.debug("refresh_vms status: Getting tenant VM instance information from VIM")
1315 for vm_id in vm_list:
1316 vm={}
1317 try:
1318 vm_vim = self.get_vminstance(vm_id)
1319 if vm_vim['status'] in vmStatus2manoFormat:
1320 vm['status'] = vmStatus2manoFormat[ vm_vim['status'] ]
tierno7edb6752016-03-21 17:37:52 +01001321 else:
tiernoae4a8d12016-07-08 12:30:39 +02001322 vm['status'] = "OTHER"
1323 vm['error_msg'] = "VIM status reported " + vm_vim['status']
tierno8e995ce2016-09-22 08:13:00 +00001324 try:
1325 vm['vim_info'] = yaml.safe_dump(vm_vim, default_flow_style=True, width=256)
1326 except yaml.representer.RepresenterError:
1327 vm['vim_info'] = str(vm_vim)
tiernoae4a8d12016-07-08 12:30:39 +02001328 vm["interfaces"] = []
1329 if vm_vim.get('fault'):
1330 vm['error_msg'] = str(vm_vim['fault'])
1331 #get interfaces
tierno7edb6752016-03-21 17:37:52 +01001332 try:
tiernoae4a8d12016-07-08 12:30:39 +02001333 self._reload_connection()
1334 port_dict=self.neutron.list_ports(device_id=vm_id)
1335 for port in port_dict["ports"]:
1336 interface={}
tierno8e995ce2016-09-22 08:13:00 +00001337 try:
1338 interface['vim_info'] = yaml.safe_dump(port, default_flow_style=True, width=256)
1339 except yaml.representer.RepresenterError:
1340 interface['vim_info'] = str(port)
tiernoae4a8d12016-07-08 12:30:39 +02001341 interface["mac_address"] = port.get("mac_address")
1342 interface["vim_net_id"] = port["network_id"]
1343 interface["vim_interface_id"] = port["id"]
Mike Marchetti5b9da422017-05-02 15:35:47 -04001344 # check if OS-EXT-SRV-ATTR:host is there,
1345 # in case of non-admin credentials, it will be missing
1346 if vm_vim.get('OS-EXT-SRV-ATTR:host'):
1347 interface["compute_node"] = vm_vim['OS-EXT-SRV-ATTR:host']
tierno867ffe92017-03-27 12:50:34 +02001348 interface["pci"] = None
Mike Marchetti5b9da422017-05-02 15:35:47 -04001349
1350 # check if binding:profile is there,
1351 # in case of non-admin credentials, it will be missing
1352 if port.get('binding:profile'):
1353 if port['binding:profile'].get('pci_slot'):
1354 # TODO: At the moment sr-iov pci addresses are converted to PF pci addresses by setting the slot to 0x00
1355 # TODO: This is just a workaround valid for niantinc. Find a better way to do so
1356 # CHANGE DDDD:BB:SS.F to DDDD:BB:00.(F%2) assuming there are 2 ports per nic
1357 pci = port['binding:profile']['pci_slot']
1358 # interface["pci"] = pci[:-4] + "00." + str(int(pci[-1]) % 2)
1359 interface["pci"] = pci
tierno867ffe92017-03-27 12:50:34 +02001360 interface["vlan"] = None
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001361 #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 +01001362 network = self.neutron.show_network(port["network_id"])
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001363 if network['network'].get('provider:network_type') == 'vlan' and \
1364 port.get("binding:vnic_type") == "direct":
tierno867ffe92017-03-27 12:50:34 +02001365 interface["vlan"] = network['network'].get('provider:segmentation_id')
tiernoae4a8d12016-07-08 12:30:39 +02001366 ips=[]
1367 #look for floating ip address
1368 floating_ip_dict = self.neutron.list_floatingips(port_id=port["id"])
1369 if floating_ip_dict.get("floatingips"):
1370 ips.append(floating_ip_dict["floatingips"][0].get("floating_ip_address") )
tierno7edb6752016-03-21 17:37:52 +01001371
tiernoae4a8d12016-07-08 12:30:39 +02001372 for subnet in port["fixed_ips"]:
1373 ips.append(subnet["ip_address"])
1374 interface["ip_address"] = ";".join(ips)
1375 vm["interfaces"].append(interface)
1376 except Exception as e:
1377 self.logger.error("Error getting vm interface information " + type(e).__name__ + ": "+ str(e))
1378 except vimconn.vimconnNotFoundException as e:
1379 self.logger.error("Exception getting vm status: %s", str(e))
1380 vm['status'] = "DELETED"
1381 vm['error_msg'] = str(e)
1382 except vimconn.vimconnException as e:
1383 self.logger.error("Exception getting vm status: %s", str(e))
1384 vm['status'] = "VIM_ERROR"
1385 vm['error_msg'] = str(e)
1386 vm_dict[vm_id] = vm
1387 return vm_dict
tierno7edb6752016-03-21 17:37:52 +01001388
tiernoae4a8d12016-07-08 12:30:39 +02001389 def action_vminstance(self, vm_id, action_dict):
tierno7edb6752016-03-21 17:37:52 +01001390 '''Send and action over a VM instance from VIM
tiernoae4a8d12016-07-08 12:30:39 +02001391 Returns the vm_id if the action was successfully sent to the VIM'''
1392 self.logger.debug("Action over VM '%s': %s", vm_id, str(action_dict))
tierno7edb6752016-03-21 17:37:52 +01001393 try:
1394 self._reload_connection()
1395 server = self.nova.servers.find(id=vm_id)
1396 if "start" in action_dict:
1397 if action_dict["start"]=="rebuild":
1398 server.rebuild()
1399 else:
1400 if server.status=="PAUSED":
1401 server.unpause()
1402 elif server.status=="SUSPENDED":
1403 server.resume()
1404 elif server.status=="SHUTOFF":
1405 server.start()
1406 elif "pause" in action_dict:
1407 server.pause()
1408 elif "resume" in action_dict:
1409 server.resume()
1410 elif "shutoff" in action_dict or "shutdown" in action_dict:
1411 server.stop()
1412 elif "forceOff" in action_dict:
1413 server.stop() #TODO
1414 elif "terminate" in action_dict:
1415 server.delete()
1416 elif "createImage" in action_dict:
1417 server.create_image()
1418 #"path":path_schema,
1419 #"description":description_schema,
1420 #"name":name_schema,
1421 #"metadata":metadata_schema,
1422 #"imageRef": id_schema,
1423 #"disk": {"oneOf":[{"type": "null"}, {"type":"string"}] },
1424 elif "rebuild" in action_dict:
1425 server.rebuild(server.image['id'])
1426 elif "reboot" in action_dict:
1427 server.reboot() #reboot_type='SOFT'
1428 elif "console" in action_dict:
1429 console_type = action_dict["console"]
1430 if console_type == None or console_type == "novnc":
1431 console_dict = server.get_vnc_console("novnc")
1432 elif console_type == "xvpvnc":
1433 console_dict = server.get_vnc_console(console_type)
1434 elif console_type == "rdp-html5":
1435 console_dict = server.get_rdp_console(console_type)
1436 elif console_type == "spice-html5":
1437 console_dict = server.get_spice_console(console_type)
1438 else:
tiernoae4a8d12016-07-08 12:30:39 +02001439 raise vimconn.vimconnException("console type '{}' not allowed".format(console_type),
1440 http_code=vimconn.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001441 try:
1442 console_url = console_dict["console"]["url"]
1443 #parse console_url
1444 protocol_index = console_url.find("//")
1445 suffix_index = console_url[protocol_index+2:].find("/") + protocol_index+2
1446 port_index = console_url[protocol_index+2:suffix_index].find(":") + protocol_index+2
1447 if protocol_index < 0 or port_index<0 or suffix_index<0:
tiernoae4a8d12016-07-08 12:30:39 +02001448 raise vimconn.vimconnException("Unexpected response from VIM " + str(console_dict))
tierno7edb6752016-03-21 17:37:52 +01001449 console_dict2={"protocol": console_url[0:protocol_index],
1450 "server": console_url[protocol_index+2 : port_index],
1451 "port": int(console_url[port_index+1 : suffix_index]),
1452 "suffix": console_url[suffix_index+1:]
1453 }
tiernoae4a8d12016-07-08 12:30:39 +02001454 return console_dict2
1455 except Exception as e:
1456 raise vimconn.vimconnException("Unexpected response from VIM " + str(console_dict))
tierno7edb6752016-03-21 17:37:52 +01001457
tiernoae4a8d12016-07-08 12:30:39 +02001458 return vm_id
tierno8e995ce2016-09-22 08:13:00 +00001459 except (ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.NotFound, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001460 self._format_exception(e)
1461 #TODO insert exception vimconn.HTTP_Unauthorized
1462
kate721d79b2017-06-24 04:21:38 -07001463 ####### VIO Specific Changes #########
1464 def _genrate_vlanID(self):
1465 """
1466 Method to get unused vlanID
1467 Args:
1468 None
1469 Returns:
1470 vlanID
1471 """
1472 #Get used VLAN IDs
1473 usedVlanIDs = []
1474 networks = self.get_network_list()
1475 for net in networks:
1476 if net.get('provider:segmentation_id'):
1477 usedVlanIDs.append(net.get('provider:segmentation_id'))
1478 used_vlanIDs = set(usedVlanIDs)
1479
1480 #find unused VLAN ID
1481 for vlanID_range in self.config.get('dataplane_net_vlan_range'):
1482 try:
1483 start_vlanid , end_vlanid = map(int, vlanID_range.replace(" ", "").split("-"))
1484 for vlanID in xrange(start_vlanid, end_vlanid + 1):
1485 if vlanID not in used_vlanIDs:
1486 return vlanID
1487 except Exception as exp:
1488 raise vimconn.vimconnException("Exception {} occurred while generating VLAN ID.".format(exp))
1489 else:
1490 raise vimconn.vimconnConflictException("Unable to create the SRIOV VLAN network."\
1491 " All given Vlan IDs {} are in use.".format(self.config.get('dataplane_net_vlan_range')))
1492
1493
1494 def _validate_vlan_ranges(self, dataplane_net_vlan_range):
1495 """
1496 Method to validate user given vlanID ranges
1497 Args: None
1498 Returns: None
1499 """
1500 for vlanID_range in dataplane_net_vlan_range:
1501 vlan_range = vlanID_range.replace(" ", "")
1502 #validate format
1503 vlanID_pattern = r'(\d)*-(\d)*$'
1504 match_obj = re.match(vlanID_pattern, vlan_range)
1505 if not match_obj:
1506 raise vimconn.vimconnConflictException("Invalid dataplane_net_vlan_range {}.You must provide "\
1507 "'dataplane_net_vlan_range' in format [start_ID - end_ID].".format(vlanID_range))
1508
1509 start_vlanid , end_vlanid = map(int,vlan_range.split("-"))
1510 if start_vlanid <= 0 :
1511 raise vimconn.vimconnConflictException("Invalid dataplane_net_vlan_range {}."\
1512 "Start ID can not be zero. For VLAN "\
1513 "networks valid IDs are 1 to 4094 ".format(vlanID_range))
1514 if end_vlanid > 4094 :
1515 raise vimconn.vimconnConflictException("Invalid dataplane_net_vlan_range {}."\
1516 "End VLAN ID can not be greater than 4094. For VLAN "\
1517 "networks valid IDs are 1 to 4094 ".format(vlanID_range))
1518
1519 if start_vlanid > end_vlanid:
1520 raise vimconn.vimconnConflictException("Invalid dataplane_net_vlan_range {}."\
1521 "You must provide a 'dataplane_net_vlan_range' in format start_ID - end_ID and "\
1522 "start_ID < end_ID ".format(vlanID_range))
1523
tiernoae4a8d12016-07-08 12:30:39 +02001524#NOT USED FUNCTIONS
1525
1526 def new_external_port(self, port_data):
1527 #TODO openstack if needed
1528 '''Adds a external port to VIM'''
1529 '''Returns the port identifier'''
1530 return -vimconn.HTTP_Internal_Server_Error, "osconnector.new_external_port() not implemented"
1531
1532 def connect_port_network(self, port_id, network_id, admin=False):
1533 #TODO openstack if needed
1534 '''Connects a external port to a network'''
1535 '''Returns status code of the VIM response'''
1536 return -vimconn.HTTP_Internal_Server_Error, "osconnector.connect_port_network() not implemented"
1537
1538 def new_user(self, user_name, user_passwd, tenant_id=None):
1539 '''Adds a new user to openstack VIM'''
1540 '''Returns the user identifier'''
1541 self.logger.debug("osconnector: Adding a new user to VIM")
1542 try:
1543 self._reload_connection()
1544 user=self.keystone.users.create(user_name, user_passwd, tenant_id=tenant_id)
1545 #self.keystone.tenants.add_user(self.k_creds["username"], #role)
1546 return user.id
1547 except ksExceptions.ConnectionError as e:
1548 error_value=-vimconn.HTTP_Bad_Request
1549 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1550 except ksExceptions.ClientException as e: #TODO remove
tierno7edb6752016-03-21 17:37:52 +01001551 error_value=-vimconn.HTTP_Bad_Request
1552 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1553 #TODO insert exception vimconn.HTTP_Unauthorized
1554 #if reaching here is because an exception
1555 if self.debug:
tiernoae4a8d12016-07-08 12:30:39 +02001556 self.logger.debug("new_user " + error_text)
tierno7edb6752016-03-21 17:37:52 +01001557 return error_value, error_text
tiernoae4a8d12016-07-08 12:30:39 +02001558
1559 def delete_user(self, user_id):
1560 '''Delete a user from openstack VIM'''
1561 '''Returns the user identifier'''
1562 if self.debug:
1563 print "osconnector: Deleting a user from VIM"
1564 try:
1565 self._reload_connection()
1566 self.keystone.users.delete(user_id)
1567 return 1, user_id
1568 except ksExceptions.ConnectionError as e:
1569 error_value=-vimconn.HTTP_Bad_Request
1570 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1571 except ksExceptions.NotFound as e:
1572 error_value=-vimconn.HTTP_Not_Found
1573 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1574 except ksExceptions.ClientException as e: #TODO remove
1575 error_value=-vimconn.HTTP_Bad_Request
1576 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1577 #TODO insert exception vimconn.HTTP_Unauthorized
1578 #if reaching here is because an exception
1579 if self.debug:
1580 print "delete_tenant " + error_text
1581 return error_value, error_text
1582
tierno7edb6752016-03-21 17:37:52 +01001583 def get_hosts_info(self):
1584 '''Get the information of deployed hosts
1585 Returns the hosts content'''
1586 if self.debug:
1587 print "osconnector: Getting Host info from VIM"
1588 try:
1589 h_list=[]
1590 self._reload_connection()
1591 hypervisors = self.nova.hypervisors.list()
1592 for hype in hypervisors:
1593 h_list.append( hype.to_dict() )
1594 return 1, {"hosts":h_list}
1595 except nvExceptions.NotFound as e:
1596 error_value=-vimconn.HTTP_Not_Found
1597 error_text= (str(e) if len(e.args)==0 else str(e.args[0]))
1598 except (ksExceptions.ClientException, nvExceptions.ClientException) as e:
1599 error_value=-vimconn.HTTP_Bad_Request
1600 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1601 #TODO insert exception vimconn.HTTP_Unauthorized
1602 #if reaching here is because an exception
1603 if self.debug:
1604 print "get_hosts_info " + error_text
1605 return error_value, error_text
1606
1607 def get_hosts(self, vim_tenant):
1608 '''Get the hosts and deployed instances
1609 Returns the hosts content'''
1610 r, hype_dict = self.get_hosts_info()
1611 if r<0:
1612 return r, hype_dict
1613 hypervisors = hype_dict["hosts"]
1614 try:
1615 servers = self.nova.servers.list()
1616 for hype in hypervisors:
1617 for server in servers:
1618 if server.to_dict()['OS-EXT-SRV-ATTR:hypervisor_hostname']==hype['hypervisor_hostname']:
1619 if 'vm' in hype:
1620 hype['vm'].append(server.id)
1621 else:
1622 hype['vm'] = [server.id]
1623 return 1, hype_dict
1624 except nvExceptions.NotFound as e:
1625 error_value=-vimconn.HTTP_Not_Found
1626 error_text= (str(e) if len(e.args)==0 else str(e.args[0]))
1627 except (ksExceptions.ClientException, nvExceptions.ClientException) as e:
1628 error_value=-vimconn.HTTP_Bad_Request
1629 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1630 #TODO insert exception vimconn.HTTP_Unauthorized
1631 #if reaching here is because an exception
1632 if self.debug:
1633 print "get_hosts " + error_text
1634 return error_value, error_text
1635
tierno7edb6752016-03-21 17:37:52 +01001636
tierno7edb6752016-03-21 17:37:52 +01001637