| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1 | # -*- coding: utf-8 -*- |
| 2 | |
| 3 | ## |
| 4 | # Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U. |
| 5 | # This file is part of openmano |
| 6 | # All Rights Reserved. |
| 7 | # |
| 8 | # Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 9 | # not use this file except in compliance with the License. You may obtain |
| 10 | # a copy of the License at |
| 11 | # |
| 12 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 13 | # |
| 14 | # Unless required by applicable law or agreed to in writing, software |
| 15 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 16 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 17 | # License for the specific language governing permissions and limitations |
| 18 | # under the License. |
| 19 | # |
| 20 | # For those usages not covered by the Apache License, Version 2.0 please |
| 21 | # contact with: nfvlabs@tid.es |
| 22 | ## |
| 23 | |
| 24 | ''' |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 25 | osconnector implements all the methods to interact with openstack using the python-neutronclient. |
| 26 | |
| 27 | For the VNF forwarding graph, The OpenStack VIM connector calls the |
| 28 | networking-sfc Neutron extension methods, whose resources are mapped |
| 29 | to the VIM connector's SFC resources as follows: |
| 30 | - Classification (OSM) -> Flow Classifier (Neutron) |
| 31 | - Service Function Instance (OSM) -> Port Pair (Neutron) |
| 32 | - Service Function (OSM) -> Port Pair Group (Neutron) |
| 33 | - Service Function Path (OSM) -> Port Chain (Neutron) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 34 | ''' |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 35 | __author__ = "Alfonso Tierno, Gerardo Garcia, Pablo Montes, xFlow Research, Igor D.C." |
| 36 | __date__ = "$22-sep-2017 23:59:59$" |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 37 | |
| 38 | import vimconn |
| tierno | 69b590e | 2018-03-13 18:52:23 +0100 | [diff] [blame] | 39 | # import json |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 40 | import logging |
| garciadeblas | 9f8456e | 2016-09-05 05:02:59 +0200 | [diff] [blame] | 41 | import netaddr |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 42 | import time |
| tierno | 36c0b17 | 2017-01-12 18:32:28 +0100 | [diff] [blame] | 43 | import yaml |
| garciadeblas | 2299e3b | 2017-01-26 14:35:55 +0000 | [diff] [blame] | 44 | import random |
| kate | 721d79b | 2017-06-24 04:21:38 -0700 | [diff] [blame] | 45 | import re |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 46 | import copy |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 47 | |
| tierno | b5cef37 | 2017-06-19 15:52:22 +0200 | [diff] [blame] | 48 | from novaclient import client as nClient, exceptions as nvExceptions |
| 49 | from keystoneauth1.identity import v2, v3 |
| 50 | from keystoneauth1 import session |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 51 | import keystoneclient.exceptions as ksExceptions |
| tierno | f716aea | 2017-06-21 18:01:40 +0200 | [diff] [blame] | 52 | import keystoneclient.v3.client as ksClient_v3 |
| 53 | import keystoneclient.v2_0.client as ksClient_v2 |
| tierno | b5cef37 | 2017-06-19 15:52:22 +0200 | [diff] [blame] | 54 | from glanceclient import client as glClient |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 55 | import glanceclient.client as gl1Client |
| 56 | import glanceclient.exc as gl1Exceptions |
| tierno | b5cef37 | 2017-06-19 15:52:22 +0200 | [diff] [blame] | 57 | from cinderclient import client as cClient |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 58 | from httplib import HTTPException |
| tierno | b5cef37 | 2017-06-19 15:52:22 +0200 | [diff] [blame] | 59 | from neutronclient.neutron import client as neClient |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 60 | from neutronclient.common import exceptions as neExceptions |
| 61 | from requests.exceptions import ConnectionError |
| 62 | |
| tierno | 40e1bce | 2017-08-09 09:12:04 +0200 | [diff] [blame] | 63 | |
| 64 | """contain the openstack virtual machine status to openmano status""" |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 65 | vmStatus2manoFormat={'ACTIVE':'ACTIVE', |
| 66 | 'PAUSED':'PAUSED', |
| 67 | 'SUSPENDED': 'SUSPENDED', |
| 68 | 'SHUTOFF':'INACTIVE', |
| 69 | 'BUILD':'BUILD', |
| 70 | 'ERROR':'ERROR','DELETED':'DELETED' |
| 71 | } |
| 72 | netStatus2manoFormat={'ACTIVE':'ACTIVE','PAUSED':'PAUSED','INACTIVE':'INACTIVE','BUILD':'BUILD','ERROR':'ERROR','DELETED':'DELETED' |
| 73 | } |
| 74 | |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 75 | supportedClassificationTypes = ['legacy_flow_classifier'] |
| 76 | |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 77 | #global var to have a timeout creating and deleting volumes |
| tierno | 00e3df7 | 2017-11-29 17:20:13 +0100 | [diff] [blame] | 78 | volume_timeout = 600 |
| 79 | server_timeout = 600 |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 80 | |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 81 | class vimconnector(vimconn.vimconnector): |
| tierno | b3d3674 | 2017-03-03 23:51:05 +0100 | [diff] [blame] | 82 | def __init__(self, uuid, name, tenant_id, tenant_name, url, url_admin=None, user=None, passwd=None, |
| 83 | log_level=None, config={}, persistent_info={}): |
| ahmadsa | 96af9f4 | 2017-01-31 16:17:14 +0500 | [diff] [blame] | 84 | '''using common constructor parameters. In this case |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 85 | 'url' is the keystone authorization url, |
| 86 | 'url_admin' is not use |
| 87 | ''' |
| tierno | f716aea | 2017-06-21 18:01:40 +0200 | [diff] [blame] | 88 | api_version = config.get('APIversion') |
| 89 | if api_version and api_version not in ('v3.3', 'v2.0', '2', '3'): |
| tierno | b5cef37 | 2017-06-19 15:52:22 +0200 | [diff] [blame] | 90 | raise vimconn.vimconnException("Invalid value '{}' for config:APIversion. " |
| tierno | f716aea | 2017-06-21 18:01:40 +0200 | [diff] [blame] | 91 | "Allowed values are 'v3.3', 'v2.0', '2' or '3'".format(api_version)) |
| kate | 721d79b | 2017-06-24 04:21:38 -0700 | [diff] [blame] | 92 | vim_type = config.get('vim_type') |
| 93 | if vim_type and vim_type not in ('vio', 'VIO'): |
| 94 | raise vimconn.vimconnException("Invalid value '{}' for config:vim_type." |
| 95 | "Allowed values are 'vio' or 'VIO'".format(vim_type)) |
| 96 | |
| 97 | if config.get('dataplane_net_vlan_range') is not None: |
| 98 | #validate vlan ranges provided by user |
| 99 | self._validate_vlan_ranges(config.get('dataplane_net_vlan_range')) |
| 100 | |
| tierno | b5cef37 | 2017-06-19 15:52:22 +0200 | [diff] [blame] | 101 | vimconn.vimconnector.__init__(self, uuid, name, tenant_id, tenant_name, url, url_admin, user, passwd, log_level, |
| 102 | config) |
| tierno | b3d3674 | 2017-03-03 23:51:05 +0100 | [diff] [blame] | 103 | |
| tierno | 4d1ce22 | 2018-04-06 10:41:06 +0200 | [diff] [blame] | 104 | if self.config.get("insecure") and self.config.get("ca_cert"): |
| 105 | raise vimconn.vimconnException("options insecure and ca_cert are mutually exclusive") |
| 106 | self.verify = True |
| 107 | if self.config.get("insecure"): |
| 108 | self.verify = False |
| 109 | if self.config.get("ca_cert"): |
| 110 | self.verify = self.config.get("ca_cert") |
| 111 | self.verify = self.config.get("insecure", False) |
| 112 | |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 113 | if not url: |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 114 | raise TypeError('url param can not be NoneType') |
| tierno | b5cef37 | 2017-06-19 15:52:22 +0200 | [diff] [blame] | 115 | self.persistent_info = persistent_info |
| mirabal | 2935631 | 2017-07-27 12:21:22 +0200 | [diff] [blame] | 116 | self.availability_zone = persistent_info.get('availability_zone', None) |
| tierno | b5cef37 | 2017-06-19 15:52:22 +0200 | [diff] [blame] | 117 | self.session = persistent_info.get('session', {'reload_client': True}) |
| 118 | self.nova = self.session.get('nova') |
| 119 | self.neutron = self.session.get('neutron') |
| 120 | self.cinder = self.session.get('cinder') |
| 121 | self.glance = self.session.get('glance') |
| tierno | b39d49e | 2017-08-02 14:02:15 +0200 | [diff] [blame] | 122 | self.glancev1 = self.session.get('glancev1') |
| tierno | f716aea | 2017-06-21 18:01:40 +0200 | [diff] [blame] | 123 | self.keystone = self.session.get('keystone') |
| 124 | self.api_version3 = self.session.get('api_version3') |
| kate | 721d79b | 2017-06-24 04:21:38 -0700 | [diff] [blame] | 125 | self.vim_type = self.config.get("vim_type") |
| 126 | if self.vim_type: |
| 127 | self.vim_type = self.vim_type.upper() |
| 128 | if self.config.get("use_internal_endpoint"): |
| 129 | self.endpoint_type = "internalURL" |
| 130 | else: |
| 131 | self.endpoint_type = None |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 132 | |
| tierno | 73ad9e4 | 2016-09-12 18:11:11 +0200 | [diff] [blame] | 133 | self.logger = logging.getLogger('openmano.vim.openstack') |
| kate | 721d79b | 2017-06-24 04:21:38 -0700 | [diff] [blame] | 134 | |
| 135 | ####### VIO Specific Changes ######### |
| 136 | if self.vim_type == "VIO": |
| 137 | self.logger = logging.getLogger('openmano.vim.vio') |
| 138 | |
| tierno | fe78990 | 2016-09-29 14:20:44 +0000 | [diff] [blame] | 139 | if log_level: |
| kate | 5461675 | 2017-09-05 23:26:28 -0700 | [diff] [blame] | 140 | self.logger.setLevel( getattr(logging, log_level)) |
| tierno | f716aea | 2017-06-21 18:01:40 +0200 | [diff] [blame] | 141 | |
| 142 | def __getitem__(self, index): |
| 143 | """Get individuals parameters. |
| 144 | Throw KeyError""" |
| 145 | if index == 'project_domain_id': |
| 146 | return self.config.get("project_domain_id") |
| 147 | elif index == 'user_domain_id': |
| 148 | return self.config.get("user_domain_id") |
| 149 | else: |
| tierno | 76a3c31 | 2017-06-29 16:42:15 +0200 | [diff] [blame] | 150 | return vimconn.vimconnector.__getitem__(self, index) |
| tierno | f716aea | 2017-06-21 18:01:40 +0200 | [diff] [blame] | 151 | |
| 152 | def __setitem__(self, index, value): |
| 153 | """Set individuals parameters and it is marked as dirty so to force connection reload. |
| 154 | Throw KeyError""" |
| 155 | if index == 'project_domain_id': |
| 156 | self.config["project_domain_id"] = value |
| 157 | elif index == 'user_domain_id': |
| 158 | self.config["user_domain_id"] = value |
| 159 | else: |
| 160 | vimconn.vimconnector.__setitem__(self, index, value) |
| tierno | b5cef37 | 2017-06-19 15:52:22 +0200 | [diff] [blame] | 161 | self.session['reload_client'] = True |
| tierno | f716aea | 2017-06-21 18:01:40 +0200 | [diff] [blame] | 162 | |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 163 | def _reload_connection(self): |
| 164 | '''Called before any operation, it check if credentials has changed |
| 165 | Throw keystoneclient.apiclient.exceptions.AuthorizationFailure |
| 166 | ''' |
| 167 | #TODO control the timing and possible token timeout, but it seams that python client does this task for us :-) |
| tierno | b5cef37 | 2017-06-19 15:52:22 +0200 | [diff] [blame] | 168 | if self.session['reload_client']: |
| tierno | f716aea | 2017-06-21 18:01:40 +0200 | [diff] [blame] | 169 | if self.config.get('APIversion'): |
| 170 | self.api_version3 = self.config['APIversion'] == 'v3.3' or self.config['APIversion'] == '3' |
| 171 | else: # get from ending auth_url that end with v3 or with v2.0 |
| tierno | 3cb8dc3 | 2017-10-24 18:13:19 +0200 | [diff] [blame] | 172 | self.api_version3 = self.url.endswith("/v3") or self.url.endswith("/v3/") |
| tierno | f716aea | 2017-06-21 18:01:40 +0200 | [diff] [blame] | 173 | self.session['api_version3'] = self.api_version3 |
| 174 | if self.api_version3: |
| tierno | 3cb8dc3 | 2017-10-24 18:13:19 +0200 | [diff] [blame] | 175 | if self.config.get('project_domain_id') or self.config.get('project_domain_name'): |
| 176 | project_domain_id_default = None |
| 177 | else: |
| 178 | project_domain_id_default = 'default' |
| 179 | if self.config.get('user_domain_id') or self.config.get('user_domain_name'): |
| 180 | user_domain_id_default = None |
| 181 | else: |
| 182 | user_domain_id_default = 'default' |
| tierno | f716aea | 2017-06-21 18:01:40 +0200 | [diff] [blame] | 183 | auth = v3.Password(auth_url=self.url, |
| tierno | b5cef37 | 2017-06-19 15:52:22 +0200 | [diff] [blame] | 184 | username=self.user, |
| 185 | password=self.passwd, |
| 186 | project_name=self.tenant_name, |
| 187 | project_id=self.tenant_id, |
| tierno | 3cb8dc3 | 2017-10-24 18:13:19 +0200 | [diff] [blame] | 188 | project_domain_id=self.config.get('project_domain_id', project_domain_id_default), |
| 189 | user_domain_id=self.config.get('user_domain_id', user_domain_id_default), |
| 190 | project_domain_name=self.config.get('project_domain_name'), |
| 191 | user_domain_name=self.config.get('user_domain_name')) |
| ahmadsa | 95baa27 | 2016-11-30 09:14:11 +0500 | [diff] [blame] | 192 | else: |
| tierno | f716aea | 2017-06-21 18:01:40 +0200 | [diff] [blame] | 193 | auth = v2.Password(auth_url=self.url, |
| tierno | b5cef37 | 2017-06-19 15:52:22 +0200 | [diff] [blame] | 194 | username=self.user, |
| 195 | password=self.passwd, |
| 196 | tenant_name=self.tenant_name, |
| 197 | tenant_id=self.tenant_id) |
| tierno | 4d1ce22 | 2018-04-06 10:41:06 +0200 | [diff] [blame] | 198 | sess = session.Session(auth=auth, verify=self.verify) |
| tierno | f716aea | 2017-06-21 18:01:40 +0200 | [diff] [blame] | 199 | if self.api_version3: |
| kate | 721d79b | 2017-06-24 04:21:38 -0700 | [diff] [blame] | 200 | self.keystone = ksClient_v3.Client(session=sess, endpoint_type=self.endpoint_type) |
| tierno | f716aea | 2017-06-21 18:01:40 +0200 | [diff] [blame] | 201 | else: |
| kate | 721d79b | 2017-06-24 04:21:38 -0700 | [diff] [blame] | 202 | self.keystone = ksClient_v2.Client(session=sess, endpoint_type=self.endpoint_type) |
| tierno | f716aea | 2017-06-21 18:01:40 +0200 | [diff] [blame] | 203 | self.session['keystone'] = self.keystone |
| montesmoreno | 9317d30 | 2017-08-16 12:48:23 +0200 | [diff] [blame] | 204 | # In order to enable microversion functionality an explicit microversion must be specified in 'config'. |
| 205 | # This implementation approach is due to the warning message in |
| 206 | # https://developer.openstack.org/api-guide/compute/microversions.html |
| 207 | # where it is stated that microversion backwards compatibility is not guaranteed and clients should |
| 208 | # always require an specific microversion. |
| 209 | # To be able to use 'device role tagging' functionality define 'microversion: 2.32' in datacenter config |
| 210 | version = self.config.get("microversion") |
| 211 | if not version: |
| 212 | version = "2.1" |
| kate | 5461675 | 2017-09-05 23:26:28 -0700 | [diff] [blame] | 213 | self.nova = self.session['nova'] = nClient.Client(str(version), session=sess, endpoint_type=self.endpoint_type) |
| kate | 721d79b | 2017-06-24 04:21:38 -0700 | [diff] [blame] | 214 | self.neutron = self.session['neutron'] = neClient.Client('2.0', session=sess, endpoint_type=self.endpoint_type) |
| 215 | self.cinder = self.session['cinder'] = cClient.Client(2, session=sess, endpoint_type=self.endpoint_type) |
| 216 | if self.endpoint_type == "internalURL": |
| 217 | glance_service_id = self.keystone.services.list(name="glance")[0].id |
| 218 | glance_endpoint = self.keystone.endpoints.list(glance_service_id, interface="internal")[0].url |
| 219 | else: |
| 220 | glance_endpoint = None |
| 221 | self.glance = self.session['glance'] = glClient.Client(2, session=sess, endpoint=glance_endpoint) |
| 222 | #using version 1 of glance client in new_image() |
| 223 | self.glancev1 = self.session['glancev1'] = glClient.Client('1', session=sess, |
| 224 | endpoint=glance_endpoint) |
| tierno | b5cef37 | 2017-06-19 15:52:22 +0200 | [diff] [blame] | 225 | self.session['reload_client'] = False |
| 226 | self.persistent_info['session'] = self.session |
| mirabal | 2935631 | 2017-07-27 12:21:22 +0200 | [diff] [blame] | 227 | # add availablity zone info inside self.persistent_info |
| 228 | self._set_availablity_zones() |
| 229 | self.persistent_info['availability_zone'] = self.availability_zone |
| ahmadsa | 95baa27 | 2016-11-30 09:14:11 +0500 | [diff] [blame] | 230 | |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 231 | def __net_os2mano(self, net_list_dict): |
| 232 | '''Transform the net openstack format to mano format |
| 233 | net_list_dict can be a list of dict or a single dict''' |
| 234 | if type(net_list_dict) is dict: |
| 235 | net_list_=(net_list_dict,) |
| 236 | elif type(net_list_dict) is list: |
| 237 | net_list_=net_list_dict |
| 238 | else: |
| 239 | raise TypeError("param net_list_dict must be a list or a dictionary") |
| 240 | for net in net_list_: |
| 241 | if net.get('provider:network_type') == "vlan": |
| 242 | net['type']='data' |
| 243 | else: |
| 244 | net['type']='bridge' |
| Pablo Montes Moreno | 6a7785b | 2017-07-03 10:44:30 +0200 | [diff] [blame] | 245 | |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 246 | def __classification_os2mano(self, class_list_dict): |
| 247 | """Transform the openstack format (Flow Classifier) to mano format |
| 248 | (Classification) class_list_dict can be a list of dict or a single dict |
| 249 | """ |
| 250 | if isinstance(class_list_dict, dict): |
| 251 | class_list_ = [class_list_dict] |
| 252 | elif isinstance(class_list_dict, list): |
| 253 | class_list_ = class_list_dict |
| 254 | else: |
| 255 | raise TypeError( |
| 256 | "param class_list_dict must be a list or a dictionary") |
| 257 | for classification in class_list_: |
| 258 | id = classification.pop('id') |
| 259 | name = classification.pop('name') |
| 260 | description = classification.pop('description') |
| 261 | project_id = classification.pop('project_id') |
| 262 | tenant_id = classification.pop('tenant_id') |
| 263 | original_classification = copy.deepcopy(classification) |
| 264 | classification.clear() |
| 265 | classification['ctype'] = 'legacy_flow_classifier' |
| 266 | classification['definition'] = original_classification |
| 267 | classification['id'] = id |
| 268 | classification['name'] = name |
| 269 | classification['description'] = description |
| 270 | classification['project_id'] = project_id |
| 271 | classification['tenant_id'] = tenant_id |
| 272 | |
| 273 | def __sfi_os2mano(self, sfi_list_dict): |
| 274 | """Transform the openstack format (Port Pair) to mano format (SFI) |
| 275 | sfi_list_dict can be a list of dict or a single dict |
| 276 | """ |
| 277 | if isinstance(sfi_list_dict, dict): |
| 278 | sfi_list_ = [sfi_list_dict] |
| 279 | elif isinstance(sfi_list_dict, list): |
| 280 | sfi_list_ = sfi_list_dict |
| 281 | else: |
| 282 | raise TypeError( |
| 283 | "param sfi_list_dict must be a list or a dictionary") |
| 284 | for sfi in sfi_list_: |
| 285 | sfi['ingress_ports'] = [] |
| 286 | sfi['egress_ports'] = [] |
| 287 | if sfi.get('ingress'): |
| 288 | sfi['ingress_ports'].append(sfi['ingress']) |
| 289 | if sfi.get('egress'): |
| 290 | sfi['egress_ports'].append(sfi['egress']) |
| 291 | del sfi['ingress'] |
| 292 | del sfi['egress'] |
| 293 | params = sfi.get('service_function_parameters') |
| 294 | sfc_encap = False |
| 295 | if params: |
| 296 | correlation = params.get('correlation') |
| 297 | if correlation: |
| 298 | sfc_encap = True |
| 299 | sfi['sfc_encap'] = sfc_encap |
| 300 | del sfi['service_function_parameters'] |
| 301 | |
| 302 | def __sf_os2mano(self, sf_list_dict): |
| 303 | """Transform the openstack format (Port Pair Group) to mano format (SF) |
| 304 | sf_list_dict can be a list of dict or a single dict |
| 305 | """ |
| 306 | if isinstance(sf_list_dict, dict): |
| 307 | sf_list_ = [sf_list_dict] |
| 308 | elif isinstance(sf_list_dict, list): |
| 309 | sf_list_ = sf_list_dict |
| 310 | else: |
| 311 | raise TypeError( |
| 312 | "param sf_list_dict must be a list or a dictionary") |
| 313 | for sf in sf_list_: |
| 314 | del sf['port_pair_group_parameters'] |
| 315 | sf['sfis'] = sf['port_pairs'] |
| 316 | del sf['port_pairs'] |
| 317 | |
| 318 | def __sfp_os2mano(self, sfp_list_dict): |
| 319 | """Transform the openstack format (Port Chain) to mano format (SFP) |
| 320 | sfp_list_dict can be a list of dict or a single dict |
| 321 | """ |
| 322 | if isinstance(sfp_list_dict, dict): |
| 323 | sfp_list_ = [sfp_list_dict] |
| 324 | elif isinstance(sfp_list_dict, list): |
| 325 | sfp_list_ = sfp_list_dict |
| 326 | else: |
| 327 | raise TypeError( |
| 328 | "param sfp_list_dict must be a list or a dictionary") |
| 329 | for sfp in sfp_list_: |
| 330 | params = sfp.pop('chain_parameters') |
| 331 | sfc_encap = False |
| 332 | if params: |
| 333 | correlation = params.get('correlation') |
| 334 | if correlation: |
| 335 | sfc_encap = True |
| 336 | sfp['sfc_encap'] = sfc_encap |
| 337 | sfp['spi'] = sfp.pop('chain_id') |
| 338 | sfp['classifications'] = sfp.pop('flow_classifiers') |
| 339 | sfp['service_functions'] = sfp.pop('port_pair_groups') |
| 340 | |
| 341 | # placeholder for now; read TODO note below |
| 342 | def _validate_classification(self, type, definition): |
| 343 | # only legacy_flow_classifier Type is supported at this point |
| 344 | return True |
| 345 | # TODO(igordcard): this method should be an abstract method of an |
| 346 | # abstract Classification class to be implemented by the specific |
| 347 | # Types. Also, abstract vimconnector should call the validation |
| 348 | # method before the implemented VIM connectors are called. |
| 349 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 350 | def _format_exception(self, exception): |
| 351 | '''Transform a keystone, nova, neutron exception into a vimconn exception''' |
| 352 | if isinstance(exception, (HTTPException, gl1Exceptions.HTTPException, gl1Exceptions.CommunicationError, |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 353 | ConnectionError, ksExceptions.ConnectionError, neExceptions.ConnectionFailed |
| 354 | )): |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 355 | raise vimconn.vimconnConnectionException(type(exception).__name__ + ": " + str(exception)) |
| 356 | elif isinstance(exception, (nvExceptions.ClientException, ksExceptions.ClientException, |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 357 | neExceptions.NeutronException, nvExceptions.BadRequest)): |
| 358 | raise vimconn.vimconnUnexpectedResponse(type(exception).__name__ + ": " + str(exception)) |
| 359 | elif isinstance(exception, (neExceptions.NetworkNotFoundClient, nvExceptions.NotFound)): |
| 360 | raise vimconn.vimconnNotFoundException(type(exception).__name__ + ": " + str(exception)) |
| 361 | elif isinstance(exception, nvExceptions.Conflict): |
| 362 | raise vimconn.vimconnConflictException(type(exception).__name__ + ": " + str(exception)) |
| Pablo Montes Moreno | 6a7785b | 2017-07-03 10:44:30 +0200 | [diff] [blame] | 363 | elif isinstance(exception, vimconn.vimconnException): |
| tierno | 41a6981 | 2018-02-16 14:34:33 +0100 | [diff] [blame] | 364 | raise exception |
| tierno | f716aea | 2017-06-21 18:01:40 +0200 | [diff] [blame] | 365 | else: # () |
| tierno | b84cbdc | 2017-07-07 14:30:30 +0200 | [diff] [blame] | 366 | self.logger.error("General Exception " + str(exception), exc_info=True) |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 367 | raise vimconn.vimconnConnectionException(type(exception).__name__ + ": " + str(exception)) |
| 368 | |
| 369 | def get_tenant_list(self, filter_dict={}): |
| 370 | '''Obtain tenants of VIM |
| 371 | filter_dict can contain the following keys: |
| 372 | name: filter by tenant name |
| 373 | id: filter by tenant uuid/id |
| 374 | <other VIM specific> |
| 375 | Returns the tenant list of dictionaries: [{'name':'<name>, 'id':'<id>, ...}, ...] |
| 376 | ''' |
| ahmadsa | 95baa27 | 2016-11-30 09:14:11 +0500 | [diff] [blame] | 377 | self.logger.debug("Getting tenants from VIM filter: '%s'", str(filter_dict)) |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 378 | try: |
| 379 | self._reload_connection() |
| tierno | f716aea | 2017-06-21 18:01:40 +0200 | [diff] [blame] | 380 | if self.api_version3: |
| 381 | project_class_list = self.keystone.projects.list(name=filter_dict.get("name")) |
| ahmadsa | 95baa27 | 2016-11-30 09:14:11 +0500 | [diff] [blame] | 382 | else: |
| tierno | f716aea | 2017-06-21 18:01:40 +0200 | [diff] [blame] | 383 | project_class_list = self.keystone.tenants.findall(**filter_dict) |
| ahmadsa | 95baa27 | 2016-11-30 09:14:11 +0500 | [diff] [blame] | 384 | project_list=[] |
| 385 | for project in project_class_list: |
| tierno | f716aea | 2017-06-21 18:01:40 +0200 | [diff] [blame] | 386 | if filter_dict.get('id') and filter_dict["id"] != project.id: |
| 387 | continue |
| ahmadsa | 95baa27 | 2016-11-30 09:14:11 +0500 | [diff] [blame] | 388 | project_list.append(project.to_dict()) |
| 389 | return project_list |
| tierno | f716aea | 2017-06-21 18:01:40 +0200 | [diff] [blame] | 390 | except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 391 | self._format_exception(e) |
| 392 | |
| 393 | def new_tenant(self, tenant_name, tenant_description): |
| 394 | '''Adds a new tenant to openstack VIM. Returns the tenant identifier''' |
| 395 | self.logger.debug("Adding a new tenant name: %s", tenant_name) |
| 396 | try: |
| 397 | self._reload_connection() |
| tierno | f716aea | 2017-06-21 18:01:40 +0200 | [diff] [blame] | 398 | if self.api_version3: |
| 399 | project = self.keystone.projects.create(tenant_name, self.config.get("project_domain_id", "default"), |
| 400 | description=tenant_description, is_domain=False) |
| ahmadsa | 95baa27 | 2016-11-30 09:14:11 +0500 | [diff] [blame] | 401 | else: |
| tierno | f716aea | 2017-06-21 18:01:40 +0200 | [diff] [blame] | 402 | project = self.keystone.tenants.create(tenant_name, tenant_description) |
| ahmadsa | 95baa27 | 2016-11-30 09:14:11 +0500 | [diff] [blame] | 403 | return project.id |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 404 | except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 405 | self._format_exception(e) |
| 406 | |
| 407 | def delete_tenant(self, tenant_id): |
| 408 | '''Delete a tenant from openstack VIM. Returns the old tenant identifier''' |
| 409 | self.logger.debug("Deleting tenant %s from VIM", tenant_id) |
| 410 | try: |
| 411 | self._reload_connection() |
| tierno | f716aea | 2017-06-21 18:01:40 +0200 | [diff] [blame] | 412 | if self.api_version3: |
| ahmadsa | 95baa27 | 2016-11-30 09:14:11 +0500 | [diff] [blame] | 413 | self.keystone.projects.delete(tenant_id) |
| 414 | else: |
| 415 | self.keystone.tenants.delete(tenant_id) |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 416 | return tenant_id |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 417 | except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 418 | self._format_exception(e) |
| ahmadsa | 95baa27 | 2016-11-30 09:14:11 +0500 | [diff] [blame] | 419 | |
| garciadeblas | 9f8456e | 2016-09-05 05:02:59 +0200 | [diff] [blame] | 420 | def new_network(self,net_name, net_type, ip_profile=None, shared=False, vlan=None): |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 421 | '''Adds a tenant network to VIM. Returns the network identifier''' |
| 422 | self.logger.debug("Adding a new network to VIM name '%s', type '%s'", net_name, net_type) |
| garciadeblas | edca7b3 | 2016-09-29 14:01:52 +0000 | [diff] [blame] | 423 | #self.logger.debug(">>>>>>>>>>>>>>>>>> IP profile %s", str(ip_profile)) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 424 | try: |
| garciadeblas | edca7b3 | 2016-09-29 14:01:52 +0000 | [diff] [blame] | 425 | new_net = None |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 426 | self._reload_connection() |
| 427 | network_dict = {'name': net_name, 'admin_state_up': True} |
| 428 | if net_type=="data" or net_type=="ptp": |
| 429 | if self.config.get('dataplane_physical_net') == None: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 430 | raise vimconn.vimconnConflictException("You must provide a 'dataplane_physical_net' at config value before creating sriov network") |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 431 | network_dict["provider:physical_network"] = self.config['dataplane_physical_net'] #"physnet_sriov" #TODO physical |
| 432 | network_dict["provider:network_type"] = "vlan" |
| 433 | if vlan!=None: |
| 434 | network_dict["provider:network_type"] = vlan |
| kate | 721d79b | 2017-06-24 04:21:38 -0700 | [diff] [blame] | 435 | |
| 436 | ####### VIO Specific Changes ######### |
| 437 | if self.vim_type == "VIO": |
| 438 | if vlan is not None: |
| 439 | network_dict["provider:segmentation_id"] = vlan |
| 440 | else: |
| 441 | if self.config.get('dataplane_net_vlan_range') is None: |
| 442 | raise vimconn.vimconnConflictException("You must provide "\ |
| 443 | "'dataplane_net_vlan_range' in format [start_ID - end_ID]"\ |
| 444 | "at config value before creating sriov network with vlan tag") |
| 445 | |
| 446 | network_dict["provider:segmentation_id"] = self._genrate_vlanID() |
| 447 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 448 | network_dict["shared"]=shared |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 449 | new_net=self.neutron.create_network({'network':network_dict}) |
| 450 | #print new_net |
| garciadeblas | 9f8456e | 2016-09-05 05:02:59 +0200 | [diff] [blame] | 451 | #create subnetwork, even if there is no profile |
| 452 | if not ip_profile: |
| 453 | ip_profile = {} |
| tierno | 41a6981 | 2018-02-16 14:34:33 +0100 | [diff] [blame] | 454 | if not ip_profile.get('subnet_address'): |
| garciadeblas | 2299e3b | 2017-01-26 14:35:55 +0000 | [diff] [blame] | 455 | #Fake subnet is required |
| 456 | subnet_rand = random.randint(0, 255) |
| 457 | ip_profile['subnet_address'] = "192.168.{}.0/24".format(subnet_rand) |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 458 | if 'ip_version' not in ip_profile: |
| garciadeblas | 9f8456e | 2016-09-05 05:02:59 +0200 | [diff] [blame] | 459 | ip_profile['ip_version'] = "IPv4" |
| tierno | a1fb446 | 2017-06-30 12:25:50 +0200 | [diff] [blame] | 460 | subnet = {"name":net_name+"-subnet", |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 461 | "network_id": new_net["network"]["id"], |
| garciadeblas | 9f8456e | 2016-09-05 05:02:59 +0200 | [diff] [blame] | 462 | "ip_version": 4 if ip_profile['ip_version']=="IPv4" else 6, |
| 463 | "cidr": ip_profile['subnet_address'] |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 464 | } |
| tierno | a1fb446 | 2017-06-30 12:25:50 +0200 | [diff] [blame] | 465 | # Gateway should be set to None if not needed. Otherwise openstack assigns one by default |
| tierno | 41a6981 | 2018-02-16 14:34:33 +0100 | [diff] [blame] | 466 | if ip_profile.get('gateway_address'): |
| 467 | subnet['gateway_ip'] = ip_profile.get('gateway_address') |
| garciadeblas | edca7b3 | 2016-09-29 14:01:52 +0000 | [diff] [blame] | 468 | if ip_profile.get('dns_address'): |
| tierno | 455612d | 2017-05-30 16:40:10 +0200 | [diff] [blame] | 469 | subnet['dns_nameservers'] = ip_profile['dns_address'].split(";") |
| garciadeblas | 9f8456e | 2016-09-05 05:02:59 +0200 | [diff] [blame] | 470 | if 'dhcp_enabled' in ip_profile: |
| tierno | 41a6981 | 2018-02-16 14:34:33 +0100 | [diff] [blame] | 471 | subnet['enable_dhcp'] = False if \ |
| 472 | ip_profile['dhcp_enabled']=="false" or ip_profile['dhcp_enabled']==False else True |
| 473 | if ip_profile.get('dhcp_start_address'): |
| tierno | a1fb446 | 2017-06-30 12:25:50 +0200 | [diff] [blame] | 474 | subnet['allocation_pools'] = [] |
| garciadeblas | 9f8456e | 2016-09-05 05:02:59 +0200 | [diff] [blame] | 475 | subnet['allocation_pools'].append(dict()) |
| 476 | subnet['allocation_pools'][0]['start'] = ip_profile['dhcp_start_address'] |
| tierno | 41a6981 | 2018-02-16 14:34:33 +0100 | [diff] [blame] | 477 | if ip_profile.get('dhcp_count'): |
| garciadeblas | 9f8456e | 2016-09-05 05:02:59 +0200 | [diff] [blame] | 478 | #parts = ip_profile['dhcp_start_address'].split('.') |
| 479 | #ip_int = (int(parts[0]) << 24) + (int(parts[1]) << 16) + (int(parts[2]) << 8) + int(parts[3]) |
| 480 | ip_int = int(netaddr.IPAddress(ip_profile['dhcp_start_address'])) |
| garciadeblas | 21d795b | 2016-09-29 17:31:46 +0200 | [diff] [blame] | 481 | ip_int += ip_profile['dhcp_count'] - 1 |
| garciadeblas | 9f8456e | 2016-09-05 05:02:59 +0200 | [diff] [blame] | 482 | ip_str = str(netaddr.IPAddress(ip_int)) |
| 483 | subnet['allocation_pools'][0]['end'] = ip_str |
| garciadeblas | edca7b3 | 2016-09-29 14:01:52 +0000 | [diff] [blame] | 484 | #self.logger.debug(">>>>>>>>>>>>>>>>>> Subnet: %s", str(subnet)) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 485 | self.neutron.create_subnet({"subnet": subnet} ) |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 486 | return new_net["network"]["id"] |
| tierno | 41a6981 | 2018-02-16 14:34:33 +0100 | [diff] [blame] | 487 | except Exception as e: |
| garciadeblas | edca7b3 | 2016-09-29 14:01:52 +0000 | [diff] [blame] | 488 | if new_net: |
| 489 | self.neutron.delete_network(new_net['network']['id']) |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 490 | self._format_exception(e) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 491 | |
| 492 | def get_network_list(self, filter_dict={}): |
| 493 | '''Obtain tenant networks of VIM |
| 494 | Filter_dict can be: |
| 495 | name: network name |
| 496 | id: network uuid |
| 497 | shared: boolean |
| 498 | tenant_id: tenant |
| 499 | admin_state_up: boolean |
| 500 | status: 'ACTIVE' |
| 501 | Returns the network list of dictionaries |
| 502 | ''' |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 503 | self.logger.debug("Getting network from VIM filter: '%s'", str(filter_dict)) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 504 | try: |
| 505 | self._reload_connection() |
| tierno | 69b590e | 2018-03-13 18:52:23 +0100 | [diff] [blame] | 506 | filter_dict_os = filter_dict.copy() |
| 507 | if self.api_version3 and "tenant_id" in filter_dict_os: |
| 508 | filter_dict_os['project_id'] = filter_dict_os.pop('tenant_id') #T ODO check |
| 509 | net_dict = self.neutron.list_networks(**filter_dict_os) |
| tierno | 00e3df7 | 2017-11-29 17:20:13 +0100 | [diff] [blame] | 510 | net_list = net_dict["networks"] |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 511 | self.__net_os2mano(net_list) |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 512 | return net_list |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 513 | except (neExceptions.ConnectionFailed, ksExceptions.ClientException, neExceptions.NeutronException, ConnectionError) as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 514 | self._format_exception(e) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 515 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 516 | def get_network(self, net_id): |
| 517 | '''Obtain details of network from VIM |
| 518 | Returns the network information from a network id''' |
| 519 | self.logger.debug(" Getting tenant network %s from VIM", net_id) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 520 | filter_dict={"id": net_id} |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 521 | net_list = self.get_network_list(filter_dict) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 522 | if len(net_list)==0: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 523 | raise vimconn.vimconnNotFoundException("Network '{}' not found".format(net_id)) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 524 | elif len(net_list)>1: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 525 | raise vimconn.vimconnConflictException("Found more than one network with this criteria") |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 526 | net = net_list[0] |
| 527 | subnets=[] |
| 528 | for subnet_id in net.get("subnets", () ): |
| 529 | try: |
| 530 | subnet = self.neutron.show_subnet(subnet_id) |
| 531 | except Exception as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 532 | self.logger.error("osconnector.get_network(): Error getting subnet %s %s" % (net_id, str(e))) |
| 533 | subnet = {"id": subnet_id, "fault": str(e)} |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 534 | subnets.append(subnet) |
| 535 | net["subnets"] = subnets |
| Pablo Montes Moreno | 51e553b | 2017-03-23 16:39:12 +0100 | [diff] [blame] | 536 | net["encapsulation"] = net.get('provider:network_type') |
| Pablo Montes Moreno | 3fbff9b | 2017-03-08 11:28:15 +0100 | [diff] [blame] | 537 | net["segmentation_id"] = net.get('provider:segmentation_id') |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 538 | return net |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 539 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 540 | def delete_network(self, net_id): |
| 541 | '''Deletes a tenant network from VIM. Returns the old network identifier''' |
| 542 | self.logger.debug("Deleting network '%s' from VIM", net_id) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 543 | try: |
| 544 | self._reload_connection() |
| 545 | #delete VM ports attached to this networks before the network |
| 546 | ports = self.neutron.list_ports(network_id=net_id) |
| 547 | for p in ports['ports']: |
| 548 | try: |
| 549 | self.neutron.delete_port(p["id"]) |
| 550 | except Exception as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 551 | self.logger.error("Error deleting port %s: %s", p["id"], str(e)) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 552 | self.neutron.delete_network(net_id) |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 553 | return net_id |
| 554 | except (neExceptions.ConnectionFailed, neExceptions.NetworkNotFoundClient, neExceptions.NeutronException, |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 555 | ksExceptions.ClientException, neExceptions.NeutronException, ConnectionError) as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 556 | self._format_exception(e) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 557 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 558 | def refresh_nets_status(self, net_list): |
| 559 | '''Get the status of the networks |
| 560 | Params: the list of network identifiers |
| 561 | Returns a dictionary with: |
| 562 | net_id: #VIM id of this network |
| 563 | status: #Mandatory. Text with one of: |
| 564 | # DELETED (not found at vim) |
| 565 | # VIM_ERROR (Cannot connect to VIM, VIM response error, ...) |
| 566 | # OTHER (Vim reported other status not understood) |
| 567 | # ERROR (VIM indicates an ERROR status) |
| 568 | # ACTIVE, INACTIVE, DOWN (admin down), |
| 569 | # BUILD (on building process) |
| 570 | # |
| 571 | error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR |
| 572 | vim_info: #Text with plain information obtained from vim (yaml.safe_dump) |
| 573 | |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 574 | ''' |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 575 | net_dict={} |
| 576 | for net_id in net_list: |
| 577 | net = {} |
| 578 | try: |
| 579 | net_vim = self.get_network(net_id) |
| 580 | if net_vim['status'] in netStatus2manoFormat: |
| 581 | net["status"] = netStatus2manoFormat[ net_vim['status'] ] |
| 582 | else: |
| 583 | net["status"] = "OTHER" |
| 584 | net["error_msg"] = "VIM status reported " + net_vim['status'] |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 585 | |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 586 | if net['status'] == "ACTIVE" and not net_vim['admin_state_up']: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 587 | net['status'] = 'DOWN' |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 588 | try: |
| 589 | net['vim_info'] = yaml.safe_dump(net_vim, default_flow_style=True, width=256) |
| 590 | except yaml.representer.RepresenterError: |
| 591 | net['vim_info'] = str(net_vim) |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 592 | if net_vim.get('fault'): #TODO |
| 593 | net['error_msg'] = str(net_vim['fault']) |
| 594 | except vimconn.vimconnNotFoundException as e: |
| 595 | self.logger.error("Exception getting net status: %s", str(e)) |
| 596 | net['status'] = "DELETED" |
| 597 | net['error_msg'] = str(e) |
| 598 | except vimconn.vimconnException as e: |
| 599 | self.logger.error("Exception getting net status: %s", str(e)) |
| 600 | net['status'] = "VIM_ERROR" |
| 601 | net['error_msg'] = str(e) |
| 602 | net_dict[net_id] = net |
| 603 | return net_dict |
| 604 | |
| 605 | def get_flavor(self, flavor_id): |
| 606 | '''Obtain flavor details from the VIM. Returns the flavor dict details''' |
| 607 | self.logger.debug("Getting flavor '%s'", flavor_id) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 608 | try: |
| 609 | self._reload_connection() |
| 610 | flavor = self.nova.flavors.find(id=flavor_id) |
| 611 | #TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema) |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 612 | return flavor.to_dict() |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 613 | except (nvExceptions.NotFound, nvExceptions.ClientException, ksExceptions.ClientException, ConnectionError) as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 614 | self._format_exception(e) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 615 | |
| tierno | cf157a8 | 2017-01-30 14:07:06 +0100 | [diff] [blame] | 616 | def get_flavor_id_from_data(self, flavor_dict): |
| 617 | """Obtain flavor id that match the flavor description |
| 618 | Returns the flavor_id or raises a vimconnNotFoundException |
| tierno | e26fc7a | 2017-05-30 14:43:03 +0200 | [diff] [blame] | 619 | flavor_dict: contains the required ram, vcpus, disk |
| 620 | If 'use_existing_flavors' is set to True at config, the closer flavor that provides same or more ram, vcpus |
| 621 | and disk is returned. Otherwise a flavor with exactly same ram, vcpus and disk is returned or a |
| 622 | vimconnNotFoundException is raised |
| tierno | cf157a8 | 2017-01-30 14:07:06 +0100 | [diff] [blame] | 623 | """ |
| tierno | e26fc7a | 2017-05-30 14:43:03 +0200 | [diff] [blame] | 624 | exact_match = False if self.config.get('use_existing_flavors') else True |
| tierno | cf157a8 | 2017-01-30 14:07:06 +0100 | [diff] [blame] | 625 | try: |
| 626 | self._reload_connection() |
| tierno | e26fc7a | 2017-05-30 14:43:03 +0200 | [diff] [blame] | 627 | flavor_candidate_id = None |
| 628 | flavor_candidate_data = (10000, 10000, 10000) |
| 629 | flavor_target = (flavor_dict["ram"], flavor_dict["vcpus"], flavor_dict["disk"]) |
| 630 | # numa=None |
| 631 | numas = flavor_dict.get("extended", {}).get("numas") |
| tierno | cf157a8 | 2017-01-30 14:07:06 +0100 | [diff] [blame] | 632 | if numas: |
| 633 | #TODO |
| 634 | raise vimconn.vimconnNotFoundException("Flavor with EPA still not implemted") |
| 635 | # if len(numas) > 1: |
| 636 | # raise vimconn.vimconnNotFoundException("Cannot find any flavor with more than one numa") |
| 637 | # numa=numas[0] |
| 638 | # numas = extended.get("numas") |
| 639 | for flavor in self.nova.flavors.list(): |
| 640 | epa = flavor.get_keys() |
| 641 | if epa: |
| 642 | continue |
| tierno | e26fc7a | 2017-05-30 14:43:03 +0200 | [diff] [blame] | 643 | # TODO |
| 644 | flavor_data = (flavor.ram, flavor.vcpus, flavor.disk) |
| 645 | if flavor_data == flavor_target: |
| 646 | return flavor.id |
| 647 | elif not exact_match and flavor_target < flavor_data < flavor_candidate_data: |
| 648 | flavor_candidate_id = flavor.id |
| 649 | flavor_candidate_data = flavor_data |
| 650 | if not exact_match and flavor_candidate_id: |
| 651 | return flavor_candidate_id |
| tierno | cf157a8 | 2017-01-30 14:07:06 +0100 | [diff] [blame] | 652 | raise vimconn.vimconnNotFoundException("Cannot find any flavor matching '{}'".format(str(flavor_dict))) |
| 653 | except (nvExceptions.NotFound, nvExceptions.ClientException, ksExceptions.ClientException, ConnectionError) as e: |
| 654 | self._format_exception(e) |
| 655 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 656 | def new_flavor(self, flavor_data, change_name_if_used=True): |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 657 | '''Adds a tenant flavor to openstack VIM |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 658 | if change_name_if_used is True, it will change name in case of conflict, because it is not supported name repetition |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 659 | Returns the flavor identifier |
| 660 | ''' |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 661 | self.logger.debug("Adding flavor '%s'", str(flavor_data)) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 662 | retry=0 |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 663 | max_retries=3 |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 664 | name_suffix = 0 |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 665 | name=flavor_data['name'] |
| 666 | while retry<max_retries: |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 667 | retry+=1 |
| 668 | try: |
| 669 | self._reload_connection() |
| 670 | if change_name_if_used: |
| 671 | #get used names |
| 672 | fl_names=[] |
| 673 | fl=self.nova.flavors.list() |
| 674 | for f in fl: |
| 675 | fl_names.append(f.name) |
| 676 | while name in fl_names: |
| 677 | name_suffix += 1 |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 678 | name = flavor_data['name']+"-" + str(name_suffix) |
| kate | 721d79b | 2017-06-24 04:21:38 -0700 | [diff] [blame] | 679 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 680 | ram = flavor_data.get('ram',64) |
| 681 | vcpus = flavor_data.get('vcpus',1) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 682 | numa_properties=None |
| 683 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 684 | extended = flavor_data.get("extended") |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 685 | if extended: |
| 686 | numas=extended.get("numas") |
| 687 | if numas: |
| 688 | numa_nodes = len(numas) |
| 689 | if numa_nodes > 1: |
| 690 | return -1, "Can not add flavor with more than one numa" |
| 691 | numa_properties = {"hw:numa_nodes":str(numa_nodes)} |
| 692 | numa_properties["hw:mem_page_size"] = "large" |
| 693 | numa_properties["hw:cpu_policy"] = "dedicated" |
| 694 | numa_properties["hw:numa_mempolicy"] = "strict" |
| kate | 721d79b | 2017-06-24 04:21:38 -0700 | [diff] [blame] | 695 | if self.vim_type == "VIO": |
| 696 | numa_properties["vmware:extra_config"] = '{"numa.nodeAffinity":"0"}' |
| 697 | numa_properties["vmware:latency_sensitivity_level"] = "high" |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 698 | for numa in numas: |
| 699 | #overwrite ram and vcpus |
| dhumal | ae3b28d | 2017-11-22 21:41:41 -0800 | [diff] [blame] | 700 | #check if key 'memory' is present in numa else use ram value at flavor |
| 701 | if 'memory' in numa: |
| 702 | ram = numa['memory']*1024 |
| Pablo Montes Moreno | ea1d623 | 2017-05-24 11:33:24 +0200 | [diff] [blame] | 703 | #See for reference: https://specs.openstack.org/openstack/nova-specs/specs/mitaka/implemented/virt-driver-cpu-thread-pinning.html |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 704 | if 'paired-threads' in numa: |
| 705 | vcpus = numa['paired-threads']*2 |
| Pablo Montes Moreno | ea1d623 | 2017-05-24 11:33:24 +0200 | [diff] [blame] | 706 | #cpu_thread_policy "require" implies that the compute node must have an STM architecture |
| 707 | numa_properties["hw:cpu_thread_policy"] = "require" |
| 708 | numa_properties["hw:cpu_policy"] = "dedicated" |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 709 | elif 'cores' in numa: |
| 710 | vcpus = numa['cores'] |
| Pablo Montes Moreno | ea1d623 | 2017-05-24 11:33:24 +0200 | [diff] [blame] | 711 | # cpu_thread_policy "prefer" implies that the host must not have an SMT architecture, or a non-SMT architecture will be emulated |
| 712 | numa_properties["hw:cpu_thread_policy"] = "isolate" |
| 713 | numa_properties["hw:cpu_policy"] = "dedicated" |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 714 | elif 'threads' in numa: |
| 715 | vcpus = numa['threads'] |
| Pablo Montes Moreno | ea1d623 | 2017-05-24 11:33:24 +0200 | [diff] [blame] | 716 | # cpu_thread_policy "prefer" implies that the host may or may not have an SMT architecture |
| 717 | numa_properties["hw:cpu_thread_policy"] = "prefer" |
| 718 | numa_properties["hw:cpu_policy"] = "dedicated" |
| Pablo Montes Moreno | 3be0b2a | 2017-03-30 13:22:15 +0200 | [diff] [blame] | 719 | # for interface in numa.get("interfaces",() ): |
| 720 | # if interface["dedicated"]=="yes": |
| 721 | # raise vimconn.vimconnException("Passthrough interfaces are not supported for the openstack connector", http_code=vimconn.HTTP_Service_Unavailable) |
| 722 | # #TODO, add the key 'pci_passthrough:alias"="<label at config>:<number ifaces>"' when a way to connect it is available |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 723 | |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 724 | #create flavor |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 725 | new_flavor=self.nova.flavors.create(name, |
| 726 | ram, |
| 727 | vcpus, |
| garciadeblas | 79d1a1a | 2017-12-11 16:07:07 +0100 | [diff] [blame] | 728 | flavor_data.get('disk',0), |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 729 | is_public=flavor_data.get('is_public', True) |
| kate | 721d79b | 2017-06-24 04:21:38 -0700 | [diff] [blame] | 730 | ) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 731 | #add metadata |
| 732 | if numa_properties: |
| 733 | new_flavor.set_keys(numa_properties) |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 734 | return new_flavor.id |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 735 | except nvExceptions.Conflict as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 736 | if change_name_if_used and retry < max_retries: |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 737 | continue |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 738 | self._format_exception(e) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 739 | #except nvExceptions.BadRequest as e: |
| 740 | except (ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 741 | self._format_exception(e) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 742 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 743 | def delete_flavor(self,flavor_id): |
| 744 | '''Deletes a tenant flavor from openstack VIM. Returns the old flavor_id |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 745 | ''' |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 746 | try: |
| 747 | self._reload_connection() |
| 748 | self.nova.flavors.delete(flavor_id) |
| 749 | return flavor_id |
| 750 | #except nvExceptions.BadRequest as e: |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 751 | except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 752 | self._format_exception(e) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 753 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 754 | def new_image(self,image_dict): |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 755 | ''' |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 756 | Adds a tenant image to VIM. imge_dict is a dictionary with: |
| 757 | name: name |
| 758 | disk_format: qcow2, vhd, vmdk, raw (by default), ... |
| 759 | location: path or URI |
| 760 | public: "yes" or "no" |
| 761 | metadata: metadata of the image |
| 762 | Returns the image_id |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 763 | ''' |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 764 | retry=0 |
| 765 | max_retries=3 |
| 766 | while retry<max_retries: |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 767 | retry+=1 |
| 768 | try: |
| 769 | self._reload_connection() |
| 770 | #determine format http://docs.openstack.org/developer/glance/formats.html |
| 771 | if "disk_format" in image_dict: |
| 772 | disk_format=image_dict["disk_format"] |
| garciadeblas | 1448045 | 2017-01-10 13:08:07 +0100 | [diff] [blame] | 773 | else: #autodiscover based on extension |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 774 | if image_dict['location'][-6:]==".qcow2": |
| 775 | disk_format="qcow2" |
| 776 | elif image_dict['location'][-4:]==".vhd": |
| 777 | disk_format="vhd" |
| 778 | elif image_dict['location'][-5:]==".vmdk": |
| 779 | disk_format="vmdk" |
| 780 | elif image_dict['location'][-4:]==".vdi": |
| 781 | disk_format="vdi" |
| 782 | elif image_dict['location'][-4:]==".iso": |
| 783 | disk_format="iso" |
| 784 | elif image_dict['location'][-4:]==".aki": |
| 785 | disk_format="aki" |
| 786 | elif image_dict['location'][-4:]==".ari": |
| 787 | disk_format="ari" |
| 788 | elif image_dict['location'][-4:]==".ami": |
| 789 | disk_format="ami" |
| 790 | else: |
| 791 | disk_format="raw" |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 792 | self.logger.debug("new_image: '%s' loading from '%s'", image_dict['name'], image_dict['location']) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 793 | if image_dict['location'][0:4]=="http": |
| tierno | b39d49e | 2017-08-02 14:02:15 +0200 | [diff] [blame] | 794 | new_image = self.glancev1.images.create(name=image_dict['name'], is_public=image_dict.get('public',"yes")=="yes", |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 795 | container_format="bare", location=image_dict['location'], disk_format=disk_format) |
| 796 | else: #local path |
| 797 | with open(image_dict['location']) as fimage: |
| tierno | b39d49e | 2017-08-02 14:02:15 +0200 | [diff] [blame] | 798 | new_image = self.glancev1.images.create(name=image_dict['name'], is_public=image_dict.get('public',"yes")=="yes", |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 799 | container_format="bare", data=fimage, disk_format=disk_format) |
| 800 | #insert metadata. We cannot use 'new_image.properties.setdefault' |
| 801 | #because nova and glance are "INDEPENDENT" and we are using nova for reading metadata |
| 802 | new_image_nova=self.nova.images.find(id=new_image.id) |
| 803 | new_image_nova.metadata.setdefault('location',image_dict['location']) |
| 804 | metadata_to_load = image_dict.get('metadata') |
| 805 | if metadata_to_load: |
| 806 | for k,v in yaml.load(metadata_to_load).iteritems(): |
| 807 | new_image_nova.metadata.setdefault(k,v) |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 808 | return new_image.id |
| 809 | except (nvExceptions.Conflict, ksExceptions.ClientException, nvExceptions.ClientException) as e: |
| 810 | self._format_exception(e) |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 811 | except (HTTPException, gl1Exceptions.HTTPException, gl1Exceptions.CommunicationError, ConnectionError) as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 812 | if retry==max_retries: |
| 813 | continue |
| 814 | self._format_exception(e) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 815 | except IOError as e: #can not open the file |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 816 | raise vimconn.vimconnConnectionException(type(e).__name__ + ": " + str(e)+ " for " + image_dict['location'], |
| 817 | http_code=vimconn.HTTP_Bad_Request) |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 818 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 819 | def delete_image(self, image_id): |
| 820 | '''Deletes a tenant image from openstack VIM. Returns the old id |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 821 | ''' |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 822 | try: |
| 823 | self._reload_connection() |
| 824 | self.nova.images.delete(image_id) |
| 825 | return image_id |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 826 | except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e: #TODO remove |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 827 | self._format_exception(e) |
| 828 | |
| 829 | def get_image_id_from_path(self, path): |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 830 | '''Get the image id from image path in the VIM database. Returns the image_id''' |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 831 | try: |
| 832 | self._reload_connection() |
| 833 | images = self.nova.images.list() |
| 834 | for image in images: |
| 835 | if image.metadata.get("location")==path: |
| 836 | return image.id |
| 837 | raise vimconn.vimconnNotFoundException("image with location '{}' not found".format( path)) |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 838 | except (ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 839 | self._format_exception(e) |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 840 | |
| garciadeblas | b69fa9f | 2016-09-28 12:04:10 +0200 | [diff] [blame] | 841 | def get_image_list(self, filter_dict={}): |
| 842 | '''Obtain tenant images from VIM |
| 843 | Filter_dict can be: |
| 844 | id: image id |
| 845 | name: image name |
| 846 | checksum: image checksum |
| 847 | Returns the image list of dictionaries: |
| 848 | [{<the fields at Filter_dict plus some VIM specific>}, ...] |
| 849 | List can be empty |
| 850 | ''' |
| 851 | self.logger.debug("Getting image list from VIM filter: '%s'", str(filter_dict)) |
| 852 | try: |
| 853 | self._reload_connection() |
| tierno | 69b590e | 2018-03-13 18:52:23 +0100 | [diff] [blame] | 854 | filter_dict_os = filter_dict.copy() |
| garciadeblas | b69fa9f | 2016-09-28 12:04:10 +0200 | [diff] [blame] | 855 | #First we filter by the available filter fields: name, id. The others are removed. |
| tierno | 69b590e | 2018-03-13 18:52:23 +0100 | [diff] [blame] | 856 | filter_dict_os.pop('checksum', None) |
| tierno | 3cb8dc3 | 2017-10-24 18:13:19 +0200 | [diff] [blame] | 857 | image_list = self.nova.images.findall(**filter_dict_os) |
| 858 | if len(image_list) == 0: |
| garciadeblas | b69fa9f | 2016-09-28 12:04:10 +0200 | [diff] [blame] | 859 | return [] |
| 860 | #Then we filter by the rest of filter fields: checksum |
| 861 | filtered_list = [] |
| 862 | for image in image_list: |
| tierno | 3cb8dc3 | 2017-10-24 18:13:19 +0200 | [diff] [blame] | 863 | try: |
| 864 | image_class = self.glance.images.get(image.id) |
| tierno | 69b590e | 2018-03-13 18:52:23 +0100 | [diff] [blame] | 865 | if 'checksum' not in filter_dict or image_class['checksum'] == filter_dict.get('checksum'): |
| tierno | 3cb8dc3 | 2017-10-24 18:13:19 +0200 | [diff] [blame] | 866 | filtered_list.append(image_class.copy()) |
| 867 | except gl1Exceptions.HTTPNotFound: |
| 868 | pass |
| garciadeblas | b69fa9f | 2016-09-28 12:04:10 +0200 | [diff] [blame] | 869 | return filtered_list |
| 870 | except (ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e: |
| 871 | self._format_exception(e) |
| 872 | |
| Pablo Montes Moreno | 6a7785b | 2017-07-03 10:44:30 +0200 | [diff] [blame] | 873 | def __wait_for_vm(self, vm_id, status): |
| 874 | """wait until vm is in the desired status and return True. |
| 875 | If the VM gets in ERROR status, return false. |
| 876 | If the timeout is reached generate an exception""" |
| 877 | elapsed_time = 0 |
| 878 | while elapsed_time < server_timeout: |
| 879 | vm_status = self.nova.servers.get(vm_id).status |
| 880 | if vm_status == status: |
| 881 | return True |
| 882 | if vm_status == 'ERROR': |
| 883 | return False |
| 884 | time.sleep(1) |
| 885 | elapsed_time += 1 |
| 886 | |
| 887 | # if we exceeded the timeout rollback |
| 888 | if elapsed_time >= server_timeout: |
| 889 | raise vimconn.vimconnException('Timeout waiting for instance ' + vm_id + ' to get ' + status, |
| 890 | http_code=vimconn.HTTP_Request_Timeout) |
| 891 | |
| mirabal | 2935631 | 2017-07-27 12:21:22 +0200 | [diff] [blame] | 892 | def _get_openstack_availablity_zones(self): |
| 893 | """ |
| 894 | Get from openstack availability zones available |
| 895 | :return: |
| 896 | """ |
| 897 | try: |
| 898 | openstack_availability_zone = self.nova.availability_zones.list() |
| 899 | openstack_availability_zone = [str(zone.zoneName) for zone in openstack_availability_zone |
| 900 | if zone.zoneName != 'internal'] |
| 901 | return openstack_availability_zone |
| 902 | except Exception as e: |
| 903 | return None |
| 904 | |
| 905 | def _set_availablity_zones(self): |
| 906 | """ |
| 907 | Set vim availablity zone |
| 908 | :return: |
| 909 | """ |
| 910 | |
| 911 | if 'availability_zone' in self.config: |
| 912 | vim_availability_zones = self.config.get('availability_zone') |
| 913 | if isinstance(vim_availability_zones, str): |
| 914 | self.availability_zone = [vim_availability_zones] |
| 915 | elif isinstance(vim_availability_zones, list): |
| 916 | self.availability_zone = vim_availability_zones |
| 917 | else: |
| 918 | self.availability_zone = self._get_openstack_availablity_zones() |
| 919 | |
| tierno | 5a3273c | 2017-08-29 11:43:46 +0200 | [diff] [blame] | 920 | def _get_vm_availability_zone(self, availability_zone_index, availability_zone_list): |
| mirabal | 2935631 | 2017-07-27 12:21:22 +0200 | [diff] [blame] | 921 | """ |
| tierno | 5a3273c | 2017-08-29 11:43:46 +0200 | [diff] [blame] | 922 | Return thge availability zone to be used by the created VM. |
| 923 | :return: The VIM availability zone to be used or None |
| mirabal | 2935631 | 2017-07-27 12:21:22 +0200 | [diff] [blame] | 924 | """ |
| tierno | 5a3273c | 2017-08-29 11:43:46 +0200 | [diff] [blame] | 925 | if availability_zone_index is None: |
| 926 | if not self.config.get('availability_zone'): |
| 927 | return None |
| 928 | elif isinstance(self.config.get('availability_zone'), str): |
| 929 | return self.config['availability_zone'] |
| 930 | else: |
| 931 | # TODO consider using a different parameter at config for default AV and AV list match |
| 932 | return self.config['availability_zone'][0] |
| mirabal | 2935631 | 2017-07-27 12:21:22 +0200 | [diff] [blame] | 933 | |
| tierno | 5a3273c | 2017-08-29 11:43:46 +0200 | [diff] [blame] | 934 | vim_availability_zones = self.availability_zone |
| 935 | # check if VIM offer enough availability zones describe in the VNFD |
| 936 | if vim_availability_zones and len(availability_zone_list) <= len(vim_availability_zones): |
| 937 | # check if all the names of NFV AV match VIM AV names |
| 938 | match_by_index = False |
| 939 | for av in availability_zone_list: |
| 940 | if av not in vim_availability_zones: |
| 941 | match_by_index = True |
| 942 | break |
| 943 | if match_by_index: |
| 944 | return vim_availability_zones[availability_zone_index] |
| 945 | else: |
| 946 | return availability_zone_list[availability_zone_index] |
| mirabal | 2935631 | 2017-07-27 12:21:22 +0200 | [diff] [blame] | 947 | else: |
| tierno | 5a3273c | 2017-08-29 11:43:46 +0200 | [diff] [blame] | 948 | raise vimconn.vimconnConflictException("No enough availability zones at VIM for this deployment") |
| mirabal | 2935631 | 2017-07-27 12:21:22 +0200 | [diff] [blame] | 949 | |
| tierno | 5a3273c | 2017-08-29 11:43:46 +0200 | [diff] [blame] | 950 | def new_vminstance(self, name, description, start, image_id, flavor_id, net_list, cloud_config=None, disk_list=None, |
| 951 | availability_zone_index=None, availability_zone_list=None): |
| tierno | 98e909c | 2017-10-14 13:27:03 +0200 | [diff] [blame] | 952 | """Adds a VM instance to VIM |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 953 | Params: |
| 954 | start: indicates if VM must start or boot in pause mode. Ignored |
| 955 | image_id,flavor_id: iamge and flavor uuid |
| 956 | net_list: list of interfaces, each one is a dictionary with: |
| 957 | name: |
| 958 | net_id: network uuid to connect |
| 959 | vpci: virtual vcpi to assign, ignored because openstack lack #TODO |
| 960 | model: interface model, ignored #TODO |
| 961 | mac_address: used for SR-IOV ifaces #TODO for other types |
| 962 | use: 'data', 'bridge', 'mgmt' |
| tierno | 66eba6e | 2017-11-10 17:09:18 +0100 | [diff] [blame] | 963 | type: 'virtual', 'PCI-PASSTHROUGH'('PF'), 'SR-IOV'('VF'), 'VFnotShared' |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 964 | vim_id: filled/added by this function |
| ahmadsa | f853d45 | 2016-12-22 11:33:47 +0500 | [diff] [blame] | 965 | floating_ip: True/False (or it can be None) |
| tierno | 41a6981 | 2018-02-16 14:34:33 +0100 | [diff] [blame] | 966 | 'cloud_config': (optional) dictionary with: |
| 967 | 'key-pairs': (optional) list of strings with the public key to be inserted to the default user |
| 968 | 'users': (optional) list of users to be inserted, each item is a dict with: |
| 969 | 'name': (mandatory) user name, |
| 970 | 'key-pairs': (optional) list of strings with the public key to be inserted to the user |
| 971 | 'user-data': (optional) string is a text script to be passed directly to cloud-init |
| 972 | 'config-files': (optional). List of files to be transferred. Each item is a dict with: |
| 973 | 'dest': (mandatory) string with the destination absolute path |
| 974 | 'encoding': (optional, by default text). Can be one of: |
| 975 | 'b64', 'base64', 'gz', 'gz+b64', 'gz+base64', 'gzip+b64', 'gzip+base64' |
| 976 | 'content' (mandatory): string with the content of the file |
| 977 | 'permissions': (optional) string with file permissions, typically octal notation '0644' |
| 978 | 'owner': (optional) file owner, string with the format 'owner:group' |
| 979 | 'boot-data-drive': boolean to indicate if user-data must be passed using a boot drive (hard disk) |
| mirabal | 2935631 | 2017-07-27 12:21:22 +0200 | [diff] [blame] | 980 | 'disk_list': (optional) list with additional disks to the VM. Each item is a dict with: |
| 981 | 'image_id': (optional). VIM id of an existing image. If not provided an empty disk must be mounted |
| 982 | 'size': (mandatory) string with the size of the disk in GB |
| tierno | 5a3273c | 2017-08-29 11:43:46 +0200 | [diff] [blame] | 983 | availability_zone_index: Index of availability_zone_list to use for this this VM. None if not AV required |
| 984 | availability_zone_list: list of availability zones given by user in the VNFD descriptor. Ignore if |
| 985 | availability_zone_index is None |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 986 | #TODO ip, security groups |
| tierno | 98e909c | 2017-10-14 13:27:03 +0200 | [diff] [blame] | 987 | Returns a tuple with the instance identifier and created_items or raises an exception on error |
| 988 | created_items can be None or a dictionary where this method can include key-values that will be passed to |
| 989 | the method delete_vminstance and action_vminstance. Can be used to store created ports, volumes, etc. |
| 990 | Format is vimconnector dependent, but do not use nested dictionaries and a value of None should be the same |
| 991 | as not present. |
| 992 | """ |
| tierno | fa51c20 | 2017-01-27 14:58:17 +0100 | [diff] [blame] | 993 | self.logger.debug("new_vminstance input: image='%s' flavor='%s' nics='%s'",image_id, flavor_id,str(net_list)) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 994 | try: |
| Pablo Montes Moreno | 6a7785b | 2017-07-03 10:44:30 +0200 | [diff] [blame] | 995 | server = None |
| tierno | 98e909c | 2017-10-14 13:27:03 +0200 | [diff] [blame] | 996 | created_items = {} |
| tierno | b0b9dab | 2017-10-14 14:25:20 +0200 | [diff] [blame] | 997 | # metadata = {} |
| tierno | 98e909c | 2017-10-14 13:27:03 +0200 | [diff] [blame] | 998 | net_list_vim = [] |
| 999 | external_network = [] # list of external networks to be connected to instance, later on used to create floating_ip |
| Pablo Montes Moreno | 6a7785b | 2017-07-03 10:44:30 +0200 | [diff] [blame] | 1000 | no_secured_ports = [] # List of port-is with port-security disabled |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1001 | self._reload_connection() |
| tierno | b0b9dab | 2017-10-14 14:25:20 +0200 | [diff] [blame] | 1002 | # metadata_vpci = {} # For a specific neutron plugin |
| tierno | b84cbdc | 2017-07-07 14:30:30 +0200 | [diff] [blame] | 1003 | block_device_mapping = None |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1004 | for net in net_list: |
| tierno | 98e909c | 2017-10-14 13:27:03 +0200 | [diff] [blame] | 1005 | if not net.get("net_id"): # skip non connected iface |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1006 | continue |
| Pablo Montes Moreno | 3be0b2a | 2017-03-30 13:22:15 +0200 | [diff] [blame] | 1007 | |
| 1008 | port_dict={ |
| 1009 | "network_id": net["net_id"], |
| 1010 | "name": net.get("name"), |
| 1011 | "admin_state_up": True |
| 1012 | } |
| 1013 | if net["type"]=="virtual": |
| tierno | b0b9dab | 2017-10-14 14:25:20 +0200 | [diff] [blame] | 1014 | pass |
| 1015 | # if "vpci" in net: |
| 1016 | # metadata_vpci[ net["net_id"] ] = [[ net["vpci"], "" ]] |
| tierno | 66eba6e | 2017-11-10 17:09:18 +0100 | [diff] [blame] | 1017 | elif net["type"] == "VF" or net["type"] == "SR-IOV": # for VF |
| tierno | b0b9dab | 2017-10-14 14:25:20 +0200 | [diff] [blame] | 1018 | # if "vpci" in net: |
| 1019 | # if "VF" not in metadata_vpci: |
| 1020 | # metadata_vpci["VF"]=[] |
| 1021 | # metadata_vpci["VF"].append([ net["vpci"], "" ]) |
| Pablo Montes Moreno | 3be0b2a | 2017-03-30 13:22:15 +0200 | [diff] [blame] | 1022 | port_dict["binding:vnic_type"]="direct" |
| tierno | b0b9dab | 2017-10-14 14:25:20 +0200 | [diff] [blame] | 1023 | # VIO specific Changes |
| kate | 721d79b | 2017-06-24 04:21:38 -0700 | [diff] [blame] | 1024 | if self.vim_type == "VIO": |
| tierno | b0b9dab | 2017-10-14 14:25:20 +0200 | [diff] [blame] | 1025 | # Need to create port with port_security_enabled = False and no-security-groups |
| kate | 721d79b | 2017-06-24 04:21:38 -0700 | [diff] [blame] | 1026 | port_dict["port_security_enabled"]=False |
| 1027 | port_dict["provider_security_groups"]=[] |
| 1028 | port_dict["security_groups"]=[] |
| tierno | 66eba6e | 2017-11-10 17:09:18 +0100 | [diff] [blame] | 1029 | else: # For PT PCI-PASSTHROUGH |
| tierno | b0b9dab | 2017-10-14 14:25:20 +0200 | [diff] [blame] | 1030 | # VIO specific Changes |
| 1031 | # Current VIO release does not support port with type 'direct-physical' |
| 1032 | # So no need to create virtual port in case of PCI-device. |
| 1033 | # Will update port_dict code when support gets added in next VIO release |
| kate | 721d79b | 2017-06-24 04:21:38 -0700 | [diff] [blame] | 1034 | if self.vim_type == "VIO": |
| tierno | b0b9dab | 2017-10-14 14:25:20 +0200 | [diff] [blame] | 1035 | raise vimconn.vimconnNotSupportedException( |
| 1036 | "Current VIO release does not support full passthrough (PT)") |
| 1037 | # if "vpci" in net: |
| 1038 | # if "PF" not in metadata_vpci: |
| 1039 | # metadata_vpci["PF"]=[] |
| 1040 | # metadata_vpci["PF"].append([ net["vpci"], "" ]) |
| Pablo Montes Moreno | 3be0b2a | 2017-03-30 13:22:15 +0200 | [diff] [blame] | 1041 | port_dict["binding:vnic_type"]="direct-physical" |
| 1042 | if not port_dict["name"]: |
| 1043 | port_dict["name"]=name |
| 1044 | if net.get("mac_address"): |
| 1045 | port_dict["mac_address"]=net["mac_address"] |
| tierno | 41a6981 | 2018-02-16 14:34:33 +0100 | [diff] [blame] | 1046 | if net.get("ip_address"): |
| 1047 | port_dict["fixed_ips"] = [{'ip_address': net["ip_address"]}] |
| 1048 | # TODO add 'subnet_id': <subnet_id> |
| Pablo Montes Moreno | 3be0b2a | 2017-03-30 13:22:15 +0200 | [diff] [blame] | 1049 | new_port = self.neutron.create_port({"port": port_dict }) |
| tierno | 00e3df7 | 2017-11-29 17:20:13 +0100 | [diff] [blame] | 1050 | created_items["port:" + str(new_port["port"]["id"])] = True |
| Pablo Montes Moreno | 3be0b2a | 2017-03-30 13:22:15 +0200 | [diff] [blame] | 1051 | net["mac_adress"] = new_port["port"]["mac_address"] |
| 1052 | net["vim_id"] = new_port["port"]["id"] |
| tierno | b84cbdc | 2017-07-07 14:30:30 +0200 | [diff] [blame] | 1053 | # if try to use a network without subnetwork, it will return a emtpy list |
| 1054 | fixed_ips = new_port["port"].get("fixed_ips") |
| 1055 | if fixed_ips: |
| 1056 | net["ip"] = fixed_ips[0].get("ip_address") |
| 1057 | else: |
| 1058 | net["ip"] = None |
| montesmoreno | 994a29d | 2017-08-22 11:23:06 +0200 | [diff] [blame] | 1059 | |
| 1060 | port = {"port-id": new_port["port"]["id"]} |
| 1061 | if float(self.nova.api_version.get_string()) >= 2.32: |
| 1062 | port["tag"] = new_port["port"]["name"] |
| 1063 | net_list_vim.append(port) |
| Pablo Montes Moreno | 3be0b2a | 2017-03-30 13:22:15 +0200 | [diff] [blame] | 1064 | |
| ahmadsa | f853d45 | 2016-12-22 11:33:47 +0500 | [diff] [blame] | 1065 | if net.get('floating_ip', False): |
| tierno | f8383b8 | 2017-01-18 15:49:48 +0100 | [diff] [blame] | 1066 | net['exit_on_floating_ip_error'] = True |
| ahmadsa | f853d45 | 2016-12-22 11:33:47 +0500 | [diff] [blame] | 1067 | external_network.append(net) |
| tierno | f8383b8 | 2017-01-18 15:49:48 +0100 | [diff] [blame] | 1068 | elif net['use'] == 'mgmt' and self.config.get('use_floating_ip'): |
| 1069 | net['exit_on_floating_ip_error'] = False |
| 1070 | external_network.append(net) |
| tierno | 326fd5e | 2018-02-22 11:58:59 +0100 | [diff] [blame] | 1071 | net['floating_ip'] = self.config.get('use_floating_ip') |
| tierno | f8383b8 | 2017-01-18 15:49:48 +0100 | [diff] [blame] | 1072 | |
| Pablo Montes Moreno | 6a7785b | 2017-07-03 10:44:30 +0200 | [diff] [blame] | 1073 | # If port security is disabled when the port has not yet been attached to the VM, then all vm traffic is dropped. |
| 1074 | # As a workaround we wait until the VM is active and then disable the port-security |
| tierno | 4d1ce22 | 2018-04-06 10:41:06 +0200 | [diff] [blame] | 1075 | if net.get("port_security") == False and not self.config.get("no_port_security_extension"): |
| Pablo Montes Moreno | 6a7785b | 2017-07-03 10:44:30 +0200 | [diff] [blame] | 1076 | no_secured_ports.append(new_port["port"]["id"]) |
| 1077 | |
| tierno | b0b9dab | 2017-10-14 14:25:20 +0200 | [diff] [blame] | 1078 | # if metadata_vpci: |
| 1079 | # metadata = {"pci_assignement": json.dumps(metadata_vpci)} |
| 1080 | # if len(metadata["pci_assignement"]) >255: |
| 1081 | # #limit the metadata size |
| 1082 | # #metadata["pci_assignement"] = metadata["pci_assignement"][0:255] |
| 1083 | # self.logger.warn("Metadata deleted since it exceeds the expected length (255) ") |
| 1084 | # metadata = {} |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1085 | |
| tierno | b0b9dab | 2017-10-14 14:25:20 +0200 | [diff] [blame] | 1086 | self.logger.debug("name '%s' image_id '%s'flavor_id '%s' net_list_vim '%s' description '%s'", |
| 1087 | name, image_id, flavor_id, str(net_list_vim), description) |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1088 | |
| tierno | b0b9dab | 2017-10-14 14:25:20 +0200 | [diff] [blame] | 1089 | security_groups = self.config.get('security_groups') |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1090 | if type(security_groups) is str: |
| 1091 | security_groups = ( security_groups, ) |
| tierno | 98e909c | 2017-10-14 13:27:03 +0200 | [diff] [blame] | 1092 | # cloud config |
| tierno | 0a1437e | 2017-10-02 00:17:43 +0200 | [diff] [blame] | 1093 | config_drive, userdata = self._create_user_data(cloud_config) |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 1094 | |
| tierno | 98e909c | 2017-10-14 13:27:03 +0200 | [diff] [blame] | 1095 | # Create additional volumes in case these are present in disk_list |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 1096 | base_disk_index = ord('b') |
| 1097 | if disk_list != None: |
| tierno | b84cbdc | 2017-07-07 14:30:30 +0200 | [diff] [blame] | 1098 | block_device_mapping = {} |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 1099 | for disk in disk_list: |
| 1100 | if 'image_id' in disk: |
| 1101 | volume = self.cinder.volumes.create(size = disk['size'],name = name + '_vd' + |
| 1102 | chr(base_disk_index), imageRef = disk['image_id']) |
| 1103 | else: |
| 1104 | volume = self.cinder.volumes.create(size=disk['size'], name=name + '_vd' + |
| 1105 | chr(base_disk_index)) |
| tierno | 00e3df7 | 2017-11-29 17:20:13 +0100 | [diff] [blame] | 1106 | created_items["volume:" + str(volume.id)] = True |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 1107 | block_device_mapping['_vd' + chr(base_disk_index)] = volume.id |
| 1108 | base_disk_index += 1 |
| 1109 | |
| tierno | b0b9dab | 2017-10-14 14:25:20 +0200 | [diff] [blame] | 1110 | # Wait until volumes are with status available |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 1111 | keep_waiting = True |
| 1112 | elapsed_time = 0 |
| 1113 | while keep_waiting and elapsed_time < volume_timeout: |
| 1114 | keep_waiting = False |
| 1115 | for volume_id in block_device_mapping.itervalues(): |
| 1116 | if self.cinder.volumes.get(volume_id).status != 'available': |
| 1117 | keep_waiting = True |
| 1118 | if keep_waiting: |
| 1119 | time.sleep(1) |
| 1120 | elapsed_time += 1 |
| 1121 | |
| tierno | b0b9dab | 2017-10-14 14:25:20 +0200 | [diff] [blame] | 1122 | # If we exceeded the timeout rollback |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 1123 | if elapsed_time >= volume_timeout: |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 1124 | raise vimconn.vimconnException('Timeout creating volumes for instance ' + name, |
| 1125 | http_code=vimconn.HTTP_Request_Timeout) |
| mirabal | 2935631 | 2017-07-27 12:21:22 +0200 | [diff] [blame] | 1126 | # get availability Zone |
| tierno | 5a3273c | 2017-08-29 11:43:46 +0200 | [diff] [blame] | 1127 | vm_av_zone = self._get_vm_availability_zone(availability_zone_index, availability_zone_list) |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 1128 | |
| tierno | b0b9dab | 2017-10-14 14:25:20 +0200 | [diff] [blame] | 1129 | self.logger.debug("nova.servers.create({}, {}, {}, nics={}, security_groups={}, " |
| mirabal | 2935631 | 2017-07-27 12:21:22 +0200 | [diff] [blame] | 1130 | "availability_zone={}, key_name={}, userdata={}, config_drive={}, " |
| tierno | b0b9dab | 2017-10-14 14:25:20 +0200 | [diff] [blame] | 1131 | "block_device_mapping={})".format(name, image_id, flavor_id, net_list_vim, |
| mirabal | 2935631 | 2017-07-27 12:21:22 +0200 | [diff] [blame] | 1132 | security_groups, vm_av_zone, self.config.get('keypair'), |
| tierno | b0b9dab | 2017-10-14 14:25:20 +0200 | [diff] [blame] | 1133 | userdata, config_drive, block_device_mapping)) |
| 1134 | server = self.nova.servers.create(name, image_id, flavor_id, nics=net_list_vim, |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 1135 | security_groups=security_groups, |
| mirabal | 2935631 | 2017-07-27 12:21:22 +0200 | [diff] [blame] | 1136 | availability_zone=vm_av_zone, |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 1137 | key_name=self.config.get('keypair'), |
| 1138 | userdata=userdata, |
| tierno | b84cbdc | 2017-07-07 14:30:30 +0200 | [diff] [blame] | 1139 | config_drive=config_drive, |
| 1140 | block_device_mapping=block_device_mapping |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 1141 | ) # , description=description) |
| Pablo Montes Moreno | 6a7785b | 2017-07-03 10:44:30 +0200 | [diff] [blame] | 1142 | |
| tierno | 326fd5e | 2018-02-22 11:58:59 +0100 | [diff] [blame] | 1143 | vm_start_time = time.time() |
| Pablo Montes Moreno | 6a7785b | 2017-07-03 10:44:30 +0200 | [diff] [blame] | 1144 | # Previously mentioned workaround to wait until the VM is active and then disable the port-security |
| 1145 | if no_secured_ports: |
| 1146 | self.__wait_for_vm(server.id, 'ACTIVE') |
| 1147 | |
| 1148 | for port_id in no_secured_ports: |
| 1149 | try: |
| tierno | 4d1ce22 | 2018-04-06 10:41:06 +0200 | [diff] [blame] | 1150 | self.neutron.update_port(port_id, |
| 1151 | {"port": {"port_security_enabled": False, "security_groups": None}}) |
| Pablo Montes Moreno | 6a7785b | 2017-07-03 10:44:30 +0200 | [diff] [blame] | 1152 | except Exception as e: |
| tierno | 4d1ce22 | 2018-04-06 10:41:06 +0200 | [diff] [blame] | 1153 | raise vimconn.vimconnException("It was not possible to disable port security for port {}".format( |
| 1154 | port_id)) |
| tierno | 98e909c | 2017-10-14 13:27:03 +0200 | [diff] [blame] | 1155 | # print "DONE :-)", server |
| Pablo Montes Moreno | 6a7785b | 2017-07-03 10:44:30 +0200 | [diff] [blame] | 1156 | |
| tierno | 4d1ce22 | 2018-04-06 10:41:06 +0200 | [diff] [blame] | 1157 | # pool_id = None |
| Pablo Montes Moreno | 6a7785b | 2017-07-03 10:44:30 +0200 | [diff] [blame] | 1158 | if external_network: |
| tierno | 98e909c | 2017-10-14 13:27:03 +0200 | [diff] [blame] | 1159 | floating_ips = self.neutron.list_floatingips().get("floatingips", ()) |
| ahmadsa | f853d45 | 2016-12-22 11:33:47 +0500 | [diff] [blame] | 1160 | for floating_network in external_network: |
| tierno | f8383b8 | 2017-01-18 15:49:48 +0100 | [diff] [blame] | 1161 | try: |
| tierno | f8383b8 | 2017-01-18 15:49:48 +0100 | [diff] [blame] | 1162 | assigned = False |
| tierno | 98e909c | 2017-10-14 13:27:03 +0200 | [diff] [blame] | 1163 | while not assigned: |
| tierno | f8383b8 | 2017-01-18 15:49:48 +0100 | [diff] [blame] | 1164 | if floating_ips: |
| 1165 | ip = floating_ips.pop(0) |
| tierno | 326fd5e | 2018-02-22 11:58:59 +0100 | [diff] [blame] | 1166 | if ip.get("port_id", False) or ip.get('tenant_id') != server.tenant_id: |
| 1167 | continue |
| 1168 | if isinstance(floating_network['floating_ip'], str): |
| 1169 | if ip.get("floating_network_id") != floating_network['floating_ip']: |
| 1170 | continue |
| 1171 | free_floating_ip = ip.get("floating_ip_address") |
| tierno | f8383b8 | 2017-01-18 15:49:48 +0100 | [diff] [blame] | 1172 | else: |
| tierno | 326fd5e | 2018-02-22 11:58:59 +0100 | [diff] [blame] | 1173 | if isinstance(floating_network['floating_ip'], str): |
| 1174 | pool_id = floating_network['floating_ip'] |
| 1175 | else: |
| tierno | 4d1ce22 | 2018-04-06 10:41:06 +0200 | [diff] [blame] | 1176 | # Find the external network |
| tierno | 326fd5e | 2018-02-22 11:58:59 +0100 | [diff] [blame] | 1177 | external_nets = list() |
| 1178 | for net in self.neutron.list_networks()['networks']: |
| 1179 | if net['router:external']: |
| 1180 | external_nets.append(net) |
| tierno | f8383b8 | 2017-01-18 15:49:48 +0100 | [diff] [blame] | 1181 | |
| tierno | 326fd5e | 2018-02-22 11:58:59 +0100 | [diff] [blame] | 1182 | if len(external_nets) == 0: |
| 1183 | raise vimconn.vimconnException("Cannot create floating_ip automatically since no external " |
| 1184 | "network is present", |
| 1185 | http_code=vimconn.HTTP_Conflict) |
| 1186 | if len(external_nets) > 1: |
| 1187 | raise vimconn.vimconnException("Cannot create floating_ip automatically since multiple " |
| 1188 | "external networks are present", |
| 1189 | http_code=vimconn.HTTP_Conflict) |
| tierno | f8383b8 | 2017-01-18 15:49:48 +0100 | [diff] [blame] | 1190 | |
| tierno | 326fd5e | 2018-02-22 11:58:59 +0100 | [diff] [blame] | 1191 | pool_id = external_nets[0].get('id') |
| tierno | f8383b8 | 2017-01-18 15:49:48 +0100 | [diff] [blame] | 1192 | param = {'floatingip': {'floating_network_id': pool_id, 'tenant_id': server.tenant_id}} |
| ahmadsa | f853d45 | 2016-12-22 11:33:47 +0500 | [diff] [blame] | 1193 | try: |
| tierno | 4d1ce22 | 2018-04-06 10:41:06 +0200 | [diff] [blame] | 1194 | # self.logger.debug("Creating floating IP") |
| tierno | f8383b8 | 2017-01-18 15:49:48 +0100 | [diff] [blame] | 1195 | new_floating_ip = self.neutron.create_floatingip(param) |
| 1196 | free_floating_ip = new_floating_ip['floatingip']['floating_ip_address'] |
| ahmadsa | f853d45 | 2016-12-22 11:33:47 +0500 | [diff] [blame] | 1197 | except Exception as e: |
| tierno | 326fd5e | 2018-02-22 11:58:59 +0100 | [diff] [blame] | 1198 | raise vimconn.vimconnException(type(e).__name__ + ": Cannot create new floating_ip " + |
| 1199 | str(e), http_code=vimconn.HTTP_Conflict) |
| 1200 | |
| 1201 | fix_ip = floating_network.get('ip') |
| 1202 | while not assigned: |
| 1203 | try: |
| 1204 | server.add_floating_ip(free_floating_ip, fix_ip) |
| 1205 | assigned = True |
| 1206 | except Exception as e: |
| tierno | 4d1ce22 | 2018-04-06 10:41:06 +0200 | [diff] [blame] | 1207 | # openstack need some time after VM creation to asign an IP. So retry if fails |
| tierno | 326fd5e | 2018-02-22 11:58:59 +0100 | [diff] [blame] | 1208 | vm_status = self.nova.servers.get(server.id).status |
| 1209 | if vm_status != 'ACTIVE' and vm_status != 'ERROR': |
| 1210 | if time.time() - vm_start_time < server_timeout: |
| 1211 | time.sleep(5) |
| 1212 | continue |
| tierno | 4d1ce22 | 2018-04-06 10:41:06 +0200 | [diff] [blame] | 1213 | raise vimconn.vimconnException( |
| 1214 | "Cannot create floating_ip: {} {}".format(type(e).__name__, e), |
| 1215 | http_code=vimconn.HTTP_Conflict) |
| tierno | 326fd5e | 2018-02-22 11:58:59 +0100 | [diff] [blame] | 1216 | |
| tierno | f8383b8 | 2017-01-18 15:49:48 +0100 | [diff] [blame] | 1217 | except Exception as e: |
| 1218 | if not floating_network['exit_on_floating_ip_error']: |
| 1219 | self.logger.warn("Cannot create floating_ip. %s", str(e)) |
| 1220 | continue |
| tierno | f8383b8 | 2017-01-18 15:49:48 +0100 | [diff] [blame] | 1221 | raise |
| montesmoreno | 2a1fc4e | 2017-01-09 16:46:04 +0000 | [diff] [blame] | 1222 | |
| tierno | 98e909c | 2017-10-14 13:27:03 +0200 | [diff] [blame] | 1223 | return server.id, created_items |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1224 | # except nvExceptions.NotFound as e: |
| 1225 | # error_value=-vimconn.HTTP_Not_Found |
| 1226 | # error_text= "vm instance %s not found" % vm_id |
| Pablo Montes Moreno | 6a7785b | 2017-07-03 10:44:30 +0200 | [diff] [blame] | 1227 | # except TypeError as e: |
| 1228 | # raise vimconn.vimconnException(type(e).__name__ + ": "+ str(e), http_code=vimconn.HTTP_Bad_Request) |
| 1229 | |
| 1230 | except Exception as e: |
| tierno | 98e909c | 2017-10-14 13:27:03 +0200 | [diff] [blame] | 1231 | server_id = None |
| 1232 | if server: |
| 1233 | server_id = server.id |
| 1234 | try: |
| 1235 | self.delete_vminstance(server_id, created_items) |
| 1236 | except Exception as e2: |
| 1237 | self.logger.error("new_vminstance rollback fail {}".format(e2)) |
| Pablo Montes Moreno | 6a7785b | 2017-07-03 10:44:30 +0200 | [diff] [blame] | 1238 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1239 | self._format_exception(e) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1240 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1241 | def get_vminstance(self,vm_id): |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1242 | '''Returns the VM instance information from VIM''' |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1243 | #self.logger.debug("Getting VM from VIM") |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1244 | try: |
| 1245 | self._reload_connection() |
| 1246 | server = self.nova.servers.find(id=vm_id) |
| 1247 | #TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema) |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1248 | return server.to_dict() |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 1249 | except (ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.NotFound, ConnectionError) as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1250 | self._format_exception(e) |
| 1251 | |
| 1252 | def get_vminstance_console(self,vm_id, console_type="vnc"): |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1253 | ''' |
| 1254 | Get a console for the virtual machine |
| 1255 | Params: |
| 1256 | vm_id: uuid of the VM |
| 1257 | console_type, can be: |
| 1258 | "novnc" (by default), "xvpvnc" for VNC types, |
| 1259 | "rdp-html5" for RDP types, "spice-html5" for SPICE types |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1260 | Returns dict with the console parameters: |
| 1261 | protocol: ssh, ftp, http, https, ... |
| 1262 | server: usually ip address |
| 1263 | port: the http, ssh, ... port |
| 1264 | suffix: extra text, e.g. the http path and query string |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1265 | ''' |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1266 | self.logger.debug("Getting VM CONSOLE from VIM") |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1267 | try: |
| 1268 | self._reload_connection() |
| 1269 | server = self.nova.servers.find(id=vm_id) |
| 1270 | if console_type == None or console_type == "novnc": |
| 1271 | console_dict = server.get_vnc_console("novnc") |
| 1272 | elif console_type == "xvpvnc": |
| 1273 | console_dict = server.get_vnc_console(console_type) |
| 1274 | elif console_type == "rdp-html5": |
| 1275 | console_dict = server.get_rdp_console(console_type) |
| 1276 | elif console_type == "spice-html5": |
| 1277 | console_dict = server.get_spice_console(console_type) |
| 1278 | else: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1279 | raise vimconn.vimconnException("console type '{}' not allowed".format(console_type), http_code=vimconn.HTTP_Bad_Request) |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1280 | |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1281 | console_dict1 = console_dict.get("console") |
| 1282 | if console_dict1: |
| 1283 | console_url = console_dict1.get("url") |
| 1284 | if console_url: |
| 1285 | #parse console_url |
| 1286 | protocol_index = console_url.find("//") |
| 1287 | suffix_index = console_url[protocol_index+2:].find("/") + protocol_index+2 |
| 1288 | port_index = console_url[protocol_index+2:suffix_index].find(":") + protocol_index+2 |
| 1289 | if protocol_index < 0 or port_index<0 or suffix_index<0: |
| 1290 | return -vimconn.HTTP_Internal_Server_Error, "Unexpected response from VIM" |
| 1291 | console_dict={"protocol": console_url[0:protocol_index], |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1292 | "server": console_url[protocol_index+2:port_index], |
| 1293 | "port": console_url[port_index:suffix_index], |
| 1294 | "suffix": console_url[suffix_index+1:] |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1295 | } |
| 1296 | protocol_index += 2 |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1297 | return console_dict |
| 1298 | raise vimconn.vimconnUnexpectedResponse("Unexpected response from VIM") |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1299 | |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 1300 | except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.BadRequest, ConnectionError) as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1301 | self._format_exception(e) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1302 | |
| tierno | 98e909c | 2017-10-14 13:27:03 +0200 | [diff] [blame] | 1303 | def delete_vminstance(self, vm_id, created_items=None): |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1304 | '''Removes a VM instance from VIM. Returns the old identifier |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1305 | ''' |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1306 | #print "osconnector: Getting VM from VIM" |
| tierno | 98e909c | 2017-10-14 13:27:03 +0200 | [diff] [blame] | 1307 | if created_items == None: |
| 1308 | created_items = {} |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1309 | try: |
| 1310 | self._reload_connection() |
| tierno | 98e909c | 2017-10-14 13:27:03 +0200 | [diff] [blame] | 1311 | # delete VM ports attached to this networks before the virtual machine |
| 1312 | for k, v in created_items.items(): |
| 1313 | if not v: # skip already deleted |
| 1314 | continue |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1315 | try: |
| tierno | ad6bdd4 | 2018-01-10 10:43:46 +0100 | [diff] [blame] | 1316 | k_item, _, k_id = k.partition(":") |
| 1317 | if k_item == "port": |
| 1318 | self.neutron.delete_port(k_id) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1319 | except Exception as e: |
| tierno | 00e3df7 | 2017-11-29 17:20:13 +0100 | [diff] [blame] | 1320 | self.logger.error("Error deleting port: {}: {}".format(type(e).__name__, e)) |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 1321 | |
| tierno | 98e909c | 2017-10-14 13:27:03 +0200 | [diff] [blame] | 1322 | # #commented because detaching the volumes makes the servers.delete not work properly ?!? |
| 1323 | # #dettach volumes attached |
| 1324 | # server = self.nova.servers.get(vm_id) |
| 1325 | # volumes_attached_dict = server._info['os-extended-volumes:volumes_attached'] #volume['id'] |
| 1326 | # #for volume in volumes_attached_dict: |
| 1327 | # # self.cinder.volumes.detach(volume['id']) |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 1328 | |
| tierno | 98e909c | 2017-10-14 13:27:03 +0200 | [diff] [blame] | 1329 | if vm_id: |
| 1330 | self.nova.servers.delete(vm_id) |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 1331 | |
| tierno | 98e909c | 2017-10-14 13:27:03 +0200 | [diff] [blame] | 1332 | # delete volumes. Although having detached, they should have in active status before deleting |
| 1333 | # we ensure in this loop |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 1334 | keep_waiting = True |
| 1335 | elapsed_time = 0 |
| 1336 | while keep_waiting and elapsed_time < volume_timeout: |
| 1337 | keep_waiting = False |
| tierno | 98e909c | 2017-10-14 13:27:03 +0200 | [diff] [blame] | 1338 | for k, v in created_items.items(): |
| 1339 | if not v: # skip already deleted |
| 1340 | continue |
| 1341 | try: |
| tierno | ad6bdd4 | 2018-01-10 10:43:46 +0100 | [diff] [blame] | 1342 | k_item, _, k_id = k.partition(":") |
| 1343 | if k_item == "volume": |
| 1344 | if self.cinder.volumes.get(k_id).status != 'available': |
| tierno | 98e909c | 2017-10-14 13:27:03 +0200 | [diff] [blame] | 1345 | keep_waiting = True |
| 1346 | else: |
| tierno | ad6bdd4 | 2018-01-10 10:43:46 +0100 | [diff] [blame] | 1347 | self.cinder.volumes.delete(k_id) |
| tierno | 98e909c | 2017-10-14 13:27:03 +0200 | [diff] [blame] | 1348 | except Exception as e: |
| tierno | 00e3df7 | 2017-11-29 17:20:13 +0100 | [diff] [blame] | 1349 | self.logger.error("Error deleting volume: {}: {}".format(type(e).__name__, e)) |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 1350 | if keep_waiting: |
| 1351 | time.sleep(1) |
| 1352 | elapsed_time += 1 |
| tierno | 98e909c | 2017-10-14 13:27:03 +0200 | [diff] [blame] | 1353 | return None |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 1354 | except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1355 | self._format_exception(e) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1356 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1357 | def refresh_vms_status(self, vm_list): |
| 1358 | '''Get the status of the virtual machines and their interfaces/ports |
| 1359 | Params: the list of VM identifiers |
| 1360 | Returns a dictionary with: |
| 1361 | vm_id: #VIM id of this Virtual Machine |
| 1362 | status: #Mandatory. Text with one of: |
| 1363 | # DELETED (not found at vim) |
| 1364 | # VIM_ERROR (Cannot connect to VIM, VIM response error, ...) |
| 1365 | # OTHER (Vim reported other status not understood) |
| 1366 | # ERROR (VIM indicates an ERROR status) |
| 1367 | # ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running), |
| 1368 | # CREATING (on building process), ERROR |
| 1369 | # ACTIVE:NoMgmtIP (Active but any of its interface has an IP address |
| 1370 | # |
| 1371 | error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR |
| 1372 | vim_info: #Text with plain information obtained from vim (yaml.safe_dump) |
| 1373 | interfaces: |
| 1374 | - vim_info: #Text with plain information obtained from vim (yaml.safe_dump) |
| 1375 | mac_address: #Text format XX:XX:XX:XX:XX:XX |
| 1376 | vim_net_id: #network id where this interface is connected |
| 1377 | vim_interface_id: #interface/port VIM id |
| 1378 | ip_address: #null, or text with IPv4, IPv6 address |
| tierno | 867ffe9 | 2017-03-27 12:50:34 +0200 | [diff] [blame] | 1379 | compute_node: #identification of compute node where PF,VF interface is allocated |
| 1380 | pci: #PCI address of the NIC that hosts the PF,VF |
| 1381 | vlan: #physical VLAN used for VF |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1382 | ''' |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1383 | vm_dict={} |
| 1384 | self.logger.debug("refresh_vms status: Getting tenant VM instance information from VIM") |
| 1385 | for vm_id in vm_list: |
| 1386 | vm={} |
| 1387 | try: |
| 1388 | vm_vim = self.get_vminstance(vm_id) |
| 1389 | if vm_vim['status'] in vmStatus2manoFormat: |
| 1390 | vm['status'] = vmStatus2manoFormat[ vm_vim['status'] ] |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1391 | else: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1392 | vm['status'] = "OTHER" |
| 1393 | vm['error_msg'] = "VIM status reported " + vm_vim['status'] |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 1394 | try: |
| 1395 | vm['vim_info'] = yaml.safe_dump(vm_vim, default_flow_style=True, width=256) |
| 1396 | except yaml.representer.RepresenterError: |
| 1397 | vm['vim_info'] = str(vm_vim) |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1398 | vm["interfaces"] = [] |
| 1399 | if vm_vim.get('fault'): |
| 1400 | vm['error_msg'] = str(vm_vim['fault']) |
| 1401 | #get interfaces |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1402 | try: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1403 | self._reload_connection() |
| 1404 | port_dict=self.neutron.list_ports(device_id=vm_id) |
| 1405 | for port in port_dict["ports"]: |
| 1406 | interface={} |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 1407 | try: |
| 1408 | interface['vim_info'] = yaml.safe_dump(port, default_flow_style=True, width=256) |
| 1409 | except yaml.representer.RepresenterError: |
| 1410 | interface['vim_info'] = str(port) |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1411 | interface["mac_address"] = port.get("mac_address") |
| 1412 | interface["vim_net_id"] = port["network_id"] |
| 1413 | interface["vim_interface_id"] = port["id"] |
| Mike Marchetti | 5b9da42 | 2017-05-02 15:35:47 -0400 | [diff] [blame] | 1414 | # check if OS-EXT-SRV-ATTR:host is there, |
| 1415 | # in case of non-admin credentials, it will be missing |
| 1416 | if vm_vim.get('OS-EXT-SRV-ATTR:host'): |
| 1417 | interface["compute_node"] = vm_vim['OS-EXT-SRV-ATTR:host'] |
| tierno | 867ffe9 | 2017-03-27 12:50:34 +0200 | [diff] [blame] | 1418 | interface["pci"] = None |
| Mike Marchetti | 5b9da42 | 2017-05-02 15:35:47 -0400 | [diff] [blame] | 1419 | |
| 1420 | # check if binding:profile is there, |
| 1421 | # in case of non-admin credentials, it will be missing |
| 1422 | if port.get('binding:profile'): |
| 1423 | if port['binding:profile'].get('pci_slot'): |
| 1424 | # TODO: At the moment sr-iov pci addresses are converted to PF pci addresses by setting the slot to 0x00 |
| 1425 | # TODO: This is just a workaround valid for niantinc. Find a better way to do so |
| 1426 | # CHANGE DDDD:BB:SS.F to DDDD:BB:00.(F%2) assuming there are 2 ports per nic |
| 1427 | pci = port['binding:profile']['pci_slot'] |
| 1428 | # interface["pci"] = pci[:-4] + "00." + str(int(pci[-1]) % 2) |
| 1429 | interface["pci"] = pci |
| tierno | 867ffe9 | 2017-03-27 12:50:34 +0200 | [diff] [blame] | 1430 | interface["vlan"] = None |
| Pablo Montes Moreno | 3be0b2a | 2017-03-30 13:22:15 +0200 | [diff] [blame] | 1431 | #if network is of type vlan and port is of type direct (sr-iov) then set vlan id |
| Pablo Montes Moreno | 51e553b | 2017-03-23 16:39:12 +0100 | [diff] [blame] | 1432 | network = self.neutron.show_network(port["network_id"]) |
| Pablo Montes Moreno | 3be0b2a | 2017-03-30 13:22:15 +0200 | [diff] [blame] | 1433 | if network['network'].get('provider:network_type') == 'vlan' and \ |
| 1434 | port.get("binding:vnic_type") == "direct": |
| tierno | 867ffe9 | 2017-03-27 12:50:34 +0200 | [diff] [blame] | 1435 | interface["vlan"] = network['network'].get('provider:segmentation_id') |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1436 | ips=[] |
| 1437 | #look for floating ip address |
| 1438 | floating_ip_dict = self.neutron.list_floatingips(port_id=port["id"]) |
| 1439 | if floating_ip_dict.get("floatingips"): |
| 1440 | ips.append(floating_ip_dict["floatingips"][0].get("floating_ip_address") ) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1441 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1442 | for subnet in port["fixed_ips"]: |
| 1443 | ips.append(subnet["ip_address"]) |
| 1444 | interface["ip_address"] = ";".join(ips) |
| 1445 | vm["interfaces"].append(interface) |
| 1446 | except Exception as e: |
| 1447 | self.logger.error("Error getting vm interface information " + type(e).__name__ + ": "+ str(e)) |
| 1448 | except vimconn.vimconnNotFoundException as e: |
| 1449 | self.logger.error("Exception getting vm status: %s", str(e)) |
| 1450 | vm['status'] = "DELETED" |
| 1451 | vm['error_msg'] = str(e) |
| 1452 | except vimconn.vimconnException as e: |
| 1453 | self.logger.error("Exception getting vm status: %s", str(e)) |
| 1454 | vm['status'] = "VIM_ERROR" |
| 1455 | vm['error_msg'] = str(e) |
| 1456 | vm_dict[vm_id] = vm |
| 1457 | return vm_dict |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1458 | |
| tierno | 98e909c | 2017-10-14 13:27:03 +0200 | [diff] [blame] | 1459 | def action_vminstance(self, vm_id, action_dict, created_items={}): |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1460 | '''Send and action over a VM instance from VIM |
| tierno | 98e909c | 2017-10-14 13:27:03 +0200 | [diff] [blame] | 1461 | Returns None or the console dict if the action was successfully sent to the VIM''' |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1462 | self.logger.debug("Action over VM '%s': %s", vm_id, str(action_dict)) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1463 | try: |
| 1464 | self._reload_connection() |
| 1465 | server = self.nova.servers.find(id=vm_id) |
| 1466 | if "start" in action_dict: |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1467 | if action_dict["start"]=="rebuild": |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1468 | server.rebuild() |
| 1469 | else: |
| 1470 | if server.status=="PAUSED": |
| 1471 | server.unpause() |
| 1472 | elif server.status=="SUSPENDED": |
| 1473 | server.resume() |
| 1474 | elif server.status=="SHUTOFF": |
| 1475 | server.start() |
| 1476 | elif "pause" in action_dict: |
| 1477 | server.pause() |
| 1478 | elif "resume" in action_dict: |
| 1479 | server.resume() |
| 1480 | elif "shutoff" in action_dict or "shutdown" in action_dict: |
| 1481 | server.stop() |
| 1482 | elif "forceOff" in action_dict: |
| 1483 | server.stop() #TODO |
| 1484 | elif "terminate" in action_dict: |
| 1485 | server.delete() |
| 1486 | elif "createImage" in action_dict: |
| 1487 | server.create_image() |
| 1488 | #"path":path_schema, |
| 1489 | #"description":description_schema, |
| 1490 | #"name":name_schema, |
| 1491 | #"metadata":metadata_schema, |
| 1492 | #"imageRef": id_schema, |
| 1493 | #"disk": {"oneOf":[{"type": "null"}, {"type":"string"}] }, |
| 1494 | elif "rebuild" in action_dict: |
| 1495 | server.rebuild(server.image['id']) |
| 1496 | elif "reboot" in action_dict: |
| 1497 | server.reboot() #reboot_type='SOFT' |
| 1498 | elif "console" in action_dict: |
| 1499 | console_type = action_dict["console"] |
| 1500 | if console_type == None or console_type == "novnc": |
| 1501 | console_dict = server.get_vnc_console("novnc") |
| 1502 | elif console_type == "xvpvnc": |
| 1503 | console_dict = server.get_vnc_console(console_type) |
| 1504 | elif console_type == "rdp-html5": |
| 1505 | console_dict = server.get_rdp_console(console_type) |
| 1506 | elif console_type == "spice-html5": |
| 1507 | console_dict = server.get_spice_console(console_type) |
| 1508 | else: |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1509 | raise vimconn.vimconnException("console type '{}' not allowed".format(console_type), |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1510 | http_code=vimconn.HTTP_Bad_Request) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1511 | try: |
| 1512 | console_url = console_dict["console"]["url"] |
| 1513 | #parse console_url |
| 1514 | protocol_index = console_url.find("//") |
| 1515 | suffix_index = console_url[protocol_index+2:].find("/") + protocol_index+2 |
| 1516 | port_index = console_url[protocol_index+2:suffix_index].find(":") + protocol_index+2 |
| 1517 | if protocol_index < 0 or port_index<0 or suffix_index<0: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1518 | raise vimconn.vimconnException("Unexpected response from VIM " + str(console_dict)) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1519 | console_dict2={"protocol": console_url[0:protocol_index], |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1520 | "server": console_url[protocol_index+2 : port_index], |
| 1521 | "port": int(console_url[port_index+1 : suffix_index]), |
| 1522 | "suffix": console_url[suffix_index+1:] |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1523 | } |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1524 | return console_dict2 |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1525 | except Exception as e: |
| 1526 | raise vimconn.vimconnException("Unexpected response from VIM " + str(console_dict)) |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1527 | |
| tierno | 98e909c | 2017-10-14 13:27:03 +0200 | [diff] [blame] | 1528 | return None |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 1529 | except (ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.NotFound, ConnectionError) as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1530 | self._format_exception(e) |
| 1531 | #TODO insert exception vimconn.HTTP_Unauthorized |
| 1532 | |
| kate | 721d79b | 2017-06-24 04:21:38 -0700 | [diff] [blame] | 1533 | ####### VIO Specific Changes ######### |
| 1534 | def _genrate_vlanID(self): |
| 1535 | """ |
| 1536 | Method to get unused vlanID |
| 1537 | Args: |
| 1538 | None |
| 1539 | Returns: |
| 1540 | vlanID |
| 1541 | """ |
| 1542 | #Get used VLAN IDs |
| 1543 | usedVlanIDs = [] |
| 1544 | networks = self.get_network_list() |
| 1545 | for net in networks: |
| 1546 | if net.get('provider:segmentation_id'): |
| 1547 | usedVlanIDs.append(net.get('provider:segmentation_id')) |
| 1548 | used_vlanIDs = set(usedVlanIDs) |
| 1549 | |
| 1550 | #find unused VLAN ID |
| 1551 | for vlanID_range in self.config.get('dataplane_net_vlan_range'): |
| 1552 | try: |
| 1553 | start_vlanid , end_vlanid = map(int, vlanID_range.replace(" ", "").split("-")) |
| 1554 | for vlanID in xrange(start_vlanid, end_vlanid + 1): |
| 1555 | if vlanID not in used_vlanIDs: |
| 1556 | return vlanID |
| 1557 | except Exception as exp: |
| 1558 | raise vimconn.vimconnException("Exception {} occurred while generating VLAN ID.".format(exp)) |
| 1559 | else: |
| 1560 | raise vimconn.vimconnConflictException("Unable to create the SRIOV VLAN network."\ |
| 1561 | " All given Vlan IDs {} are in use.".format(self.config.get('dataplane_net_vlan_range'))) |
| 1562 | |
| 1563 | |
| 1564 | def _validate_vlan_ranges(self, dataplane_net_vlan_range): |
| 1565 | """ |
| 1566 | Method to validate user given vlanID ranges |
| 1567 | Args: None |
| 1568 | Returns: None |
| 1569 | """ |
| 1570 | for vlanID_range in dataplane_net_vlan_range: |
| 1571 | vlan_range = vlanID_range.replace(" ", "") |
| 1572 | #validate format |
| 1573 | vlanID_pattern = r'(\d)*-(\d)*$' |
| 1574 | match_obj = re.match(vlanID_pattern, vlan_range) |
| 1575 | if not match_obj: |
| 1576 | raise vimconn.vimconnConflictException("Invalid dataplane_net_vlan_range {}.You must provide "\ |
| 1577 | "'dataplane_net_vlan_range' in format [start_ID - end_ID].".format(vlanID_range)) |
| 1578 | |
| 1579 | start_vlanid , end_vlanid = map(int,vlan_range.split("-")) |
| 1580 | if start_vlanid <= 0 : |
| 1581 | raise vimconn.vimconnConflictException("Invalid dataplane_net_vlan_range {}."\ |
| 1582 | "Start ID can not be zero. For VLAN "\ |
| 1583 | "networks valid IDs are 1 to 4094 ".format(vlanID_range)) |
| 1584 | if end_vlanid > 4094 : |
| 1585 | raise vimconn.vimconnConflictException("Invalid dataplane_net_vlan_range {}."\ |
| 1586 | "End VLAN ID can not be greater than 4094. For VLAN "\ |
| 1587 | "networks valid IDs are 1 to 4094 ".format(vlanID_range)) |
| 1588 | |
| 1589 | if start_vlanid > end_vlanid: |
| 1590 | raise vimconn.vimconnConflictException("Invalid dataplane_net_vlan_range {}."\ |
| 1591 | "You must provide a 'dataplane_net_vlan_range' in format start_ID - end_ID and "\ |
| 1592 | "start_ID < end_ID ".format(vlanID_range)) |
| 1593 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1594 | #NOT USED FUNCTIONS |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1595 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1596 | def new_external_port(self, port_data): |
| 1597 | #TODO openstack if needed |
| 1598 | '''Adds a external port to VIM''' |
| 1599 | '''Returns the port identifier''' |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1600 | return -vimconn.HTTP_Internal_Server_Error, "osconnector.new_external_port() not implemented" |
| 1601 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1602 | def connect_port_network(self, port_id, network_id, admin=False): |
| 1603 | #TODO openstack if needed |
| 1604 | '''Connects a external port to a network''' |
| 1605 | '''Returns status code of the VIM response''' |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1606 | return -vimconn.HTTP_Internal_Server_Error, "osconnector.connect_port_network() not implemented" |
| 1607 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1608 | def new_user(self, user_name, user_passwd, tenant_id=None): |
| 1609 | '''Adds a new user to openstack VIM''' |
| 1610 | '''Returns the user identifier''' |
| 1611 | self.logger.debug("osconnector: Adding a new user to VIM") |
| 1612 | try: |
| 1613 | self._reload_connection() |
| 1614 | user=self.keystone.users.create(user_name, user_passwd, tenant_id=tenant_id) |
| 1615 | #self.keystone.tenants.add_user(self.k_creds["username"], #role) |
| 1616 | return user.id |
| 1617 | except ksExceptions.ConnectionError as e: |
| 1618 | error_value=-vimconn.HTTP_Bad_Request |
| 1619 | error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0])) |
| 1620 | except ksExceptions.ClientException as e: #TODO remove |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1621 | error_value=-vimconn.HTTP_Bad_Request |
| 1622 | error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0])) |
| 1623 | #TODO insert exception vimconn.HTTP_Unauthorized |
| 1624 | #if reaching here is because an exception |
| tierno | 9c5c832 | 2018-03-23 15:44:03 +0100 | [diff] [blame] | 1625 | self.logger.debug("new_user " + error_text) |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1626 | return error_value, error_text |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1627 | |
| 1628 | def delete_user(self, user_id): |
| 1629 | '''Delete a user from openstack VIM''' |
| 1630 | '''Returns the user identifier''' |
| 1631 | if self.debug: |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1632 | print("osconnector: Deleting a user from VIM") |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1633 | try: |
| 1634 | self._reload_connection() |
| 1635 | self.keystone.users.delete(user_id) |
| 1636 | return 1, user_id |
| 1637 | except ksExceptions.ConnectionError as e: |
| 1638 | error_value=-vimconn.HTTP_Bad_Request |
| 1639 | error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0])) |
| 1640 | except ksExceptions.NotFound as e: |
| 1641 | error_value=-vimconn.HTTP_Not_Found |
| 1642 | error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0])) |
| 1643 | except ksExceptions.ClientException as e: #TODO remove |
| 1644 | error_value=-vimconn.HTTP_Bad_Request |
| 1645 | error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0])) |
| 1646 | #TODO insert exception vimconn.HTTP_Unauthorized |
| 1647 | #if reaching here is because an exception |
| tierno | 9c5c832 | 2018-03-23 15:44:03 +0100 | [diff] [blame] | 1648 | self.logger.debug("delete_tenant " + error_text) |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1649 | return error_value, error_text |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1650 | |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1651 | def get_hosts_info(self): |
| 1652 | '''Get the information of deployed hosts |
| 1653 | Returns the hosts content''' |
| 1654 | if self.debug: |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1655 | print("osconnector: Getting Host info from VIM") |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1656 | try: |
| 1657 | h_list=[] |
| 1658 | self._reload_connection() |
| 1659 | hypervisors = self.nova.hypervisors.list() |
| 1660 | for hype in hypervisors: |
| 1661 | h_list.append( hype.to_dict() ) |
| 1662 | return 1, {"hosts":h_list} |
| 1663 | except nvExceptions.NotFound as e: |
| 1664 | error_value=-vimconn.HTTP_Not_Found |
| 1665 | error_text= (str(e) if len(e.args)==0 else str(e.args[0])) |
| 1666 | except (ksExceptions.ClientException, nvExceptions.ClientException) as e: |
| 1667 | error_value=-vimconn.HTTP_Bad_Request |
| 1668 | error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0])) |
| 1669 | #TODO insert exception vimconn.HTTP_Unauthorized |
| 1670 | #if reaching here is because an exception |
| tierno | 9c5c832 | 2018-03-23 15:44:03 +0100 | [diff] [blame] | 1671 | self.logger.debug("get_hosts_info " + error_text) |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1672 | return error_value, error_text |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1673 | |
| 1674 | def get_hosts(self, vim_tenant): |
| 1675 | '''Get the hosts and deployed instances |
| 1676 | Returns the hosts content''' |
| 1677 | r, hype_dict = self.get_hosts_info() |
| 1678 | if r<0: |
| 1679 | return r, hype_dict |
| 1680 | hypervisors = hype_dict["hosts"] |
| 1681 | try: |
| 1682 | servers = self.nova.servers.list() |
| 1683 | for hype in hypervisors: |
| 1684 | for server in servers: |
| 1685 | if server.to_dict()['OS-EXT-SRV-ATTR:hypervisor_hostname']==hype['hypervisor_hostname']: |
| 1686 | if 'vm' in hype: |
| 1687 | hype['vm'].append(server.id) |
| 1688 | else: |
| 1689 | hype['vm'] = [server.id] |
| 1690 | return 1, hype_dict |
| 1691 | except nvExceptions.NotFound as e: |
| 1692 | error_value=-vimconn.HTTP_Not_Found |
| 1693 | error_text= (str(e) if len(e.args)==0 else str(e.args[0])) |
| 1694 | except (ksExceptions.ClientException, nvExceptions.ClientException) as e: |
| 1695 | error_value=-vimconn.HTTP_Bad_Request |
| 1696 | error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0])) |
| 1697 | #TODO insert exception vimconn.HTTP_Unauthorized |
| 1698 | #if reaching here is because an exception |
| tierno | 9c5c832 | 2018-03-23 15:44:03 +0100 | [diff] [blame] | 1699 | self.logger.debug("get_hosts " + error_text) |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1700 | return error_value, error_text |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1701 | |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1702 | def new_classification(self, name, ctype, definition): |
| 1703 | self.logger.debug( |
| 1704 | 'Adding a new (Traffic) Classification to VIM, named %s', name) |
| 1705 | try: |
| 1706 | new_class = None |
| 1707 | self._reload_connection() |
| 1708 | if ctype not in supportedClassificationTypes: |
| 1709 | raise vimconn.vimconnNotSupportedException( |
| 1710 | 'OpenStack VIM connector doesn\'t support provided ' |
| 1711 | 'Classification Type {}, supported ones are: ' |
| 1712 | '{}'.format(ctype, supportedClassificationTypes)) |
| 1713 | if not self._validate_classification(ctype, definition): |
| 1714 | raise vimconn.vimconnException( |
| 1715 | 'Incorrect Classification definition ' |
| 1716 | 'for the type specified.') |
| 1717 | classification_dict = definition |
| 1718 | classification_dict['name'] = name |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1719 | |
| Igor D.C | caadc44 | 2017-11-06 12:48:48 +0000 | [diff] [blame] | 1720 | new_class = self.neutron.create_sfc_flow_classifier( |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1721 | {'flow_classifier': classification_dict}) |
| 1722 | return new_class['flow_classifier']['id'] |
| 1723 | except (neExceptions.ConnectionFailed, ksExceptions.ClientException, |
| 1724 | neExceptions.NeutronException, ConnectionError) as e: |
| 1725 | self.logger.error( |
| 1726 | 'Creation of Classification failed.') |
| 1727 | self._format_exception(e) |
| 1728 | |
| 1729 | def get_classification(self, class_id): |
| 1730 | self.logger.debug(" Getting Classification %s from VIM", class_id) |
| 1731 | filter_dict = {"id": class_id} |
| 1732 | class_list = self.get_classification_list(filter_dict) |
| 1733 | if len(class_list) == 0: |
| 1734 | raise vimconn.vimconnNotFoundException( |
| 1735 | "Classification '{}' not found".format(class_id)) |
| 1736 | elif len(class_list) > 1: |
| 1737 | raise vimconn.vimconnConflictException( |
| 1738 | "Found more than one Classification with this criteria") |
| 1739 | classification = class_list[0] |
| 1740 | return classification |
| 1741 | |
| 1742 | def get_classification_list(self, filter_dict={}): |
| 1743 | self.logger.debug("Getting Classifications from VIM filter: '%s'", |
| 1744 | str(filter_dict)) |
| 1745 | try: |
| tierno | 69b590e | 2018-03-13 18:52:23 +0100 | [diff] [blame] | 1746 | filter_dict_os = filter_dict.copy() |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1747 | self._reload_connection() |
| tierno | 69b590e | 2018-03-13 18:52:23 +0100 | [diff] [blame] | 1748 | if self.api_version3 and "tenant_id" in filter_dict_os: |
| 1749 | filter_dict_os['project_id'] = filter_dict_os.pop('tenant_id') |
| Igor D.C | caadc44 | 2017-11-06 12:48:48 +0000 | [diff] [blame] | 1750 | classification_dict = self.neutron.list_sfc_flow_classifiers( |
| tierno | 69b590e | 2018-03-13 18:52:23 +0100 | [diff] [blame] | 1751 | **filter_dict_os) |
| 1752 | classification_list = classification_dict["flow_classifiers"] |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1753 | self.__classification_os2mano(classification_list) |
| 1754 | return classification_list |
| 1755 | except (neExceptions.ConnectionFailed, ksExceptions.ClientException, |
| 1756 | neExceptions.NeutronException, ConnectionError) as e: |
| 1757 | self._format_exception(e) |
| 1758 | |
| 1759 | def delete_classification(self, class_id): |
| 1760 | self.logger.debug("Deleting Classification '%s' from VIM", class_id) |
| 1761 | try: |
| 1762 | self._reload_connection() |
| Igor D.C | caadc44 | 2017-11-06 12:48:48 +0000 | [diff] [blame] | 1763 | self.neutron.delete_sfc_flow_classifier(class_id) |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1764 | return class_id |
| 1765 | except (neExceptions.ConnectionFailed, neExceptions.NeutronException, |
| 1766 | ksExceptions.ClientException, neExceptions.NeutronException, |
| 1767 | ConnectionError) as e: |
| 1768 | self._format_exception(e) |
| 1769 | |
| 1770 | def new_sfi(self, name, ingress_ports, egress_ports, sfc_encap=True): |
| 1771 | self.logger.debug( |
| 1772 | "Adding a new Service Function Instance to VIM, named '%s'", name) |
| 1773 | try: |
| 1774 | new_sfi = None |
| 1775 | self._reload_connection() |
| 1776 | correlation = None |
| 1777 | if sfc_encap: |
| Igor D.C | caadc44 | 2017-11-06 12:48:48 +0000 | [diff] [blame] | 1778 | correlation = 'nsh' |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1779 | if len(ingress_ports) != 1: |
| 1780 | raise vimconn.vimconnNotSupportedException( |
| 1781 | "OpenStack VIM connector can only have " |
| 1782 | "1 ingress port per SFI") |
| 1783 | if len(egress_ports) != 1: |
| 1784 | raise vimconn.vimconnNotSupportedException( |
| 1785 | "OpenStack VIM connector can only have " |
| 1786 | "1 egress port per SFI") |
| 1787 | sfi_dict = {'name': name, |
| 1788 | 'ingress': ingress_ports[0], |
| 1789 | 'egress': egress_ports[0], |
| 1790 | 'service_function_parameters': { |
| 1791 | 'correlation': correlation}} |
| Igor D.C | caadc44 | 2017-11-06 12:48:48 +0000 | [diff] [blame] | 1792 | new_sfi = self.neutron.create_sfc_port_pair({'port_pair': sfi_dict}) |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1793 | return new_sfi['port_pair']['id'] |
| 1794 | except (neExceptions.ConnectionFailed, ksExceptions.ClientException, |
| 1795 | neExceptions.NeutronException, ConnectionError) as e: |
| 1796 | if new_sfi: |
| 1797 | try: |
| Igor D.C | caadc44 | 2017-11-06 12:48:48 +0000 | [diff] [blame] | 1798 | self.neutron.delete_sfc_port_pair( |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1799 | new_sfi['port_pair']['id']) |
| 1800 | except Exception: |
| 1801 | self.logger.error( |
| 1802 | 'Creation of Service Function Instance failed, with ' |
| 1803 | 'subsequent deletion failure as well.') |
| 1804 | self._format_exception(e) |
| 1805 | |
| 1806 | def get_sfi(self, sfi_id): |
| 1807 | self.logger.debug( |
| 1808 | 'Getting Service Function Instance %s from VIM', sfi_id) |
| 1809 | filter_dict = {"id": sfi_id} |
| 1810 | sfi_list = self.get_sfi_list(filter_dict) |
| 1811 | if len(sfi_list) == 0: |
| 1812 | raise vimconn.vimconnNotFoundException( |
| 1813 | "Service Function Instance '{}' not found".format(sfi_id)) |
| 1814 | elif len(sfi_list) > 1: |
| 1815 | raise vimconn.vimconnConflictException( |
| 1816 | 'Found more than one Service Function Instance ' |
| 1817 | 'with this criteria') |
| 1818 | sfi = sfi_list[0] |
| 1819 | return sfi |
| 1820 | |
| 1821 | def get_sfi_list(self, filter_dict={}): |
| 1822 | self.logger.debug("Getting Service Function Instances from " |
| 1823 | "VIM filter: '%s'", str(filter_dict)) |
| 1824 | try: |
| 1825 | self._reload_connection() |
| tierno | 69b590e | 2018-03-13 18:52:23 +0100 | [diff] [blame] | 1826 | filter_dict_os = filter_dict.copy() |
| 1827 | if self.api_version3 and "tenant_id" in filter_dict_os: |
| 1828 | filter_dict_os['project_id'] = filter_dict_os.pop('tenant_id') |
| 1829 | sfi_dict = self.neutron.list_sfc_port_pairs(**filter_dict_os) |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1830 | sfi_list = sfi_dict["port_pairs"] |
| 1831 | self.__sfi_os2mano(sfi_list) |
| 1832 | return sfi_list |
| 1833 | except (neExceptions.ConnectionFailed, ksExceptions.ClientException, |
| 1834 | neExceptions.NeutronException, ConnectionError) as e: |
| 1835 | self._format_exception(e) |
| 1836 | |
| 1837 | def delete_sfi(self, sfi_id): |
| 1838 | self.logger.debug("Deleting Service Function Instance '%s' " |
| 1839 | "from VIM", sfi_id) |
| 1840 | try: |
| 1841 | self._reload_connection() |
| Igor D.C | caadc44 | 2017-11-06 12:48:48 +0000 | [diff] [blame] | 1842 | self.neutron.delete_sfc_port_pair(sfi_id) |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1843 | return sfi_id |
| 1844 | except (neExceptions.ConnectionFailed, neExceptions.NeutronException, |
| 1845 | ksExceptions.ClientException, neExceptions.NeutronException, |
| 1846 | ConnectionError) as e: |
| 1847 | self._format_exception(e) |
| 1848 | |
| 1849 | def new_sf(self, name, sfis, sfc_encap=True): |
| 1850 | self.logger.debug("Adding a new Service Function to VIM, " |
| 1851 | "named '%s'", name) |
| 1852 | try: |
| 1853 | new_sf = None |
| 1854 | self._reload_connection() |
| tierno | 9c5c832 | 2018-03-23 15:44:03 +0100 | [diff] [blame] | 1855 | # correlation = None |
| 1856 | # if sfc_encap: |
| 1857 | # correlation = 'nsh' |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1858 | for instance in sfis: |
| 1859 | sfi = self.get_sfi(instance) |
| Igor D.C | caadc44 | 2017-11-06 12:48:48 +0000 | [diff] [blame] | 1860 | if sfi.get('sfc_encap') != sfc_encap: |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1861 | raise vimconn.vimconnNotSupportedException( |
| 1862 | "OpenStack VIM connector requires all SFIs of the " |
| 1863 | "same SF to share the same SFC Encapsulation") |
| 1864 | sf_dict = {'name': name, |
| 1865 | 'port_pairs': sfis} |
| Igor D.C | caadc44 | 2017-11-06 12:48:48 +0000 | [diff] [blame] | 1866 | new_sf = self.neutron.create_sfc_port_pair_group({ |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1867 | 'port_pair_group': sf_dict}) |
| 1868 | return new_sf['port_pair_group']['id'] |
| 1869 | except (neExceptions.ConnectionFailed, ksExceptions.ClientException, |
| 1870 | neExceptions.NeutronException, ConnectionError) as e: |
| 1871 | if new_sf: |
| 1872 | try: |
| Igor D.C | caadc44 | 2017-11-06 12:48:48 +0000 | [diff] [blame] | 1873 | self.neutron.delete_sfc_port_pair_group( |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1874 | new_sf['port_pair_group']['id']) |
| 1875 | except Exception: |
| 1876 | self.logger.error( |
| 1877 | 'Creation of Service Function failed, with ' |
| 1878 | 'subsequent deletion failure as well.') |
| 1879 | self._format_exception(e) |
| 1880 | |
| 1881 | def get_sf(self, sf_id): |
| 1882 | self.logger.debug("Getting Service Function %s from VIM", sf_id) |
| 1883 | filter_dict = {"id": sf_id} |
| 1884 | sf_list = self.get_sf_list(filter_dict) |
| 1885 | if len(sf_list) == 0: |
| 1886 | raise vimconn.vimconnNotFoundException( |
| 1887 | "Service Function '{}' not found".format(sf_id)) |
| 1888 | elif len(sf_list) > 1: |
| 1889 | raise vimconn.vimconnConflictException( |
| 1890 | "Found more than one Service Function with this criteria") |
| 1891 | sf = sf_list[0] |
| 1892 | return sf |
| 1893 | |
| 1894 | def get_sf_list(self, filter_dict={}): |
| 1895 | self.logger.debug("Getting Service Function from VIM filter: '%s'", |
| 1896 | str(filter_dict)) |
| 1897 | try: |
| 1898 | self._reload_connection() |
| tierno | 69b590e | 2018-03-13 18:52:23 +0100 | [diff] [blame] | 1899 | filter_dict_os = filter_dict.copy() |
| 1900 | if self.api_version3 and "tenant_id" in filter_dict_os: |
| 1901 | filter_dict_os['project_id'] = filter_dict_os.pop('tenant_id') |
| 1902 | sf_dict = self.neutron.list_sfc_port_pair_groups(**filter_dict_os) |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1903 | sf_list = sf_dict["port_pair_groups"] |
| 1904 | self.__sf_os2mano(sf_list) |
| 1905 | return sf_list |
| 1906 | except (neExceptions.ConnectionFailed, ksExceptions.ClientException, |
| 1907 | neExceptions.NeutronException, ConnectionError) as e: |
| 1908 | self._format_exception(e) |
| 1909 | |
| 1910 | def delete_sf(self, sf_id): |
| 1911 | self.logger.debug("Deleting Service Function '%s' from VIM", sf_id) |
| 1912 | try: |
| 1913 | self._reload_connection() |
| Igor D.C | caadc44 | 2017-11-06 12:48:48 +0000 | [diff] [blame] | 1914 | self.neutron.delete_sfc_port_pair_group(sf_id) |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1915 | return sf_id |
| 1916 | except (neExceptions.ConnectionFailed, neExceptions.NeutronException, |
| 1917 | ksExceptions.ClientException, neExceptions.NeutronException, |
| 1918 | ConnectionError) as e: |
| 1919 | self._format_exception(e) |
| 1920 | |
| 1921 | def new_sfp(self, name, classifications, sfs, sfc_encap=True, spi=None): |
| 1922 | self.logger.debug("Adding a new Service Function Path to VIM, " |
| 1923 | "named '%s'", name) |
| 1924 | try: |
| 1925 | new_sfp = None |
| 1926 | self._reload_connection() |
| Igor D.C | caadc44 | 2017-11-06 12:48:48 +0000 | [diff] [blame] | 1927 | # In networking-sfc the MPLS encapsulation is legacy |
| 1928 | # should be used when no full SFC Encapsulation is intended |
| 1929 | sfc_encap = 'mpls' |
| 1930 | if sfc_encap: |
| 1931 | correlation = 'nsh' |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1932 | sfp_dict = {'name': name, |
| 1933 | 'flow_classifiers': classifications, |
| 1934 | 'port_pair_groups': sfs, |
| 1935 | 'chain_parameters': {'correlation': correlation}} |
| 1936 | if spi: |
| 1937 | sfp_dict['chain_id'] = spi |
| Igor D.C | caadc44 | 2017-11-06 12:48:48 +0000 | [diff] [blame] | 1938 | new_sfp = self.neutron.create_sfc_port_chain({'port_chain': sfp_dict}) |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1939 | return new_sfp["port_chain"]["id"] |
| 1940 | except (neExceptions.ConnectionFailed, ksExceptions.ClientException, |
| 1941 | neExceptions.NeutronException, ConnectionError) as e: |
| 1942 | if new_sfp: |
| 1943 | try: |
| Igor D.C | caadc44 | 2017-11-06 12:48:48 +0000 | [diff] [blame] | 1944 | self.neutron.delete_sfc_port_chain(new_sfp['port_chain']['id']) |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1945 | except Exception: |
| 1946 | self.logger.error( |
| 1947 | 'Creation of Service Function Path failed, with ' |
| 1948 | 'subsequent deletion failure as well.') |
| 1949 | self._format_exception(e) |
| 1950 | |
| 1951 | def get_sfp(self, sfp_id): |
| 1952 | self.logger.debug(" Getting Service Function Path %s from VIM", sfp_id) |
| 1953 | filter_dict = {"id": sfp_id} |
| 1954 | sfp_list = self.get_sfp_list(filter_dict) |
| 1955 | if len(sfp_list) == 0: |
| 1956 | raise vimconn.vimconnNotFoundException( |
| 1957 | "Service Function Path '{}' not found".format(sfp_id)) |
| 1958 | elif len(sfp_list) > 1: |
| 1959 | raise vimconn.vimconnConflictException( |
| 1960 | "Found more than one Service Function Path with this criteria") |
| 1961 | sfp = sfp_list[0] |
| 1962 | return sfp |
| 1963 | |
| 1964 | def get_sfp_list(self, filter_dict={}): |
| 1965 | self.logger.debug("Getting Service Function Paths from VIM filter: " |
| 1966 | "'%s'", str(filter_dict)) |
| 1967 | try: |
| 1968 | self._reload_connection() |
| tierno | 69b590e | 2018-03-13 18:52:23 +0100 | [diff] [blame] | 1969 | filter_dict_os = filter_dict.copy() |
| 1970 | if self.api_version3 and "tenant_id" in filter_dict_os: |
| 1971 | filter_dict_os['project_id'] = filter_dict_os.pop('tenant_id') |
| 1972 | sfp_dict = self.neutron.list_sfc_port_chains(**filter_dict_os) |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1973 | sfp_list = sfp_dict["port_chains"] |
| 1974 | self.__sfp_os2mano(sfp_list) |
| 1975 | return sfp_list |
| 1976 | except (neExceptions.ConnectionFailed, ksExceptions.ClientException, |
| 1977 | neExceptions.NeutronException, ConnectionError) as e: |
| 1978 | self._format_exception(e) |
| 1979 | |
| 1980 | def delete_sfp(self, sfp_id): |
| 1981 | self.logger.debug( |
| 1982 | "Deleting Service Function Path '%s' from VIM", sfp_id) |
| 1983 | try: |
| 1984 | self._reload_connection() |
| Igor D.C | caadc44 | 2017-11-06 12:48:48 +0000 | [diff] [blame] | 1985 | self.neutron.delete_sfc_port_chain(sfp_id) |
| Igor Duarte Cardoso | 3cf9bcd | 2017-08-14 16:39:34 +0000 | [diff] [blame] | 1986 | return sfp_id |
| 1987 | except (neExceptions.ConnectionFailed, neExceptions.NeutronException, |
| 1988 | ksExceptions.ClientException, neExceptions.NeutronException, |
| 1989 | ConnectionError) as e: |
| 1990 | self._format_exception(e) |