blob: 3eb2990be69bc8fbedc4ccde58682c12ec304c7a [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
tierno7edb6752016-03-21 17:37:52 +010039
tiernob5cef372017-06-19 15:52:22 +020040from novaclient import client as nClient, exceptions as nvExceptions
41from keystoneauth1.identity import v2, v3
42from keystoneauth1 import session
tierno7edb6752016-03-21 17:37:52 +010043import keystoneclient.exceptions as ksExceptions
tiernof716aea2017-06-21 18:01:40 +020044import keystoneclient.v3.client as ksClient_v3
45import keystoneclient.v2_0.client as ksClient_v2
tiernob5cef372017-06-19 15:52:22 +020046from glanceclient import client as glClient
tierno7edb6752016-03-21 17:37:52 +010047import glanceclient.client as gl1Client
48import glanceclient.exc as gl1Exceptions
tiernob5cef372017-06-19 15:52:22 +020049from cinderclient import client as cClient
tierno7edb6752016-03-21 17:37:52 +010050from httplib import HTTPException
tiernob5cef372017-06-19 15:52:22 +020051from neutronclient.neutron import client as neClient
tierno7edb6752016-03-21 17:37:52 +010052from neutronclient.common import exceptions as neExceptions
53from requests.exceptions import ConnectionError
tierno40e1bce2017-08-09 09:12:04 +020054from email.mime.multipart import MIMEMultipart
55from email.mime.text import MIMEText
tierno7edb6752016-03-21 17:37:52 +010056
tierno40e1bce2017-08-09 09:12:04 +020057
58"""contain the openstack virtual machine status to openmano status"""
tierno7edb6752016-03-21 17:37:52 +010059vmStatus2manoFormat={'ACTIVE':'ACTIVE',
60 'PAUSED':'PAUSED',
61 'SUSPENDED': 'SUSPENDED',
62 'SHUTOFF':'INACTIVE',
63 'BUILD':'BUILD',
64 'ERROR':'ERROR','DELETED':'DELETED'
65 }
66netStatus2manoFormat={'ACTIVE':'ACTIVE','PAUSED':'PAUSED','INACTIVE':'INACTIVE','BUILD':'BUILD','ERROR':'ERROR','DELETED':'DELETED'
67 }
68
montesmoreno0c8def02016-12-22 12:16:23 +000069#global var to have a timeout creating and deleting volumes
70volume_timeout = 60
garciadeblas05a1a612017-07-23 20:26:28 +020071server_timeout = 300
montesmoreno0c8def02016-12-22 12:16:23 +000072
tierno7edb6752016-03-21 17:37:52 +010073class vimconnector(vimconn.vimconnector):
tiernob3d36742017-03-03 23:51:05 +010074 def __init__(self, uuid, name, tenant_id, tenant_name, url, url_admin=None, user=None, passwd=None,
75 log_level=None, config={}, persistent_info={}):
ahmadsa96af9f42017-01-31 16:17:14 +050076 '''using common constructor parameters. In this case
tierno7edb6752016-03-21 17:37:52 +010077 'url' is the keystone authorization url,
78 'url_admin' is not use
79 '''
tiernof716aea2017-06-21 18:01:40 +020080 api_version = config.get('APIversion')
81 if api_version and api_version not in ('v3.3', 'v2.0', '2', '3'):
tiernob5cef372017-06-19 15:52:22 +020082 raise vimconn.vimconnException("Invalid value '{}' for config:APIversion. "
tiernof716aea2017-06-21 18:01:40 +020083 "Allowed values are 'v3.3', 'v2.0', '2' or '3'".format(api_version))
tiernob5cef372017-06-19 15:52:22 +020084 vimconn.vimconnector.__init__(self, uuid, name, tenant_id, tenant_name, url, url_admin, user, passwd, log_level,
85 config)
tiernob3d36742017-03-03 23:51:05 +010086
tiernob5cef372017-06-19 15:52:22 +020087 self.insecure = self.config.get("insecure", False)
tierno7edb6752016-03-21 17:37:52 +010088 if not url:
89 raise TypeError, 'url param can not be NoneType'
tiernob5cef372017-06-19 15:52:22 +020090 self.persistent_info = persistent_info
mirabal29356312017-07-27 12:21:22 +020091 self.availability_zone = persistent_info.get('availability_zone', None)
tiernob5cef372017-06-19 15:52:22 +020092 self.session = persistent_info.get('session', {'reload_client': True})
93 self.nova = self.session.get('nova')
94 self.neutron = self.session.get('neutron')
95 self.cinder = self.session.get('cinder')
96 self.glance = self.session.get('glance')
tiernob39d49e2017-08-02 14:02:15 +020097 self.glancev1 = self.session.get('glancev1')
tiernof716aea2017-06-21 18:01:40 +020098 self.keystone = self.session.get('keystone')
99 self.api_version3 = self.session.get('api_version3')
montesmoreno0c8def02016-12-22 12:16:23 +0000100
tierno73ad9e42016-09-12 18:11:11 +0200101 self.logger = logging.getLogger('openmano.vim.openstack')
tiernofe789902016-09-29 14:20:44 +0000102 if log_level:
103 self.logger.setLevel( getattr(logging, log_level) )
tiernof716aea2017-06-21 18:01:40 +0200104
105 def __getitem__(self, index):
106 """Get individuals parameters.
107 Throw KeyError"""
108 if index == 'project_domain_id':
109 return self.config.get("project_domain_id")
110 elif index == 'user_domain_id':
111 return self.config.get("user_domain_id")
112 else:
tierno76a3c312017-06-29 16:42:15 +0200113 return vimconn.vimconnector.__getitem__(self, index)
tiernof716aea2017-06-21 18:01:40 +0200114
115 def __setitem__(self, index, value):
116 """Set individuals parameters and it is marked as dirty so to force connection reload.
117 Throw KeyError"""
118 if index == 'project_domain_id':
119 self.config["project_domain_id"] = value
120 elif index == 'user_domain_id':
121 self.config["user_domain_id"] = value
122 else:
123 vimconn.vimconnector.__setitem__(self, index, value)
tiernob5cef372017-06-19 15:52:22 +0200124 self.session['reload_client'] = True
tiernof716aea2017-06-21 18:01:40 +0200125
tierno7edb6752016-03-21 17:37:52 +0100126 def _reload_connection(self):
127 '''Called before any operation, it check if credentials has changed
128 Throw keystoneclient.apiclient.exceptions.AuthorizationFailure
129 '''
130 #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 +0200131 if self.session['reload_client']:
tiernof716aea2017-06-21 18:01:40 +0200132 if self.config.get('APIversion'):
133 self.api_version3 = self.config['APIversion'] == 'v3.3' or self.config['APIversion'] == '3'
134 else: # get from ending auth_url that end with v3 or with v2.0
135 self.api_version3 = self.url.split("/")[-1] == "v3"
136 self.session['api_version3'] = self.api_version3
137 if self.api_version3:
138 auth = v3.Password(auth_url=self.url,
tiernob5cef372017-06-19 15:52:22 +0200139 username=self.user,
140 password=self.passwd,
141 project_name=self.tenant_name,
142 project_id=self.tenant_id,
143 project_domain_id=self.config.get('project_domain_id', 'default'),
144 user_domain_id=self.config.get('user_domain_id', 'default'))
ahmadsa95baa272016-11-30 09:14:11 +0500145 else:
tiernof716aea2017-06-21 18:01:40 +0200146 auth = v2.Password(auth_url=self.url,
tiernob5cef372017-06-19 15:52:22 +0200147 username=self.user,
148 password=self.passwd,
149 tenant_name=self.tenant_name,
150 tenant_id=self.tenant_id)
151 sess = session.Session(auth=auth, verify=not self.insecure)
tiernof716aea2017-06-21 18:01:40 +0200152 if self.api_version3:
153 self.keystone = ksClient_v3.Client(session=sess)
154 else:
155 self.keystone = ksClient_v2.Client(session=sess)
156 self.session['keystone'] = self.keystone
montesmoreno9317d302017-08-16 12:48:23 +0200157 # In order to enable microversion functionality an explicit microversion must be specified in 'config'.
158 # This implementation approach is due to the warning message in
159 # https://developer.openstack.org/api-guide/compute/microversions.html
160 # where it is stated that microversion backwards compatibility is not guaranteed and clients should
161 # always require an specific microversion.
162 # To be able to use 'device role tagging' functionality define 'microversion: 2.32' in datacenter config
163 version = self.config.get("microversion")
164 if not version:
165 version = "2.1"
166 self.nova = self.session['nova'] = nClient.Client(str(version), session=sess)
tiernob5cef372017-06-19 15:52:22 +0200167 self.neutron = self.session['neutron'] = neClient.Client('2.0', session=sess)
168 self.cinder = self.session['cinder'] = cClient.Client(2, session=sess)
169 self.glance = self.session['glance'] = glClient.Client(2, session=sess)
tiernob39d49e2017-08-02 14:02:15 +0200170 self.glancev1 = self.session['glancev1'] = glClient.Client('1', session=sess)
tiernob5cef372017-06-19 15:52:22 +0200171 self.session['reload_client'] = False
172 self.persistent_info['session'] = self.session
mirabal29356312017-07-27 12:21:22 +0200173 # add availablity zone info inside self.persistent_info
174 self._set_availablity_zones()
175 self.persistent_info['availability_zone'] = self.availability_zone
ahmadsa95baa272016-11-30 09:14:11 +0500176
tierno7edb6752016-03-21 17:37:52 +0100177 def __net_os2mano(self, net_list_dict):
178 '''Transform the net openstack format to mano format
179 net_list_dict can be a list of dict or a single dict'''
180 if type(net_list_dict) is dict:
181 net_list_=(net_list_dict,)
182 elif type(net_list_dict) is list:
183 net_list_=net_list_dict
184 else:
185 raise TypeError("param net_list_dict must be a list or a dictionary")
186 for net in net_list_:
187 if net.get('provider:network_type') == "vlan":
188 net['type']='data'
189 else:
190 net['type']='bridge'
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +0200191
tiernoae4a8d12016-07-08 12:30:39 +0200192 def _format_exception(self, exception):
193 '''Transform a keystone, nova, neutron exception into a vimconn exception'''
194 if isinstance(exception, (HTTPException, gl1Exceptions.HTTPException, gl1Exceptions.CommunicationError,
tierno8e995ce2016-09-22 08:13:00 +0000195 ConnectionError, ksExceptions.ConnectionError, neExceptions.ConnectionFailed
196 )):
tiernoae4a8d12016-07-08 12:30:39 +0200197 raise vimconn.vimconnConnectionException(type(exception).__name__ + ": " + str(exception))
198 elif isinstance(exception, (nvExceptions.ClientException, ksExceptions.ClientException,
199 neExceptions.NeutronException, nvExceptions.BadRequest)):
200 raise vimconn.vimconnUnexpectedResponse(type(exception).__name__ + ": " + str(exception))
201 elif isinstance(exception, (neExceptions.NetworkNotFoundClient, nvExceptions.NotFound)):
202 raise vimconn.vimconnNotFoundException(type(exception).__name__ + ": " + str(exception))
203 elif isinstance(exception, nvExceptions.Conflict):
204 raise vimconn.vimconnConflictException(type(exception).__name__ + ": " + str(exception))
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +0200205 elif isinstance(exception, vimconn.vimconnException):
206 raise
tiernof716aea2017-06-21 18:01:40 +0200207 else: # ()
tiernob84cbdc2017-07-07 14:30:30 +0200208 self.logger.error("General Exception " + str(exception), exc_info=True)
tiernoae4a8d12016-07-08 12:30:39 +0200209 raise vimconn.vimconnConnectionException(type(exception).__name__ + ": " + str(exception))
210
211 def get_tenant_list(self, filter_dict={}):
212 '''Obtain tenants of VIM
213 filter_dict can contain the following keys:
214 name: filter by tenant name
215 id: filter by tenant uuid/id
216 <other VIM specific>
217 Returns the tenant list of dictionaries: [{'name':'<name>, 'id':'<id>, ...}, ...]
218 '''
ahmadsa95baa272016-11-30 09:14:11 +0500219 self.logger.debug("Getting tenants from VIM filter: '%s'", str(filter_dict))
tiernoae4a8d12016-07-08 12:30:39 +0200220 try:
221 self._reload_connection()
tiernof716aea2017-06-21 18:01:40 +0200222 if self.api_version3:
223 project_class_list = self.keystone.projects.list(name=filter_dict.get("name"))
ahmadsa95baa272016-11-30 09:14:11 +0500224 else:
tiernof716aea2017-06-21 18:01:40 +0200225 project_class_list = self.keystone.tenants.findall(**filter_dict)
ahmadsa95baa272016-11-30 09:14:11 +0500226 project_list=[]
227 for project in project_class_list:
tiernof716aea2017-06-21 18:01:40 +0200228 if filter_dict.get('id') and filter_dict["id"] != project.id:
229 continue
ahmadsa95baa272016-11-30 09:14:11 +0500230 project_list.append(project.to_dict())
231 return project_list
tiernof716aea2017-06-21 18:01:40 +0200232 except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200233 self._format_exception(e)
234
235 def new_tenant(self, tenant_name, tenant_description):
236 '''Adds a new tenant to openstack VIM. Returns the tenant identifier'''
237 self.logger.debug("Adding a new tenant name: %s", tenant_name)
238 try:
239 self._reload_connection()
tiernof716aea2017-06-21 18:01:40 +0200240 if self.api_version3:
241 project = self.keystone.projects.create(tenant_name, self.config.get("project_domain_id", "default"),
242 description=tenant_description, is_domain=False)
ahmadsa95baa272016-11-30 09:14:11 +0500243 else:
tiernof716aea2017-06-21 18:01:40 +0200244 project = self.keystone.tenants.create(tenant_name, tenant_description)
ahmadsa95baa272016-11-30 09:14:11 +0500245 return project.id
tierno8e995ce2016-09-22 08:13:00 +0000246 except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200247 self._format_exception(e)
248
249 def delete_tenant(self, tenant_id):
250 '''Delete a tenant from openstack VIM. Returns the old tenant identifier'''
251 self.logger.debug("Deleting tenant %s from VIM", tenant_id)
252 try:
253 self._reload_connection()
tiernof716aea2017-06-21 18:01:40 +0200254 if self.api_version3:
ahmadsa95baa272016-11-30 09:14:11 +0500255 self.keystone.projects.delete(tenant_id)
256 else:
257 self.keystone.tenants.delete(tenant_id)
tiernoae4a8d12016-07-08 12:30:39 +0200258 return tenant_id
tierno8e995ce2016-09-22 08:13:00 +0000259 except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200260 self._format_exception(e)
ahmadsa95baa272016-11-30 09:14:11 +0500261
garciadeblas9f8456e2016-09-05 05:02:59 +0200262 def new_network(self,net_name, net_type, ip_profile=None, shared=False, vlan=None):
tiernoae4a8d12016-07-08 12:30:39 +0200263 '''Adds a tenant network to VIM. Returns the network identifier'''
264 self.logger.debug("Adding a new network to VIM name '%s', type '%s'", net_name, net_type)
garciadeblasedca7b32016-09-29 14:01:52 +0000265 #self.logger.debug(">>>>>>>>>>>>>>>>>> IP profile %s", str(ip_profile))
tierno7edb6752016-03-21 17:37:52 +0100266 try:
garciadeblasedca7b32016-09-29 14:01:52 +0000267 new_net = None
tierno7edb6752016-03-21 17:37:52 +0100268 self._reload_connection()
269 network_dict = {'name': net_name, 'admin_state_up': True}
270 if net_type=="data" or net_type=="ptp":
271 if self.config.get('dataplane_physical_net') == None:
tiernoae4a8d12016-07-08 12:30:39 +0200272 raise vimconn.vimconnConflictException("You must provide a 'dataplane_physical_net' at config value before creating sriov network")
tierno7edb6752016-03-21 17:37:52 +0100273 network_dict["provider:physical_network"] = self.config['dataplane_physical_net'] #"physnet_sriov" #TODO physical
274 network_dict["provider:network_type"] = "vlan"
275 if vlan!=None:
276 network_dict["provider:network_type"] = vlan
tiernoae4a8d12016-07-08 12:30:39 +0200277 network_dict["shared"]=shared
tierno7edb6752016-03-21 17:37:52 +0100278 new_net=self.neutron.create_network({'network':network_dict})
279 #print new_net
garciadeblas9f8456e2016-09-05 05:02:59 +0200280 #create subnetwork, even if there is no profile
281 if not ip_profile:
282 ip_profile = {}
283 if 'subnet_address' not in ip_profile:
garciadeblas2299e3b2017-01-26 14:35:55 +0000284 #Fake subnet is required
285 subnet_rand = random.randint(0, 255)
286 ip_profile['subnet_address'] = "192.168.{}.0/24".format(subnet_rand)
garciadeblas9f8456e2016-09-05 05:02:59 +0200287 if 'ip_version' not in ip_profile:
288 ip_profile['ip_version'] = "IPv4"
tiernoa1fb4462017-06-30 12:25:50 +0200289 subnet = {"name":net_name+"-subnet",
tierno7edb6752016-03-21 17:37:52 +0100290 "network_id": new_net["network"]["id"],
garciadeblas9f8456e2016-09-05 05:02:59 +0200291 "ip_version": 4 if ip_profile['ip_version']=="IPv4" else 6,
292 "cidr": ip_profile['subnet_address']
tierno7edb6752016-03-21 17:37:52 +0100293 }
tiernoa1fb4462017-06-30 12:25:50 +0200294 # Gateway should be set to None if not needed. Otherwise openstack assigns one by default
295 subnet['gateway_ip'] = ip_profile.get('gateway_address')
garciadeblasedca7b32016-09-29 14:01:52 +0000296 if ip_profile.get('dns_address'):
tierno455612d2017-05-30 16:40:10 +0200297 subnet['dns_nameservers'] = ip_profile['dns_address'].split(";")
garciadeblas9f8456e2016-09-05 05:02:59 +0200298 if 'dhcp_enabled' in ip_profile:
299 subnet['enable_dhcp'] = False if ip_profile['dhcp_enabled']=="false" else True
300 if 'dhcp_start_address' in ip_profile:
tiernoa1fb4462017-06-30 12:25:50 +0200301 subnet['allocation_pools'] = []
garciadeblas9f8456e2016-09-05 05:02:59 +0200302 subnet['allocation_pools'].append(dict())
303 subnet['allocation_pools'][0]['start'] = ip_profile['dhcp_start_address']
304 if 'dhcp_count' in ip_profile:
305 #parts = ip_profile['dhcp_start_address'].split('.')
306 #ip_int = (int(parts[0]) << 24) + (int(parts[1]) << 16) + (int(parts[2]) << 8) + int(parts[3])
307 ip_int = int(netaddr.IPAddress(ip_profile['dhcp_start_address']))
garciadeblas21d795b2016-09-29 17:31:46 +0200308 ip_int += ip_profile['dhcp_count'] - 1
garciadeblas9f8456e2016-09-05 05:02:59 +0200309 ip_str = str(netaddr.IPAddress(ip_int))
310 subnet['allocation_pools'][0]['end'] = ip_str
garciadeblasedca7b32016-09-29 14:01:52 +0000311 #self.logger.debug(">>>>>>>>>>>>>>>>>> Subnet: %s", str(subnet))
tierno7edb6752016-03-21 17:37:52 +0100312 self.neutron.create_subnet({"subnet": subnet} )
tiernoae4a8d12016-07-08 12:30:39 +0200313 return new_net["network"]["id"]
tierno8e995ce2016-09-22 08:13:00 +0000314 except (neExceptions.ConnectionFailed, ksExceptions.ClientException, neExceptions.NeutronException, ConnectionError) as e:
garciadeblasedca7b32016-09-29 14:01:52 +0000315 if new_net:
316 self.neutron.delete_network(new_net['network']['id'])
tiernoae4a8d12016-07-08 12:30:39 +0200317 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100318
319 def get_network_list(self, filter_dict={}):
320 '''Obtain tenant networks of VIM
321 Filter_dict can be:
322 name: network name
323 id: network uuid
324 shared: boolean
325 tenant_id: tenant
326 admin_state_up: boolean
327 status: 'ACTIVE'
328 Returns the network list of dictionaries
329 '''
tiernoae4a8d12016-07-08 12:30:39 +0200330 self.logger.debug("Getting network from VIM filter: '%s'", str(filter_dict))
tierno7edb6752016-03-21 17:37:52 +0100331 try:
332 self._reload_connection()
tiernof716aea2017-06-21 18:01:40 +0200333 if self.api_version3 and "tenant_id" in filter_dict:
334 filter_dict['project_id'] = filter_dict.pop('tenant_id') #TODO check
tierno7edb6752016-03-21 17:37:52 +0100335 net_dict=self.neutron.list_networks(**filter_dict)
336 net_list=net_dict["networks"]
337 self.__net_os2mano(net_list)
tiernoae4a8d12016-07-08 12:30:39 +0200338 return net_list
tierno8e995ce2016-09-22 08:13:00 +0000339 except (neExceptions.ConnectionFailed, ksExceptions.ClientException, neExceptions.NeutronException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200340 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100341
tiernoae4a8d12016-07-08 12:30:39 +0200342 def get_network(self, net_id):
343 '''Obtain details of network from VIM
344 Returns the network information from a network id'''
345 self.logger.debug(" Getting tenant network %s from VIM", net_id)
tierno7edb6752016-03-21 17:37:52 +0100346 filter_dict={"id": net_id}
tiernoae4a8d12016-07-08 12:30:39 +0200347 net_list = self.get_network_list(filter_dict)
tierno7edb6752016-03-21 17:37:52 +0100348 if len(net_list)==0:
tiernoae4a8d12016-07-08 12:30:39 +0200349 raise vimconn.vimconnNotFoundException("Network '{}' not found".format(net_id))
tierno7edb6752016-03-21 17:37:52 +0100350 elif len(net_list)>1:
tiernoae4a8d12016-07-08 12:30:39 +0200351 raise vimconn.vimconnConflictException("Found more than one network with this criteria")
tierno7edb6752016-03-21 17:37:52 +0100352 net = net_list[0]
353 subnets=[]
354 for subnet_id in net.get("subnets", () ):
355 try:
356 subnet = self.neutron.show_subnet(subnet_id)
357 except Exception as e:
tiernoae4a8d12016-07-08 12:30:39 +0200358 self.logger.error("osconnector.get_network(): Error getting subnet %s %s" % (net_id, str(e)))
359 subnet = {"id": subnet_id, "fault": str(e)}
tierno7edb6752016-03-21 17:37:52 +0100360 subnets.append(subnet)
361 net["subnets"] = subnets
Pablo Montes Moreno51e553b2017-03-23 16:39:12 +0100362 net["encapsulation"] = net.get('provider:network_type')
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100363 net["segmentation_id"] = net.get('provider:segmentation_id')
tiernoae4a8d12016-07-08 12:30:39 +0200364 return net
tierno7edb6752016-03-21 17:37:52 +0100365
tiernoae4a8d12016-07-08 12:30:39 +0200366 def delete_network(self, net_id):
367 '''Deletes a tenant network from VIM. Returns the old network identifier'''
368 self.logger.debug("Deleting network '%s' from VIM", net_id)
tierno7edb6752016-03-21 17:37:52 +0100369 try:
370 self._reload_connection()
371 #delete VM ports attached to this networks before the network
372 ports = self.neutron.list_ports(network_id=net_id)
373 for p in ports['ports']:
374 try:
375 self.neutron.delete_port(p["id"])
376 except Exception as e:
tiernoae4a8d12016-07-08 12:30:39 +0200377 self.logger.error("Error deleting port %s: %s", p["id"], str(e))
tierno7edb6752016-03-21 17:37:52 +0100378 self.neutron.delete_network(net_id)
tiernoae4a8d12016-07-08 12:30:39 +0200379 return net_id
380 except (neExceptions.ConnectionFailed, neExceptions.NetworkNotFoundClient, neExceptions.NeutronException,
tierno8e995ce2016-09-22 08:13:00 +0000381 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 refresh_nets_status(self, net_list):
385 '''Get the status of the networks
386 Params: the list of network identifiers
387 Returns a dictionary with:
388 net_id: #VIM id of this network
389 status: #Mandatory. Text with one of:
390 # DELETED (not found at vim)
391 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
392 # OTHER (Vim reported other status not understood)
393 # ERROR (VIM indicates an ERROR status)
394 # ACTIVE, INACTIVE, DOWN (admin down),
395 # BUILD (on building process)
396 #
397 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
398 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
399
400 '''
401 net_dict={}
402 for net_id in net_list:
403 net = {}
404 try:
405 net_vim = self.get_network(net_id)
406 if net_vim['status'] in netStatus2manoFormat:
407 net["status"] = netStatus2manoFormat[ net_vim['status'] ]
408 else:
409 net["status"] = "OTHER"
410 net["error_msg"] = "VIM status reported " + net_vim['status']
411
tierno8e995ce2016-09-22 08:13:00 +0000412 if net['status'] == "ACTIVE" and not net_vim['admin_state_up']:
tiernoae4a8d12016-07-08 12:30:39 +0200413 net['status'] = 'DOWN'
tierno8e995ce2016-09-22 08:13:00 +0000414 try:
415 net['vim_info'] = yaml.safe_dump(net_vim, default_flow_style=True, width=256)
416 except yaml.representer.RepresenterError:
417 net['vim_info'] = str(net_vim)
tiernoae4a8d12016-07-08 12:30:39 +0200418 if net_vim.get('fault'): #TODO
419 net['error_msg'] = str(net_vim['fault'])
420 except vimconn.vimconnNotFoundException as e:
421 self.logger.error("Exception getting net status: %s", str(e))
422 net['status'] = "DELETED"
423 net['error_msg'] = str(e)
424 except vimconn.vimconnException as e:
425 self.logger.error("Exception getting net status: %s", str(e))
426 net['status'] = "VIM_ERROR"
427 net['error_msg'] = str(e)
428 net_dict[net_id] = net
429 return net_dict
430
431 def get_flavor(self, flavor_id):
432 '''Obtain flavor details from the VIM. Returns the flavor dict details'''
433 self.logger.debug("Getting flavor '%s'", flavor_id)
tierno7edb6752016-03-21 17:37:52 +0100434 try:
435 self._reload_connection()
436 flavor = self.nova.flavors.find(id=flavor_id)
437 #TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
tiernoae4a8d12016-07-08 12:30:39 +0200438 return flavor.to_dict()
tierno8e995ce2016-09-22 08:13:00 +0000439 except (nvExceptions.NotFound, nvExceptions.ClientException, ksExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200440 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100441
tiernocf157a82017-01-30 14:07:06 +0100442 def get_flavor_id_from_data(self, flavor_dict):
443 """Obtain flavor id that match the flavor description
444 Returns the flavor_id or raises a vimconnNotFoundException
tiernoe26fc7a2017-05-30 14:43:03 +0200445 flavor_dict: contains the required ram, vcpus, disk
446 If 'use_existing_flavors' is set to True at config, the closer flavor that provides same or more ram, vcpus
447 and disk is returned. Otherwise a flavor with exactly same ram, vcpus and disk is returned or a
448 vimconnNotFoundException is raised
tiernocf157a82017-01-30 14:07:06 +0100449 """
tiernoe26fc7a2017-05-30 14:43:03 +0200450 exact_match = False if self.config.get('use_existing_flavors') else True
tiernocf157a82017-01-30 14:07:06 +0100451 try:
452 self._reload_connection()
tiernoe26fc7a2017-05-30 14:43:03 +0200453 flavor_candidate_id = None
454 flavor_candidate_data = (10000, 10000, 10000)
455 flavor_target = (flavor_dict["ram"], flavor_dict["vcpus"], flavor_dict["disk"])
456 # numa=None
457 numas = flavor_dict.get("extended", {}).get("numas")
tiernocf157a82017-01-30 14:07:06 +0100458 if numas:
459 #TODO
460 raise vimconn.vimconnNotFoundException("Flavor with EPA still not implemted")
461 # if len(numas) > 1:
462 # raise vimconn.vimconnNotFoundException("Cannot find any flavor with more than one numa")
463 # numa=numas[0]
464 # numas = extended.get("numas")
465 for flavor in self.nova.flavors.list():
466 epa = flavor.get_keys()
467 if epa:
468 continue
tiernoe26fc7a2017-05-30 14:43:03 +0200469 # TODO
470 flavor_data = (flavor.ram, flavor.vcpus, flavor.disk)
471 if flavor_data == flavor_target:
472 return flavor.id
473 elif not exact_match and flavor_target < flavor_data < flavor_candidate_data:
474 flavor_candidate_id = flavor.id
475 flavor_candidate_data = flavor_data
476 if not exact_match and flavor_candidate_id:
477 return flavor_candidate_id
tiernocf157a82017-01-30 14:07:06 +0100478 raise vimconn.vimconnNotFoundException("Cannot find any flavor matching '{}'".format(str(flavor_dict)))
479 except (nvExceptions.NotFound, nvExceptions.ClientException, ksExceptions.ClientException, ConnectionError) as e:
480 self._format_exception(e)
481
482
tiernoae4a8d12016-07-08 12:30:39 +0200483 def new_flavor(self, flavor_data, change_name_if_used=True):
tierno7edb6752016-03-21 17:37:52 +0100484 '''Adds a tenant flavor to openstack VIM
tiernoae4a8d12016-07-08 12:30:39 +0200485 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 +0100486 Returns the flavor identifier
487 '''
tiernoae4a8d12016-07-08 12:30:39 +0200488 self.logger.debug("Adding flavor '%s'", str(flavor_data))
tierno7edb6752016-03-21 17:37:52 +0100489 retry=0
tiernoae4a8d12016-07-08 12:30:39 +0200490 max_retries=3
tierno7edb6752016-03-21 17:37:52 +0100491 name_suffix = 0
tiernoae4a8d12016-07-08 12:30:39 +0200492 name=flavor_data['name']
493 while retry<max_retries:
tierno7edb6752016-03-21 17:37:52 +0100494 retry+=1
495 try:
496 self._reload_connection()
497 if change_name_if_used:
498 #get used names
499 fl_names=[]
500 fl=self.nova.flavors.list()
501 for f in fl:
502 fl_names.append(f.name)
503 while name in fl_names:
504 name_suffix += 1
tiernoae4a8d12016-07-08 12:30:39 +0200505 name = flavor_data['name']+"-" + str(name_suffix)
tierno7edb6752016-03-21 17:37:52 +0100506
tiernoae4a8d12016-07-08 12:30:39 +0200507 ram = flavor_data.get('ram',64)
508 vcpus = flavor_data.get('vcpus',1)
tierno7edb6752016-03-21 17:37:52 +0100509 numa_properties=None
510
tiernoae4a8d12016-07-08 12:30:39 +0200511 extended = flavor_data.get("extended")
tierno7edb6752016-03-21 17:37:52 +0100512 if extended:
513 numas=extended.get("numas")
514 if numas:
515 numa_nodes = len(numas)
516 if numa_nodes > 1:
517 return -1, "Can not add flavor with more than one numa"
518 numa_properties = {"hw:numa_nodes":str(numa_nodes)}
519 numa_properties["hw:mem_page_size"] = "large"
520 numa_properties["hw:cpu_policy"] = "dedicated"
521 numa_properties["hw:numa_mempolicy"] = "strict"
522 for numa in numas:
523 #overwrite ram and vcpus
524 ram = numa['memory']*1024
Pablo Montes Morenoea1d6232017-05-24 11:33:24 +0200525 #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 +0100526 if 'paired-threads' in numa:
527 vcpus = numa['paired-threads']*2
Pablo Montes Morenoea1d6232017-05-24 11:33:24 +0200528 #cpu_thread_policy "require" implies that the compute node must have an STM architecture
529 numa_properties["hw:cpu_thread_policy"] = "require"
530 numa_properties["hw:cpu_policy"] = "dedicated"
tierno7edb6752016-03-21 17:37:52 +0100531 elif 'cores' in numa:
532 vcpus = numa['cores']
Pablo Montes Morenoea1d6232017-05-24 11:33:24 +0200533 # cpu_thread_policy "prefer" implies that the host must not have an SMT architecture, or a non-SMT architecture will be emulated
534 numa_properties["hw:cpu_thread_policy"] = "isolate"
535 numa_properties["hw:cpu_policy"] = "dedicated"
tierno7edb6752016-03-21 17:37:52 +0100536 elif 'threads' in numa:
537 vcpus = numa['threads']
Pablo Montes Morenoea1d6232017-05-24 11:33:24 +0200538 # cpu_thread_policy "prefer" implies that the host may or may not have an SMT architecture
539 numa_properties["hw:cpu_thread_policy"] = "prefer"
540 numa_properties["hw:cpu_policy"] = "dedicated"
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +0200541 # for interface in numa.get("interfaces",() ):
542 # if interface["dedicated"]=="yes":
543 # raise vimconn.vimconnException("Passthrough interfaces are not supported for the openstack connector", http_code=vimconn.HTTP_Service_Unavailable)
544 # #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 +0100545
546 #create flavor
547 new_flavor=self.nova.flavors.create(name,
548 ram,
549 vcpus,
tiernoae4a8d12016-07-08 12:30:39 +0200550 flavor_data.get('disk',1),
551 is_public=flavor_data.get('is_public', True)
tierno7edb6752016-03-21 17:37:52 +0100552 )
553 #add metadata
554 if numa_properties:
555 new_flavor.set_keys(numa_properties)
tiernoae4a8d12016-07-08 12:30:39 +0200556 return new_flavor.id
tierno7edb6752016-03-21 17:37:52 +0100557 except nvExceptions.Conflict as e:
tiernoae4a8d12016-07-08 12:30:39 +0200558 if change_name_if_used and retry < max_retries:
tierno7edb6752016-03-21 17:37:52 +0100559 continue
tiernoae4a8d12016-07-08 12:30:39 +0200560 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100561 #except nvExceptions.BadRequest as e:
562 except (ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200563 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100564
tiernoae4a8d12016-07-08 12:30:39 +0200565 def delete_flavor(self,flavor_id):
566 '''Deletes a tenant flavor from openstack VIM. Returns the old flavor_id
tierno7edb6752016-03-21 17:37:52 +0100567 '''
tiernoae4a8d12016-07-08 12:30:39 +0200568 try:
569 self._reload_connection()
570 self.nova.flavors.delete(flavor_id)
571 return flavor_id
572 #except nvExceptions.BadRequest as e:
tierno8e995ce2016-09-22 08:13:00 +0000573 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200574 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100575
tiernoae4a8d12016-07-08 12:30:39 +0200576 def new_image(self,image_dict):
tierno7edb6752016-03-21 17:37:52 +0100577 '''
tiernoae4a8d12016-07-08 12:30:39 +0200578 Adds a tenant image to VIM. imge_dict is a dictionary with:
579 name: name
580 disk_format: qcow2, vhd, vmdk, raw (by default), ...
581 location: path or URI
582 public: "yes" or "no"
583 metadata: metadata of the image
584 Returns the image_id
tierno7edb6752016-03-21 17:37:52 +0100585 '''
tiernoae4a8d12016-07-08 12:30:39 +0200586 retry=0
587 max_retries=3
588 while retry<max_retries:
tierno7edb6752016-03-21 17:37:52 +0100589 retry+=1
590 try:
591 self._reload_connection()
592 #determine format http://docs.openstack.org/developer/glance/formats.html
593 if "disk_format" in image_dict:
594 disk_format=image_dict["disk_format"]
garciadeblas14480452017-01-10 13:08:07 +0100595 else: #autodiscover based on extension
tierno7edb6752016-03-21 17:37:52 +0100596 if image_dict['location'][-6:]==".qcow2":
597 disk_format="qcow2"
598 elif image_dict['location'][-4:]==".vhd":
599 disk_format="vhd"
600 elif image_dict['location'][-5:]==".vmdk":
601 disk_format="vmdk"
602 elif image_dict['location'][-4:]==".vdi":
603 disk_format="vdi"
604 elif image_dict['location'][-4:]==".iso":
605 disk_format="iso"
606 elif image_dict['location'][-4:]==".aki":
607 disk_format="aki"
608 elif image_dict['location'][-4:]==".ari":
609 disk_format="ari"
610 elif image_dict['location'][-4:]==".ami":
611 disk_format="ami"
612 else:
613 disk_format="raw"
tiernoae4a8d12016-07-08 12:30:39 +0200614 self.logger.debug("new_image: '%s' loading from '%s'", image_dict['name'], image_dict['location'])
tierno7edb6752016-03-21 17:37:52 +0100615 if image_dict['location'][0:4]=="http":
tiernob39d49e2017-08-02 14:02:15 +0200616 new_image = self.glancev1.images.create(name=image_dict['name'], is_public=image_dict.get('public',"yes")=="yes",
tierno7edb6752016-03-21 17:37:52 +0100617 container_format="bare", location=image_dict['location'], disk_format=disk_format)
618 else: #local path
619 with open(image_dict['location']) as fimage:
tiernob39d49e2017-08-02 14:02:15 +0200620 new_image = self.glancev1.images.create(name=image_dict['name'], is_public=image_dict.get('public',"yes")=="yes",
tierno7edb6752016-03-21 17:37:52 +0100621 container_format="bare", data=fimage, disk_format=disk_format)
622 #insert metadata. We cannot use 'new_image.properties.setdefault'
623 #because nova and glance are "INDEPENDENT" and we are using nova for reading metadata
624 new_image_nova=self.nova.images.find(id=new_image.id)
625 new_image_nova.metadata.setdefault('location',image_dict['location'])
626 metadata_to_load = image_dict.get('metadata')
627 if metadata_to_load:
628 for k,v in yaml.load(metadata_to_load).iteritems():
629 new_image_nova.metadata.setdefault(k,v)
tiernoae4a8d12016-07-08 12:30:39 +0200630 return new_image.id
631 except (nvExceptions.Conflict, ksExceptions.ClientException, nvExceptions.ClientException) as e:
632 self._format_exception(e)
tierno8e995ce2016-09-22 08:13:00 +0000633 except (HTTPException, gl1Exceptions.HTTPException, gl1Exceptions.CommunicationError, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200634 if retry==max_retries:
635 continue
636 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100637 except IOError as e: #can not open the file
tiernoae4a8d12016-07-08 12:30:39 +0200638 raise vimconn.vimconnConnectionException(type(e).__name__ + ": " + str(e)+ " for " + image_dict['location'],
639 http_code=vimconn.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100640
tiernoae4a8d12016-07-08 12:30:39 +0200641 def delete_image(self, image_id):
642 '''Deletes a tenant image from openstack VIM. Returns the old id
tierno7edb6752016-03-21 17:37:52 +0100643 '''
tiernoae4a8d12016-07-08 12:30:39 +0200644 try:
645 self._reload_connection()
646 self.nova.images.delete(image_id)
647 return image_id
tierno8e995ce2016-09-22 08:13:00 +0000648 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e: #TODO remove
tiernoae4a8d12016-07-08 12:30:39 +0200649 self._format_exception(e)
650
651 def get_image_id_from_path(self, path):
garciadeblasb69fa9f2016-09-28 12:04:10 +0200652 '''Get the image id from image path in the VIM database. Returns the image_id'''
tiernoae4a8d12016-07-08 12:30:39 +0200653 try:
654 self._reload_connection()
655 images = self.nova.images.list()
656 for image in images:
657 if image.metadata.get("location")==path:
658 return image.id
659 raise vimconn.vimconnNotFoundException("image with location '{}' not found".format( path))
tierno8e995ce2016-09-22 08:13:00 +0000660 except (ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200661 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100662
garciadeblasb69fa9f2016-09-28 12:04:10 +0200663 def get_image_list(self, filter_dict={}):
664 '''Obtain tenant images from VIM
665 Filter_dict can be:
666 id: image id
667 name: image name
668 checksum: image checksum
669 Returns the image list of dictionaries:
670 [{<the fields at Filter_dict plus some VIM specific>}, ...]
671 List can be empty
672 '''
673 self.logger.debug("Getting image list from VIM filter: '%s'", str(filter_dict))
674 try:
675 self._reload_connection()
676 filter_dict_os=filter_dict.copy()
677 #First we filter by the available filter fields: name, id. The others are removed.
678 filter_dict_os.pop('checksum',None)
679 image_list=self.nova.images.findall(**filter_dict_os)
680 if len(image_list)==0:
681 return []
682 #Then we filter by the rest of filter fields: checksum
683 filtered_list = []
684 for image in image_list:
tierno4540ea52017-01-18 17:44:32 +0100685 image_class=self.glance.images.get(image.id)
686 if 'checksum' not in filter_dict or image_class['checksum']==filter_dict.get('checksum'):
687 filtered_list.append(image_class.copy())
garciadeblasb69fa9f2016-09-28 12:04:10 +0200688 return filtered_list
689 except (ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e:
690 self._format_exception(e)
691
tierno40e1bce2017-08-09 09:12:04 +0200692 @staticmethod
693 def _create_mimemultipart(content_list):
694 """Creates a MIMEmultipart text combining the content_list
695 :param content_list: list of text scripts to be combined
696 :return: str of the created MIMEmultipart. If the list is empty returns None, if the list contains only one
697 element MIMEmultipart is not created and this content is returned
698 """
699 if not content_list:
700 return None
701 elif len(content_list) == 1:
702 return content_list[0]
703 combined_message = MIMEMultipart()
704 for content in content_list:
705 if content.startswith('#include'):
706 format = 'text/x-include-url'
707 elif content.startswith('#include-once'):
708 format = 'text/x-include-once-url'
709 elif content.startswith('#!'):
710 format = 'text/x-shellscript'
711 elif content.startswith('#cloud-config'):
712 format = 'text/cloud-config'
713 elif content.startswith('#cloud-config-archive'):
714 format = 'text/cloud-config-archive'
715 elif content.startswith('#upstart-job'):
716 format = 'text/upstart-job'
717 elif content.startswith('#part-handler'):
718 format = 'text/part-handler'
719 elif content.startswith('#cloud-boothook'):
720 format = 'text/cloud-boothook'
721 else: # by default
722 format = 'text/x-shellscript'
723 sub_message = MIMEText(content, format, sys.getdefaultencoding())
724 combined_message.attach(sub_message)
725 return combined_message.as_string()
726
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +0200727 def __wait_for_vm(self, vm_id, status):
728 """wait until vm is in the desired status and return True.
729 If the VM gets in ERROR status, return false.
730 If the timeout is reached generate an exception"""
731 elapsed_time = 0
732 while elapsed_time < server_timeout:
733 vm_status = self.nova.servers.get(vm_id).status
734 if vm_status == status:
735 return True
736 if vm_status == 'ERROR':
737 return False
738 time.sleep(1)
739 elapsed_time += 1
740
741 # if we exceeded the timeout rollback
742 if elapsed_time >= server_timeout:
743 raise vimconn.vimconnException('Timeout waiting for instance ' + vm_id + ' to get ' + status,
744 http_code=vimconn.HTTP_Request_Timeout)
745
mirabal29356312017-07-27 12:21:22 +0200746 def _get_openstack_availablity_zones(self):
747 """
748 Get from openstack availability zones available
749 :return:
750 """
751 try:
752 openstack_availability_zone = self.nova.availability_zones.list()
753 openstack_availability_zone = [str(zone.zoneName) for zone in openstack_availability_zone
754 if zone.zoneName != 'internal']
755 return openstack_availability_zone
756 except Exception as e:
757 return None
758
759 def _set_availablity_zones(self):
760 """
761 Set vim availablity zone
762 :return:
763 """
764
765 if 'availability_zone' in self.config:
766 vim_availability_zones = self.config.get('availability_zone')
767 if isinstance(vim_availability_zones, str):
768 self.availability_zone = [vim_availability_zones]
769 elif isinstance(vim_availability_zones, list):
770 self.availability_zone = vim_availability_zones
771 else:
772 self.availability_zone = self._get_openstack_availablity_zones()
773
tierno5a3273c2017-08-29 11:43:46 +0200774 def _get_vm_availability_zone(self, availability_zone_index, availability_zone_list):
mirabal29356312017-07-27 12:21:22 +0200775 """
tierno5a3273c2017-08-29 11:43:46 +0200776 Return thge availability zone to be used by the created VM.
777 :return: The VIM availability zone to be used or None
mirabal29356312017-07-27 12:21:22 +0200778 """
tierno5a3273c2017-08-29 11:43:46 +0200779 if availability_zone_index is None:
780 if not self.config.get('availability_zone'):
781 return None
782 elif isinstance(self.config.get('availability_zone'), str):
783 return self.config['availability_zone']
784 else:
785 # TODO consider using a different parameter at config for default AV and AV list match
786 return self.config['availability_zone'][0]
mirabal29356312017-07-27 12:21:22 +0200787
tierno5a3273c2017-08-29 11:43:46 +0200788 vim_availability_zones = self.availability_zone
789 # check if VIM offer enough availability zones describe in the VNFD
790 if vim_availability_zones and len(availability_zone_list) <= len(vim_availability_zones):
791 # check if all the names of NFV AV match VIM AV names
792 match_by_index = False
793 for av in availability_zone_list:
794 if av not in vim_availability_zones:
795 match_by_index = True
796 break
797 if match_by_index:
798 return vim_availability_zones[availability_zone_index]
799 else:
800 return availability_zone_list[availability_zone_index]
mirabal29356312017-07-27 12:21:22 +0200801 else:
tierno5a3273c2017-08-29 11:43:46 +0200802 raise vimconn.vimconnConflictException("No enough availability zones at VIM for this deployment")
mirabal29356312017-07-27 12:21:22 +0200803
tierno5a3273c2017-08-29 11:43:46 +0200804 def new_vminstance(self, name, description, start, image_id, flavor_id, net_list, cloud_config=None, disk_list=None,
805 availability_zone_index=None, availability_zone_list=None):
tierno7edb6752016-03-21 17:37:52 +0100806 '''Adds a VM instance to VIM
807 Params:
808 start: indicates if VM must start or boot in pause mode. Ignored
809 image_id,flavor_id: iamge and flavor uuid
810 net_list: list of interfaces, each one is a dictionary with:
811 name:
812 net_id: network uuid to connect
813 vpci: virtual vcpi to assign, ignored because openstack lack #TODO
814 model: interface model, ignored #TODO
815 mac_address: used for SR-IOV ifaces #TODO for other types
816 use: 'data', 'bridge', 'mgmt'
817 type: 'virtual', 'PF', 'VF', 'VFnotShared'
818 vim_id: filled/added by this function
ahmadsaf853d452016-12-22 11:33:47 +0500819 floating_ip: True/False (or it can be None)
mirabal29356312017-07-27 12:21:22 +0200820 'cloud_config': (optional) dictionary with:
821 'key-pairs': (optional) list of strings with the public key to be inserted to the default user
822 'users': (optional) list of users to be inserted, each item is a dict with:
823 'name': (mandatory) user name,
824 'key-pairs': (optional) list of strings with the public key to be inserted to the user
825 'user-data': (optional) string is a text script to be passed directly to cloud-init
826 'config-files': (optional). List of files to be transferred. Each item is a dict with:
827 'dest': (mandatory) string with the destination absolute path
828 'encoding': (optional, by default text). Can be one of:
829 'b64', 'base64', 'gz', 'gz+b64', 'gz+base64', 'gzip+b64', 'gzip+base64'
830 'content' (mandatory): string with the content of the file
831 'permissions': (optional) string with file permissions, typically octal notation '0644'
832 'owner': (optional) file owner, string with the format 'owner:group'
833 'boot-data-drive': boolean to indicate if user-data must be passed using a boot drive (hard disk)
834 'disk_list': (optional) list with additional disks to the VM. Each item is a dict with:
835 'image_id': (optional). VIM id of an existing image. If not provided an empty disk must be mounted
836 'size': (mandatory) string with the size of the disk in GB
tierno5a3273c2017-08-29 11:43:46 +0200837 availability_zone_index: Index of availability_zone_list to use for this this VM. None if not AV required
838 availability_zone_list: list of availability zones given by user in the VNFD descriptor. Ignore if
839 availability_zone_index is None
tierno7edb6752016-03-21 17:37:52 +0100840 #TODO ip, security groups
tiernoae4a8d12016-07-08 12:30:39 +0200841 Returns the instance identifier
tierno7edb6752016-03-21 17:37:52 +0100842 '''
tiernofa51c202017-01-27 14:58:17 +0100843 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 +0100844 try:
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +0200845 server = None
tierno6e116232016-07-18 13:01:40 +0200846 metadata={}
tierno7edb6752016-03-21 17:37:52 +0100847 net_list_vim=[]
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +0200848 external_network=[] # list of external networks to be connected to instance, later on used to create floating_ip
849 no_secured_ports = [] # List of port-is with port-security disabled
tierno7edb6752016-03-21 17:37:52 +0100850 self._reload_connection()
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +0200851 metadata_vpci={} # For a specific neutron plugin
tiernob84cbdc2017-07-07 14:30:30 +0200852 block_device_mapping = None
tierno7edb6752016-03-21 17:37:52 +0100853 for net in net_list:
854 if not net.get("net_id"): #skip non connected iface
855 continue
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +0200856
857 port_dict={
858 "network_id": net["net_id"],
859 "name": net.get("name"),
860 "admin_state_up": True
861 }
862 if net["type"]=="virtual":
863 if "vpci" in net:
864 metadata_vpci[ net["net_id"] ] = [[ net["vpci"], "" ]]
865 elif net["type"]=="VF": # for VF
866 if "vpci" in net:
867 if "VF" not in metadata_vpci:
868 metadata_vpci["VF"]=[]
869 metadata_vpci["VF"].append([ net["vpci"], "" ])
870 port_dict["binding:vnic_type"]="direct"
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +0200871 else: # For PT
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +0200872 if "vpci" in net:
873 if "PF" not in metadata_vpci:
874 metadata_vpci["PF"]=[]
875 metadata_vpci["PF"].append([ net["vpci"], "" ])
876 port_dict["binding:vnic_type"]="direct-physical"
877 if not port_dict["name"]:
878 port_dict["name"]=name
879 if net.get("mac_address"):
880 port_dict["mac_address"]=net["mac_address"]
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +0200881 new_port = self.neutron.create_port({"port": port_dict })
882 net["mac_adress"] = new_port["port"]["mac_address"]
883 net["vim_id"] = new_port["port"]["id"]
tiernob84cbdc2017-07-07 14:30:30 +0200884 # if try to use a network without subnetwork, it will return a emtpy list
885 fixed_ips = new_port["port"].get("fixed_ips")
886 if fixed_ips:
887 net["ip"] = fixed_ips[0].get("ip_address")
888 else:
889 net["ip"] = None
montesmoreno994a29d2017-08-22 11:23:06 +0200890
891 port = {"port-id": new_port["port"]["id"]}
892 if float(self.nova.api_version.get_string()) >= 2.32:
893 port["tag"] = new_port["port"]["name"]
894 net_list_vim.append(port)
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +0200895
ahmadsaf853d452016-12-22 11:33:47 +0500896 if net.get('floating_ip', False):
tiernof8383b82017-01-18 15:49:48 +0100897 net['exit_on_floating_ip_error'] = True
ahmadsaf853d452016-12-22 11:33:47 +0500898 external_network.append(net)
tiernof8383b82017-01-18 15:49:48 +0100899 elif net['use'] == 'mgmt' and self.config.get('use_floating_ip'):
900 net['exit_on_floating_ip_error'] = False
901 external_network.append(net)
902
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +0200903 # If port security is disabled when the port has not yet been attached to the VM, then all vm traffic is dropped.
904 # As a workaround we wait until the VM is active and then disable the port-security
905 if net.get("port_security") == False:
906 no_secured_ports.append(new_port["port"]["id"])
907
tierno7edb6752016-03-21 17:37:52 +0100908 if metadata_vpci:
909 metadata = {"pci_assignement": json.dumps(metadata_vpci)}
tiernoafbced42016-07-23 01:43:53 +0200910 if len(metadata["pci_assignement"]) >255:
tierno6e116232016-07-18 13:01:40 +0200911 #limit the metadata size
912 #metadata["pci_assignement"] = metadata["pci_assignement"][0:255]
913 self.logger.warn("Metadata deleted since it exceeds the expected length (255) ")
914 metadata = {}
tierno7edb6752016-03-21 17:37:52 +0100915
tiernoae4a8d12016-07-08 12:30:39 +0200916 self.logger.debug("name '%s' image_id '%s'flavor_id '%s' net_list_vim '%s' description '%s' metadata %s",
917 name, image_id, flavor_id, str(net_list_vim), description, str(metadata))
tierno7edb6752016-03-21 17:37:52 +0100918
919 security_groups = self.config.get('security_groups')
920 if type(security_groups) is str:
921 security_groups = ( security_groups, )
tierno36c0b172017-01-12 18:32:28 +0100922 #cloud config
923 userdata=None
924 config_drive = None
tierno40e1bce2017-08-09 09:12:04 +0200925 userdata_list = []
tiernoa4e1a6e2016-08-31 14:19:40 +0200926 if isinstance(cloud_config, dict):
tierno36c0b172017-01-12 18:32:28 +0100927 if cloud_config.get("user-data"):
tierno40e1bce2017-08-09 09:12:04 +0200928 if isinstance(cloud_config["user-data"], str):
929 userdata_list.append(cloud_config["user-data"])
930 else:
931 for u in cloud_config["user-data"]:
932 userdata_list.append(u)
tierno36c0b172017-01-12 18:32:28 +0100933 if cloud_config.get("boot-data-drive") != None:
934 config_drive = cloud_config["boot-data-drive"]
935 if cloud_config.get("config-files") or cloud_config.get("users") or cloud_config.get("key-pairs"):
tierno36c0b172017-01-12 18:32:28 +0100936 userdata_dict={}
937 #default user
938 if cloud_config.get("key-pairs"):
939 userdata_dict["ssh-authorized-keys"] = cloud_config["key-pairs"]
940 userdata_dict["users"] = [{"default": None, "ssh-authorized-keys": cloud_config["key-pairs"] }]
941 if cloud_config.get("users"):
tierno01d0bf52017-01-25 14:27:20 +0100942 if "users" not in userdata_dict:
tierno36c0b172017-01-12 18:32:28 +0100943 userdata_dict["users"] = [ "default" ]
944 for user in cloud_config["users"]:
945 user_info = {
946 "name" : user["name"],
947 "sudo": "ALL = (ALL)NOPASSWD:ALL"
948 }
949 if "user-info" in user:
950 user_info["gecos"] = user["user-info"]
951 if user.get("key-pairs"):
952 user_info["ssh-authorized-keys"] = user["key-pairs"]
953 userdata_dict["users"].append(user_info)
954
955 if cloud_config.get("config-files"):
956 userdata_dict["write_files"] = []
957 for file in cloud_config["config-files"]:
958 file_info = {
959 "path" : file["dest"],
960 "content": file["content"]
961 }
962 if file.get("encoding"):
963 file_info["encoding"] = file["encoding"]
964 if file.get("permissions"):
965 file_info["permissions"] = file["permissions"]
966 if file.get("owner"):
967 file_info["owner"] = file["owner"]
968 userdata_dict["write_files"].append(file_info)
tierno40e1bce2017-08-09 09:12:04 +0200969 userdata_list.append("#cloud-config\n" + yaml.safe_dump(userdata_dict, indent=4,
970 default_flow_style=False))
971 userdata = self._create_mimemultipart(userdata_list)
tiernoa4e1a6e2016-08-31 14:19:40 +0200972 self.logger.debug("userdata: %s", userdata)
973 elif isinstance(cloud_config, str):
974 userdata = cloud_config
montesmoreno0c8def02016-12-22 12:16:23 +0000975
976 #Create additional volumes in case these are present in disk_list
montesmoreno0c8def02016-12-22 12:16:23 +0000977 base_disk_index = ord('b')
978 if disk_list != None:
tiernob84cbdc2017-07-07 14:30:30 +0200979 block_device_mapping = {}
montesmoreno0c8def02016-12-22 12:16:23 +0000980 for disk in disk_list:
981 if 'image_id' in disk:
982 volume = self.cinder.volumes.create(size = disk['size'],name = name + '_vd' +
983 chr(base_disk_index), imageRef = disk['image_id'])
984 else:
985 volume = self.cinder.volumes.create(size=disk['size'], name=name + '_vd' +
986 chr(base_disk_index))
987 block_device_mapping['_vd' + chr(base_disk_index)] = volume.id
988 base_disk_index += 1
989
990 #wait until volumes are with status available
991 keep_waiting = True
992 elapsed_time = 0
993 while keep_waiting and elapsed_time < volume_timeout:
994 keep_waiting = False
995 for volume_id in block_device_mapping.itervalues():
996 if self.cinder.volumes.get(volume_id).status != 'available':
997 keep_waiting = True
998 if keep_waiting:
999 time.sleep(1)
1000 elapsed_time += 1
1001
1002 #if we exceeded the timeout rollback
1003 if elapsed_time >= volume_timeout:
1004 #delete the volumes we just created
1005 for volume_id in block_device_mapping.itervalues():
1006 self.cinder.volumes.delete(volume_id)
1007
1008 #delete ports we just created
1009 for net_item in net_list_vim:
1010 if 'port-id' in net_item:
montesmorenocf227142017-01-12 12:24:21 +00001011 self.neutron.delete_port(net_item['port-id'])
montesmoreno0c8def02016-12-22 12:16:23 +00001012
1013 raise vimconn.vimconnException('Timeout creating volumes for instance ' + name,
1014 http_code=vimconn.HTTP_Request_Timeout)
mirabal29356312017-07-27 12:21:22 +02001015 # get availability Zone
tierno5a3273c2017-08-29 11:43:46 +02001016 vm_av_zone = self._get_vm_availability_zone(availability_zone_index, availability_zone_list)
montesmoreno0c8def02016-12-22 12:16:23 +00001017
mirabal29356312017-07-27 12:21:22 +02001018 self.logger.debug("nova.servers.create({}, {}, {}, nics={}, meta={}, security_groups={}, "
1019 "availability_zone={}, key_name={}, userdata={}, config_drive={}, "
1020 "block_device_mapping={})".format(name, image_id, flavor_id, net_list_vim, metadata,
1021 security_groups, vm_av_zone, self.config.get('keypair'),
1022 userdata, config_drive, block_device_mapping))
tierno7edb6752016-03-21 17:37:52 +01001023 server = self.nova.servers.create(name, image_id, flavor_id, nics=net_list_vim, meta=metadata,
montesmoreno0c8def02016-12-22 12:16:23 +00001024 security_groups=security_groups,
mirabal29356312017-07-27 12:21:22 +02001025 availability_zone=vm_av_zone,
montesmoreno0c8def02016-12-22 12:16:23 +00001026 key_name=self.config.get('keypair'),
1027 userdata=userdata,
tiernob84cbdc2017-07-07 14:30:30 +02001028 config_drive=config_drive,
1029 block_device_mapping=block_device_mapping
montesmoreno0c8def02016-12-22 12:16:23 +00001030 ) # , description=description)
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001031
1032 # Previously mentioned workaround to wait until the VM is active and then disable the port-security
1033 if no_secured_ports:
1034 self.__wait_for_vm(server.id, 'ACTIVE')
1035
1036 for port_id in no_secured_ports:
1037 try:
1038 self.neutron.update_port(port_id, {"port": {"port_security_enabled": False, "security_groups": None} })
1039
1040 except Exception as e:
1041 self.logger.error("It was not possible to disable port security for port {}".format(port_id))
1042 self.delete_vminstance(server.id)
1043 raise
1044
tiernoae4a8d12016-07-08 12:30:39 +02001045 #print "DONE :-)", server
ahmadsaf853d452016-12-22 11:33:47 +05001046 pool_id = None
1047 floating_ips = self.neutron.list_floatingips().get("floatingips", ())
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001048
1049 if external_network:
1050 self.__wait_for_vm(server.id, 'ACTIVE')
1051
ahmadsaf853d452016-12-22 11:33:47 +05001052 for floating_network in external_network:
tiernof8383b82017-01-18 15:49:48 +01001053 try:
tiernof8383b82017-01-18 15:49:48 +01001054 assigned = False
1055 while(assigned == False):
1056 if floating_ips:
1057 ip = floating_ips.pop(0)
1058 if not ip.get("port_id", False) and ip.get('tenant_id') == server.tenant_id:
1059 free_floating_ip = ip.get("floating_ip_address")
1060 try:
1061 fix_ip = floating_network.get('ip')
1062 server.add_floating_ip(free_floating_ip, fix_ip)
1063 assigned = True
1064 except Exception as e:
1065 raise vimconn.vimconnException(type(e).__name__ + ": Cannot create floating_ip "+ str(e), http_code=vimconn.HTTP_Conflict)
1066 else:
1067 #Find the external network
1068 external_nets = list()
1069 for net in self.neutron.list_networks()['networks']:
1070 if net['router:external']:
1071 external_nets.append(net)
1072
1073 if len(external_nets) == 0:
1074 raise vimconn.vimconnException("Cannot create floating_ip automatically since no external "
1075 "network is present",
1076 http_code=vimconn.HTTP_Conflict)
1077 if len(external_nets) > 1:
1078 raise vimconn.vimconnException("Cannot create floating_ip automatically since multiple "
1079 "external networks are present",
1080 http_code=vimconn.HTTP_Conflict)
1081
1082 pool_id = external_nets[0].get('id')
1083 param = {'floatingip': {'floating_network_id': pool_id, 'tenant_id': server.tenant_id}}
ahmadsaf853d452016-12-22 11:33:47 +05001084 try:
tiernof8383b82017-01-18 15:49:48 +01001085 #self.logger.debug("Creating floating IP")
1086 new_floating_ip = self.neutron.create_floatingip(param)
1087 free_floating_ip = new_floating_ip['floatingip']['floating_ip_address']
ahmadsaf853d452016-12-22 11:33:47 +05001088 fix_ip = floating_network.get('ip')
1089 server.add_floating_ip(free_floating_ip, fix_ip)
tiernof8383b82017-01-18 15:49:48 +01001090 assigned=True
ahmadsaf853d452016-12-22 11:33:47 +05001091 except Exception as e:
tiernof8383b82017-01-18 15:49:48 +01001092 raise vimconn.vimconnException(type(e).__name__ + ": Cannot assign floating_ip "+ str(e), http_code=vimconn.HTTP_Conflict)
1093 except Exception as e:
1094 if not floating_network['exit_on_floating_ip_error']:
1095 self.logger.warn("Cannot create floating_ip. %s", str(e))
1096 continue
tiernof8383b82017-01-18 15:49:48 +01001097 raise
montesmoreno2a1fc4e2017-01-09 16:46:04 +00001098
tiernoae4a8d12016-07-08 12:30:39 +02001099 return server.id
tierno7edb6752016-03-21 17:37:52 +01001100# except nvExceptions.NotFound as e:
1101# error_value=-vimconn.HTTP_Not_Found
1102# error_text= "vm instance %s not found" % vm_id
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001103# except TypeError as e:
1104# raise vimconn.vimconnException(type(e).__name__ + ": "+ str(e), http_code=vimconn.HTTP_Bad_Request)
1105
1106 except Exception as e:
montesmoreno2a1fc4e2017-01-09 16:46:04 +00001107 # delete the volumes we just created
tiernob84cbdc2017-07-07 14:30:30 +02001108 if block_device_mapping:
montesmoreno2a1fc4e2017-01-09 16:46:04 +00001109 for volume_id in block_device_mapping.itervalues():
1110 self.cinder.volumes.delete(volume_id)
1111
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001112 # Delete the VM
1113 if server != None:
1114 self.delete_vminstance(server.id)
1115 else:
1116 # delete ports we just created
1117 for net_item in net_list_vim:
1118 if 'port-id' in net_item:
1119 self.neutron.delete_port(net_item['port-id'])
1120
tiernoae4a8d12016-07-08 12:30:39 +02001121 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001122
tiernoae4a8d12016-07-08 12:30:39 +02001123 def get_vminstance(self,vm_id):
tierno7edb6752016-03-21 17:37:52 +01001124 '''Returns the VM instance information from VIM'''
tiernoae4a8d12016-07-08 12:30:39 +02001125 #self.logger.debug("Getting VM from VIM")
tierno7edb6752016-03-21 17:37:52 +01001126 try:
1127 self._reload_connection()
1128 server = self.nova.servers.find(id=vm_id)
1129 #TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
tiernoae4a8d12016-07-08 12:30:39 +02001130 return server.to_dict()
tierno8e995ce2016-09-22 08:13:00 +00001131 except (ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.NotFound, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001132 self._format_exception(e)
1133
1134 def get_vminstance_console(self,vm_id, console_type="vnc"):
tierno7edb6752016-03-21 17:37:52 +01001135 '''
1136 Get a console for the virtual machine
1137 Params:
1138 vm_id: uuid of the VM
1139 console_type, can be:
1140 "novnc" (by default), "xvpvnc" for VNC types,
1141 "rdp-html5" for RDP types, "spice-html5" for SPICE types
tiernoae4a8d12016-07-08 12:30:39 +02001142 Returns dict with the console parameters:
1143 protocol: ssh, ftp, http, https, ...
1144 server: usually ip address
1145 port: the http, ssh, ... port
1146 suffix: extra text, e.g. the http path and query string
tierno7edb6752016-03-21 17:37:52 +01001147 '''
tiernoae4a8d12016-07-08 12:30:39 +02001148 self.logger.debug("Getting VM CONSOLE from VIM")
tierno7edb6752016-03-21 17:37:52 +01001149 try:
1150 self._reload_connection()
1151 server = self.nova.servers.find(id=vm_id)
1152 if console_type == None or console_type == "novnc":
1153 console_dict = server.get_vnc_console("novnc")
1154 elif console_type == "xvpvnc":
1155 console_dict = server.get_vnc_console(console_type)
1156 elif console_type == "rdp-html5":
1157 console_dict = server.get_rdp_console(console_type)
1158 elif console_type == "spice-html5":
1159 console_dict = server.get_spice_console(console_type)
1160 else:
tiernoae4a8d12016-07-08 12:30:39 +02001161 raise vimconn.vimconnException("console type '{}' not allowed".format(console_type), http_code=vimconn.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001162
1163 console_dict1 = console_dict.get("console")
1164 if console_dict1:
1165 console_url = console_dict1.get("url")
1166 if console_url:
1167 #parse console_url
1168 protocol_index = console_url.find("//")
1169 suffix_index = console_url[protocol_index+2:].find("/") + protocol_index+2
1170 port_index = console_url[protocol_index+2:suffix_index].find(":") + protocol_index+2
1171 if protocol_index < 0 or port_index<0 or suffix_index<0:
1172 return -vimconn.HTTP_Internal_Server_Error, "Unexpected response from VIM"
1173 console_dict={"protocol": console_url[0:protocol_index],
1174 "server": console_url[protocol_index+2:port_index],
1175 "port": console_url[port_index:suffix_index],
1176 "suffix": console_url[suffix_index+1:]
1177 }
1178 protocol_index += 2
tiernoae4a8d12016-07-08 12:30:39 +02001179 return console_dict
1180 raise vimconn.vimconnUnexpectedResponse("Unexpected response from VIM")
tierno7edb6752016-03-21 17:37:52 +01001181
tierno8e995ce2016-09-22 08:13:00 +00001182 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.BadRequest, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001183 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001184
tiernoae4a8d12016-07-08 12:30:39 +02001185 def delete_vminstance(self, vm_id):
1186 '''Removes a VM instance from VIM. Returns the old identifier
tierno7edb6752016-03-21 17:37:52 +01001187 '''
tiernoae4a8d12016-07-08 12:30:39 +02001188 #print "osconnector: Getting VM from VIM"
tierno7edb6752016-03-21 17:37:52 +01001189 try:
1190 self._reload_connection()
1191 #delete VM ports attached to this networks before the virtual machine
1192 ports = self.neutron.list_ports(device_id=vm_id)
1193 for p in ports['ports']:
1194 try:
1195 self.neutron.delete_port(p["id"])
1196 except Exception as e:
tiernoae4a8d12016-07-08 12:30:39 +02001197 self.logger.error("Error deleting port: " + type(e).__name__ + ": "+ str(e))
montesmoreno0c8def02016-12-22 12:16:23 +00001198
1199 #commented because detaching the volumes makes the servers.delete not work properly ?!?
1200 #dettach volumes attached
1201 server = self.nova.servers.get(vm_id)
1202 volumes_attached_dict = server._info['os-extended-volumes:volumes_attached']
1203 #for volume in volumes_attached_dict:
1204 # self.cinder.volumes.detach(volume['id'])
1205
tierno7edb6752016-03-21 17:37:52 +01001206 self.nova.servers.delete(vm_id)
montesmoreno0c8def02016-12-22 12:16:23 +00001207
1208 #delete volumes.
1209 #Although having detached them should have them in active status
1210 #we ensure in this loop
1211 keep_waiting = True
1212 elapsed_time = 0
1213 while keep_waiting and elapsed_time < volume_timeout:
1214 keep_waiting = False
1215 for volume in volumes_attached_dict:
1216 if self.cinder.volumes.get(volume['id']).status != 'available':
1217 keep_waiting = True
1218 else:
1219 self.cinder.volumes.delete(volume['id'])
1220 if keep_waiting:
1221 time.sleep(1)
1222 elapsed_time += 1
1223
tiernoae4a8d12016-07-08 12:30:39 +02001224 return vm_id
tierno8e995ce2016-09-22 08:13:00 +00001225 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001226 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001227 #TODO insert exception vimconn.HTTP_Unauthorized
1228 #if reaching here is because an exception
tierno7edb6752016-03-21 17:37:52 +01001229
tiernoae4a8d12016-07-08 12:30:39 +02001230 def refresh_vms_status(self, vm_list):
1231 '''Get the status of the virtual machines and their interfaces/ports
1232 Params: the list of VM identifiers
1233 Returns a dictionary with:
1234 vm_id: #VIM id of this Virtual Machine
1235 status: #Mandatory. Text with one of:
1236 # DELETED (not found at vim)
1237 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
1238 # OTHER (Vim reported other status not understood)
1239 # ERROR (VIM indicates an ERROR status)
1240 # ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running),
1241 # CREATING (on building process), ERROR
1242 # ACTIVE:NoMgmtIP (Active but any of its interface has an IP address
1243 #
1244 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
1245 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
1246 interfaces:
1247 - vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
1248 mac_address: #Text format XX:XX:XX:XX:XX:XX
1249 vim_net_id: #network id where this interface is connected
1250 vim_interface_id: #interface/port VIM id
1251 ip_address: #null, or text with IPv4, IPv6 address
tierno867ffe92017-03-27 12:50:34 +02001252 compute_node: #identification of compute node where PF,VF interface is allocated
1253 pci: #PCI address of the NIC that hosts the PF,VF
1254 vlan: #physical VLAN used for VF
tierno7edb6752016-03-21 17:37:52 +01001255 '''
tiernoae4a8d12016-07-08 12:30:39 +02001256 vm_dict={}
1257 self.logger.debug("refresh_vms status: Getting tenant VM instance information from VIM")
1258 for vm_id in vm_list:
1259 vm={}
1260 try:
1261 vm_vim = self.get_vminstance(vm_id)
1262 if vm_vim['status'] in vmStatus2manoFormat:
1263 vm['status'] = vmStatus2manoFormat[ vm_vim['status'] ]
tierno7edb6752016-03-21 17:37:52 +01001264 else:
tiernoae4a8d12016-07-08 12:30:39 +02001265 vm['status'] = "OTHER"
1266 vm['error_msg'] = "VIM status reported " + vm_vim['status']
tierno8e995ce2016-09-22 08:13:00 +00001267 try:
1268 vm['vim_info'] = yaml.safe_dump(vm_vim, default_flow_style=True, width=256)
1269 except yaml.representer.RepresenterError:
1270 vm['vim_info'] = str(vm_vim)
tiernoae4a8d12016-07-08 12:30:39 +02001271 vm["interfaces"] = []
1272 if vm_vim.get('fault'):
1273 vm['error_msg'] = str(vm_vim['fault'])
1274 #get interfaces
tierno7edb6752016-03-21 17:37:52 +01001275 try:
tiernoae4a8d12016-07-08 12:30:39 +02001276 self._reload_connection()
1277 port_dict=self.neutron.list_ports(device_id=vm_id)
1278 for port in port_dict["ports"]:
1279 interface={}
tierno8e995ce2016-09-22 08:13:00 +00001280 try:
1281 interface['vim_info'] = yaml.safe_dump(port, default_flow_style=True, width=256)
1282 except yaml.representer.RepresenterError:
1283 interface['vim_info'] = str(port)
tiernoae4a8d12016-07-08 12:30:39 +02001284 interface["mac_address"] = port.get("mac_address")
1285 interface["vim_net_id"] = port["network_id"]
1286 interface["vim_interface_id"] = port["id"]
Mike Marchetti5b9da422017-05-02 15:35:47 -04001287 # check if OS-EXT-SRV-ATTR:host is there,
1288 # in case of non-admin credentials, it will be missing
1289 if vm_vim.get('OS-EXT-SRV-ATTR:host'):
1290 interface["compute_node"] = vm_vim['OS-EXT-SRV-ATTR:host']
tierno867ffe92017-03-27 12:50:34 +02001291 interface["pci"] = None
Mike Marchetti5b9da422017-05-02 15:35:47 -04001292
1293 # check if binding:profile is there,
1294 # in case of non-admin credentials, it will be missing
1295 if port.get('binding:profile'):
1296 if port['binding:profile'].get('pci_slot'):
1297 # TODO: At the moment sr-iov pci addresses are converted to PF pci addresses by setting the slot to 0x00
1298 # TODO: This is just a workaround valid for niantinc. Find a better way to do so
1299 # CHANGE DDDD:BB:SS.F to DDDD:BB:00.(F%2) assuming there are 2 ports per nic
1300 pci = port['binding:profile']['pci_slot']
1301 # interface["pci"] = pci[:-4] + "00." + str(int(pci[-1]) % 2)
1302 interface["pci"] = pci
tierno867ffe92017-03-27 12:50:34 +02001303 interface["vlan"] = None
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001304 #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 +01001305 network = self.neutron.show_network(port["network_id"])
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001306 if network['network'].get('provider:network_type') == 'vlan' and \
1307 port.get("binding:vnic_type") == "direct":
tierno867ffe92017-03-27 12:50:34 +02001308 interface["vlan"] = network['network'].get('provider:segmentation_id')
tiernoae4a8d12016-07-08 12:30:39 +02001309 ips=[]
1310 #look for floating ip address
1311 floating_ip_dict = self.neutron.list_floatingips(port_id=port["id"])
1312 if floating_ip_dict.get("floatingips"):
1313 ips.append(floating_ip_dict["floatingips"][0].get("floating_ip_address") )
tierno7edb6752016-03-21 17:37:52 +01001314
tiernoae4a8d12016-07-08 12:30:39 +02001315 for subnet in port["fixed_ips"]:
1316 ips.append(subnet["ip_address"])
1317 interface["ip_address"] = ";".join(ips)
1318 vm["interfaces"].append(interface)
1319 except Exception as e:
1320 self.logger.error("Error getting vm interface information " + type(e).__name__ + ": "+ str(e))
1321 except vimconn.vimconnNotFoundException as e:
1322 self.logger.error("Exception getting vm status: %s", str(e))
1323 vm['status'] = "DELETED"
1324 vm['error_msg'] = str(e)
1325 except vimconn.vimconnException as e:
1326 self.logger.error("Exception getting vm status: %s", str(e))
1327 vm['status'] = "VIM_ERROR"
1328 vm['error_msg'] = str(e)
1329 vm_dict[vm_id] = vm
1330 return vm_dict
tierno7edb6752016-03-21 17:37:52 +01001331
tiernoae4a8d12016-07-08 12:30:39 +02001332 def action_vminstance(self, vm_id, action_dict):
tierno7edb6752016-03-21 17:37:52 +01001333 '''Send and action over a VM instance from VIM
tiernoae4a8d12016-07-08 12:30:39 +02001334 Returns the vm_id if the action was successfully sent to the VIM'''
1335 self.logger.debug("Action over VM '%s': %s", vm_id, str(action_dict))
tierno7edb6752016-03-21 17:37:52 +01001336 try:
1337 self._reload_connection()
1338 server = self.nova.servers.find(id=vm_id)
1339 if "start" in action_dict:
1340 if action_dict["start"]=="rebuild":
1341 server.rebuild()
1342 else:
1343 if server.status=="PAUSED":
1344 server.unpause()
1345 elif server.status=="SUSPENDED":
1346 server.resume()
1347 elif server.status=="SHUTOFF":
1348 server.start()
1349 elif "pause" in action_dict:
1350 server.pause()
1351 elif "resume" in action_dict:
1352 server.resume()
1353 elif "shutoff" in action_dict or "shutdown" in action_dict:
1354 server.stop()
1355 elif "forceOff" in action_dict:
1356 server.stop() #TODO
1357 elif "terminate" in action_dict:
1358 server.delete()
1359 elif "createImage" in action_dict:
1360 server.create_image()
1361 #"path":path_schema,
1362 #"description":description_schema,
1363 #"name":name_schema,
1364 #"metadata":metadata_schema,
1365 #"imageRef": id_schema,
1366 #"disk": {"oneOf":[{"type": "null"}, {"type":"string"}] },
1367 elif "rebuild" in action_dict:
1368 server.rebuild(server.image['id'])
1369 elif "reboot" in action_dict:
1370 server.reboot() #reboot_type='SOFT'
1371 elif "console" in action_dict:
1372 console_type = action_dict["console"]
1373 if console_type == None or console_type == "novnc":
1374 console_dict = server.get_vnc_console("novnc")
1375 elif console_type == "xvpvnc":
1376 console_dict = server.get_vnc_console(console_type)
1377 elif console_type == "rdp-html5":
1378 console_dict = server.get_rdp_console(console_type)
1379 elif console_type == "spice-html5":
1380 console_dict = server.get_spice_console(console_type)
1381 else:
tiernoae4a8d12016-07-08 12:30:39 +02001382 raise vimconn.vimconnException("console type '{}' not allowed".format(console_type),
1383 http_code=vimconn.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001384 try:
1385 console_url = console_dict["console"]["url"]
1386 #parse console_url
1387 protocol_index = console_url.find("//")
1388 suffix_index = console_url[protocol_index+2:].find("/") + protocol_index+2
1389 port_index = console_url[protocol_index+2:suffix_index].find(":") + protocol_index+2
1390 if protocol_index < 0 or port_index<0 or suffix_index<0:
tiernoae4a8d12016-07-08 12:30:39 +02001391 raise vimconn.vimconnException("Unexpected response from VIM " + str(console_dict))
tierno7edb6752016-03-21 17:37:52 +01001392 console_dict2={"protocol": console_url[0:protocol_index],
1393 "server": console_url[protocol_index+2 : port_index],
1394 "port": int(console_url[port_index+1 : suffix_index]),
1395 "suffix": console_url[suffix_index+1:]
1396 }
tiernoae4a8d12016-07-08 12:30:39 +02001397 return console_dict2
1398 except Exception as e:
1399 raise vimconn.vimconnException("Unexpected response from VIM " + str(console_dict))
tierno7edb6752016-03-21 17:37:52 +01001400
tiernoae4a8d12016-07-08 12:30:39 +02001401 return vm_id
tierno8e995ce2016-09-22 08:13:00 +00001402 except (ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.NotFound, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001403 self._format_exception(e)
1404 #TODO insert exception vimconn.HTTP_Unauthorized
1405
1406#NOT USED FUNCTIONS
1407
1408 def new_external_port(self, port_data):
1409 #TODO openstack if needed
1410 '''Adds a external port to VIM'''
1411 '''Returns the port identifier'''
1412 return -vimconn.HTTP_Internal_Server_Error, "osconnector.new_external_port() not implemented"
1413
1414 def connect_port_network(self, port_id, network_id, admin=False):
1415 #TODO openstack if needed
1416 '''Connects a external port to a network'''
1417 '''Returns status code of the VIM response'''
1418 return -vimconn.HTTP_Internal_Server_Error, "osconnector.connect_port_network() not implemented"
1419
1420 def new_user(self, user_name, user_passwd, tenant_id=None):
1421 '''Adds a new user to openstack VIM'''
1422 '''Returns the user identifier'''
1423 self.logger.debug("osconnector: Adding a new user to VIM")
1424 try:
1425 self._reload_connection()
1426 user=self.keystone.users.create(user_name, user_passwd, tenant_id=tenant_id)
1427 #self.keystone.tenants.add_user(self.k_creds["username"], #role)
1428 return user.id
1429 except ksExceptions.ConnectionError as e:
1430 error_value=-vimconn.HTTP_Bad_Request
1431 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1432 except ksExceptions.ClientException as e: #TODO remove
tierno7edb6752016-03-21 17:37:52 +01001433 error_value=-vimconn.HTTP_Bad_Request
1434 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1435 #TODO insert exception vimconn.HTTP_Unauthorized
1436 #if reaching here is because an exception
1437 if self.debug:
tiernoae4a8d12016-07-08 12:30:39 +02001438 self.logger.debug("new_user " + error_text)
tierno7edb6752016-03-21 17:37:52 +01001439 return error_value, error_text
tiernoae4a8d12016-07-08 12:30:39 +02001440
1441 def delete_user(self, user_id):
1442 '''Delete a user from openstack VIM'''
1443 '''Returns the user identifier'''
1444 if self.debug:
1445 print "osconnector: Deleting a user from VIM"
1446 try:
1447 self._reload_connection()
1448 self.keystone.users.delete(user_id)
1449 return 1, user_id
1450 except ksExceptions.ConnectionError as e:
1451 error_value=-vimconn.HTTP_Bad_Request
1452 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1453 except ksExceptions.NotFound as e:
1454 error_value=-vimconn.HTTP_Not_Found
1455 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1456 except ksExceptions.ClientException as e: #TODO remove
1457 error_value=-vimconn.HTTP_Bad_Request
1458 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1459 #TODO insert exception vimconn.HTTP_Unauthorized
1460 #if reaching here is because an exception
1461 if self.debug:
1462 print "delete_tenant " + error_text
1463 return error_value, error_text
1464
tierno7edb6752016-03-21 17:37:52 +01001465 def get_hosts_info(self):
1466 '''Get the information of deployed hosts
1467 Returns the hosts content'''
1468 if self.debug:
1469 print "osconnector: Getting Host info from VIM"
1470 try:
1471 h_list=[]
1472 self._reload_connection()
1473 hypervisors = self.nova.hypervisors.list()
1474 for hype in hypervisors:
1475 h_list.append( hype.to_dict() )
1476 return 1, {"hosts":h_list}
1477 except nvExceptions.NotFound as e:
1478 error_value=-vimconn.HTTP_Not_Found
1479 error_text= (str(e) if len(e.args)==0 else str(e.args[0]))
1480 except (ksExceptions.ClientException, nvExceptions.ClientException) as e:
1481 error_value=-vimconn.HTTP_Bad_Request
1482 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1483 #TODO insert exception vimconn.HTTP_Unauthorized
1484 #if reaching here is because an exception
1485 if self.debug:
1486 print "get_hosts_info " + error_text
1487 return error_value, error_text
1488
1489 def get_hosts(self, vim_tenant):
1490 '''Get the hosts and deployed instances
1491 Returns the hosts content'''
1492 r, hype_dict = self.get_hosts_info()
1493 if r<0:
1494 return r, hype_dict
1495 hypervisors = hype_dict["hosts"]
1496 try:
1497 servers = self.nova.servers.list()
1498 for hype in hypervisors:
1499 for server in servers:
1500 if server.to_dict()['OS-EXT-SRV-ATTR:hypervisor_hostname']==hype['hypervisor_hostname']:
1501 if 'vm' in hype:
1502 hype['vm'].append(server.id)
1503 else:
1504 hype['vm'] = [server.id]
1505 return 1, hype_dict
1506 except nvExceptions.NotFound as e:
1507 error_value=-vimconn.HTTP_Not_Found
1508 error_text= (str(e) if len(e.args)==0 else str(e.args[0]))
1509 except (ksExceptions.ClientException, nvExceptions.ClientException) as e:
1510 error_value=-vimconn.HTTP_Bad_Request
1511 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1512 #TODO insert exception vimconn.HTTP_Unauthorized
1513 #if reaching here is because an exception
1514 if self.debug:
1515 print "get_hosts " + error_text
1516 return error_value, error_text
1517
tierno7edb6752016-03-21 17:37:52 +01001518