| 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 | ''' |
| 25 | osconnector implements all the methods to interact with openstack using the python-client. |
| 26 | ''' |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 27 | __author__="Alfonso Tierno, Gerardo Garcia, Pablo Montes, xFlow Research" |
| 28 | __date__ ="$22-jun-2014 11:19:29$" |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 29 | |
| 30 | import vimconn |
| 31 | import json |
| 32 | import yaml |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 33 | import logging |
| garciadeblas | 9f8456e | 2016-09-05 05:02:59 +0200 | [diff] [blame] | 34 | import netaddr |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 35 | import time |
| tierno | 36c0b17 | 2017-01-12 18:32:28 +0100 | [diff] [blame] | 36 | import yaml |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 37 | |
| ahmadsa | 95baa27 | 2016-11-30 09:14:11 +0500 | [diff] [blame] | 38 | from novaclient import client as nClient_v2, exceptions as nvExceptions, api_versions as APIVersion |
| 39 | import keystoneclient.v2_0.client as ksClient_v2 |
| 40 | from novaclient.v2.client import Client as nClient |
| 41 | import keystoneclient.v3.client as ksClient |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 42 | import keystoneclient.exceptions as ksExceptions |
| 43 | import glanceclient.v2.client as glClient |
| 44 | import glanceclient.client as gl1Client |
| 45 | import glanceclient.exc as gl1Exceptions |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 46 | import cinderclient.v2.client as cClient_v2 |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 47 | from httplib import HTTPException |
| ahmadsa | 95baa27 | 2016-11-30 09:14:11 +0500 | [diff] [blame] | 48 | from neutronclient.neutron import client as neClient_v2 |
| 49 | from neutronclient.v2_0 import client as neClient |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 50 | from neutronclient.common import exceptions as neExceptions |
| 51 | from requests.exceptions import ConnectionError |
| 52 | |
| 53 | '''contain the openstack virtual machine status to openmano status''' |
| 54 | vmStatus2manoFormat={'ACTIVE':'ACTIVE', |
| 55 | 'PAUSED':'PAUSED', |
| 56 | 'SUSPENDED': 'SUSPENDED', |
| 57 | 'SHUTOFF':'INACTIVE', |
| 58 | 'BUILD':'BUILD', |
| 59 | 'ERROR':'ERROR','DELETED':'DELETED' |
| 60 | } |
| 61 | netStatus2manoFormat={'ACTIVE':'ACTIVE','PAUSED':'PAUSED','INACTIVE':'INACTIVE','BUILD':'BUILD','ERROR':'ERROR','DELETED':'DELETED' |
| 62 | } |
| 63 | |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 64 | #global var to have a timeout creating and deleting volumes |
| 65 | volume_timeout = 60 |
| montesmoreno | 2a1fc4e | 2017-01-09 16:46:04 +0000 | [diff] [blame] | 66 | server_timeout = 60 |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 67 | |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 68 | class vimconnector(vimconn.vimconnector): |
| tierno | fe78990 | 2016-09-29 14:20:44 +0000 | [diff] [blame] | 69 | def __init__(self, uuid, name, tenant_id, tenant_name, url, url_admin=None, user=None, passwd=None, log_level=None, config={}): |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 70 | '''using common constructor parameters. In this case |
| 71 | 'url' is the keystone authorization url, |
| 72 | 'url_admin' is not use |
| 73 | ''' |
| ahmadsa | 95baa27 | 2016-11-30 09:14:11 +0500 | [diff] [blame] | 74 | self.osc_api_version = 'v2.0' |
| 75 | if config.get('APIversion') == 'v3.3': |
| 76 | self.osc_api_version = 'v3.3' |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 77 | vimconn.vimconnector.__init__(self, uuid, name, tenant_id, tenant_name, url, url_admin, user, passwd, log_level, config) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 78 | |
| 79 | self.k_creds={} |
| 80 | self.n_creds={} |
| tierno | c75a5dc | 2017-01-18 15:53:44 +0100 | [diff] [blame] | 81 | if self.config.get("insecure"): |
| 82 | self.k_creds["insecure"] = True |
| 83 | self.n_creds["insecure"] = True |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 84 | if not url: |
| 85 | raise TypeError, 'url param can not be NoneType' |
| 86 | self.k_creds['auth_url'] = url |
| 87 | self.n_creds['auth_url'] = url |
| tierno | 392f285 | 2016-05-13 12:28:55 +0200 | [diff] [blame] | 88 | if tenant_name: |
| 89 | self.k_creds['tenant_name'] = tenant_name |
| 90 | self.n_creds['project_id'] = tenant_name |
| 91 | if tenant_id: |
| 92 | self.k_creds['tenant_id'] = tenant_id |
| 93 | self.n_creds['tenant_id'] = tenant_id |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 94 | if user: |
| 95 | self.k_creds['username'] = user |
| 96 | self.n_creds['username'] = user |
| 97 | if passwd: |
| 98 | self.k_creds['password'] = passwd |
| 99 | self.n_creds['api_key'] = passwd |
| ahmadsa | 95baa27 | 2016-11-30 09:14:11 +0500 | [diff] [blame] | 100 | if self.osc_api_version == 'v3.3': |
| 101 | self.k_creds['project_name'] = tenant_name |
| 102 | self.k_creds['project_id'] = tenant_id |
| montesmoreno | cf22714 | 2017-01-12 12:24:21 +0000 | [diff] [blame] | 103 | if config.get('region_name'): |
| 104 | self.k_creds['region_name'] = config.get('region_name') |
| 105 | self.n_creds['region_name'] = config.get('region_name') |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 106 | |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 107 | self.reload_client = True |
| tierno | 73ad9e4 | 2016-09-12 18:11:11 +0200 | [diff] [blame] | 108 | self.logger = logging.getLogger('openmano.vim.openstack') |
| tierno | fe78990 | 2016-09-29 14:20:44 +0000 | [diff] [blame] | 109 | if log_level: |
| 110 | self.logger.setLevel( getattr(logging, log_level) ) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 111 | |
| 112 | def __setitem__(self,index, value): |
| 113 | '''Set individuals parameters |
| 114 | Throw TypeError, KeyError |
| 115 | ''' |
| tierno | 392f285 | 2016-05-13 12:28:55 +0200 | [diff] [blame] | 116 | if index=='tenant_id': |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 117 | self.reload_client=True |
| tierno | 392f285 | 2016-05-13 12:28:55 +0200 | [diff] [blame] | 118 | self.tenant_id = value |
| ahmadsa | 95baa27 | 2016-11-30 09:14:11 +0500 | [diff] [blame] | 119 | if self.osc_api_version == 'v3.3': |
| 120 | if value: |
| 121 | self.k_creds['project_id'] = value |
| 122 | self.n_creds['project_id'] = value |
| 123 | else: |
| 124 | del self.k_creds['project_id'] |
| 125 | del self.n_creds['project_id'] |
| tierno | 392f285 | 2016-05-13 12:28:55 +0200 | [diff] [blame] | 126 | else: |
| ahmadsa | 95baa27 | 2016-11-30 09:14:11 +0500 | [diff] [blame] | 127 | if value: |
| 128 | self.k_creds['tenant_id'] = value |
| 129 | self.n_creds['tenant_id'] = value |
| 130 | else: |
| 131 | del self.k_creds['tenant_id'] |
| 132 | del self.n_creds['tenant_id'] |
| tierno | 392f285 | 2016-05-13 12:28:55 +0200 | [diff] [blame] | 133 | elif index=='tenant_name': |
| 134 | self.reload_client=True |
| 135 | self.tenant_name = value |
| ahmadsa | 95baa27 | 2016-11-30 09:14:11 +0500 | [diff] [blame] | 136 | if self.osc_api_version == 'v3.3': |
| 137 | if value: |
| 138 | self.k_creds['project_name'] = value |
| 139 | self.n_creds['project_name'] = value |
| 140 | else: |
| 141 | del self.k_creds['project_name'] |
| 142 | del self.n_creds['project_name'] |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 143 | else: |
| ahmadsa | 95baa27 | 2016-11-30 09:14:11 +0500 | [diff] [blame] | 144 | if value: |
| 145 | self.k_creds['tenant_name'] = value |
| 146 | self.n_creds['project_id'] = value |
| 147 | else: |
| 148 | del self.k_creds['tenant_name'] |
| 149 | del self.n_creds['project_id'] |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 150 | elif index=='user': |
| 151 | self.reload_client=True |
| 152 | self.user = value |
| 153 | if value: |
| 154 | self.k_creds['username'] = value |
| 155 | self.n_creds['username'] = value |
| 156 | else: |
| 157 | del self.k_creds['username'] |
| 158 | del self.n_creds['username'] |
| 159 | elif index=='passwd': |
| 160 | self.reload_client=True |
| 161 | self.passwd = value |
| 162 | if value: |
| 163 | self.k_creds['password'] = value |
| 164 | self.n_creds['api_key'] = value |
| 165 | else: |
| 166 | del self.k_creds['password'] |
| 167 | del self.n_creds['api_key'] |
| 168 | elif index=='url': |
| 169 | self.reload_client=True |
| 170 | self.url = value |
| 171 | if value: |
| 172 | self.k_creds['auth_url'] = value |
| 173 | self.n_creds['auth_url'] = value |
| 174 | else: |
| 175 | raise TypeError, 'url param can not be NoneType' |
| 176 | else: |
| 177 | vimconn.vimconnector.__setitem__(self,index, value) |
| 178 | |
| 179 | def _reload_connection(self): |
| 180 | '''Called before any operation, it check if credentials has changed |
| 181 | Throw keystoneclient.apiclient.exceptions.AuthorizationFailure |
| 182 | ''' |
| 183 | #TODO control the timing and possible token timeout, but it seams that python client does this task for us :-) |
| 184 | if self.reload_client: |
| 185 | #test valid params |
| 186 | if len(self.n_creds) <4: |
| 187 | raise ksExceptions.ClientException("Not enough parameters to connect to openstack") |
| ahmadsa | 95baa27 | 2016-11-30 09:14:11 +0500 | [diff] [blame] | 188 | if self.osc_api_version == 'v3.3': |
| 189 | self.nova = nClient(APIVersion(version_str='2'), **self.n_creds) |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 190 | #TODO To be updated for v3 |
| 191 | #self.cinder = cClient.Client(**self.n_creds) |
| ahmadsa | 95baa27 | 2016-11-30 09:14:11 +0500 | [diff] [blame] | 192 | self.keystone = ksClient.Client(**self.k_creds) |
| 193 | self.ne_endpoint=self.keystone.service_catalog.url_for(service_type='network', endpoint_type='publicURL') |
| 194 | self.neutron = neClient.Client(APIVersion(version_str='2'), endpoint_url=self.ne_endpoint, token=self.keystone.auth_token, **self.k_creds) |
| 195 | else: |
| 196 | self.nova = nClient_v2.Client('2', **self.n_creds) |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 197 | self.cinder = cClient_v2.Client(**self.n_creds) |
| ahmadsa | 95baa27 | 2016-11-30 09:14:11 +0500 | [diff] [blame] | 198 | self.keystone = ksClient_v2.Client(**self.k_creds) |
| 199 | self.ne_endpoint=self.keystone.service_catalog.url_for(service_type='network', endpoint_type='publicURL') |
| 200 | self.neutron = neClient_v2.Client('2.0', endpoint_url=self.ne_endpoint, token=self.keystone.auth_token, **self.k_creds) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 201 | self.glance_endpoint = self.keystone.service_catalog.url_for(service_type='image', endpoint_type='publicURL') |
| 202 | self.glance = glClient.Client(self.glance_endpoint, token=self.keystone.auth_token, **self.k_creds) #TODO check k_creds vs n_creds |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 203 | self.reload_client = False |
| ahmadsa | 95baa27 | 2016-11-30 09:14:11 +0500 | [diff] [blame] | 204 | |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 205 | def __net_os2mano(self, net_list_dict): |
| 206 | '''Transform the net openstack format to mano format |
| 207 | net_list_dict can be a list of dict or a single dict''' |
| 208 | if type(net_list_dict) is dict: |
| 209 | net_list_=(net_list_dict,) |
| 210 | elif type(net_list_dict) is list: |
| 211 | net_list_=net_list_dict |
| 212 | else: |
| 213 | raise TypeError("param net_list_dict must be a list or a dictionary") |
| 214 | for net in net_list_: |
| 215 | if net.get('provider:network_type') == "vlan": |
| 216 | net['type']='data' |
| 217 | else: |
| 218 | net['type']='bridge' |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 219 | |
| 220 | |
| 221 | |
| 222 | def _format_exception(self, exception): |
| 223 | '''Transform a keystone, nova, neutron exception into a vimconn exception''' |
| 224 | if isinstance(exception, (HTTPException, gl1Exceptions.HTTPException, gl1Exceptions.CommunicationError, |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 225 | ConnectionError, ksExceptions.ConnectionError, neExceptions.ConnectionFailed |
| 226 | )): |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 227 | raise vimconn.vimconnConnectionException(type(exception).__name__ + ": " + str(exception)) |
| 228 | elif isinstance(exception, (nvExceptions.ClientException, ksExceptions.ClientException, |
| 229 | neExceptions.NeutronException, nvExceptions.BadRequest)): |
| 230 | raise vimconn.vimconnUnexpectedResponse(type(exception).__name__ + ": " + str(exception)) |
| 231 | elif isinstance(exception, (neExceptions.NetworkNotFoundClient, nvExceptions.NotFound)): |
| 232 | raise vimconn.vimconnNotFoundException(type(exception).__name__ + ": " + str(exception)) |
| 233 | elif isinstance(exception, nvExceptions.Conflict): |
| 234 | raise vimconn.vimconnConflictException(type(exception).__name__ + ": " + str(exception)) |
| 235 | else: # () |
| 236 | raise vimconn.vimconnConnectionException(type(exception).__name__ + ": " + str(exception)) |
| 237 | |
| 238 | def get_tenant_list(self, filter_dict={}): |
| 239 | '''Obtain tenants of VIM |
| 240 | filter_dict can contain the following keys: |
| 241 | name: filter by tenant name |
| 242 | id: filter by tenant uuid/id |
| 243 | <other VIM specific> |
| 244 | Returns the tenant list of dictionaries: [{'name':'<name>, 'id':'<id>, ...}, ...] |
| 245 | ''' |
| ahmadsa | 95baa27 | 2016-11-30 09:14:11 +0500 | [diff] [blame] | 246 | self.logger.debug("Getting tenants from VIM filter: '%s'", str(filter_dict)) |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 247 | try: |
| 248 | self._reload_connection() |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 249 | if self.osc_api_version == 'v3.3': |
| ahmadsa | 95baa27 | 2016-11-30 09:14:11 +0500 | [diff] [blame] | 250 | project_class_list=self.keystone.projects.findall(**filter_dict) |
| 251 | else: |
| 252 | project_class_list=self.keystone.tenants.findall(**filter_dict) |
| 253 | project_list=[] |
| 254 | for project in project_class_list: |
| 255 | project_list.append(project.to_dict()) |
| 256 | return project_list |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 257 | except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 258 | self._format_exception(e) |
| 259 | |
| 260 | def new_tenant(self, tenant_name, tenant_description): |
| 261 | '''Adds a new tenant to openstack VIM. Returns the tenant identifier''' |
| 262 | self.logger.debug("Adding a new tenant name: %s", tenant_name) |
| 263 | try: |
| 264 | self._reload_connection() |
| ahmadsa | 95baa27 | 2016-11-30 09:14:11 +0500 | [diff] [blame] | 265 | if self.osc_api_version == 'v3.3': |
| 266 | project=self.keystone.projects.create(tenant_name, tenant_description) |
| 267 | else: |
| 268 | project=self.keystone.tenants.create(tenant_name, tenant_description) |
| 269 | return project.id |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 270 | except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 271 | self._format_exception(e) |
| 272 | |
| 273 | def delete_tenant(self, tenant_id): |
| 274 | '''Delete a tenant from openstack VIM. Returns the old tenant identifier''' |
| 275 | self.logger.debug("Deleting tenant %s from VIM", tenant_id) |
| 276 | try: |
| 277 | self._reload_connection() |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 278 | if self.osc_api_version == 'v3.3': |
| ahmadsa | 95baa27 | 2016-11-30 09:14:11 +0500 | [diff] [blame] | 279 | self.keystone.projects.delete(tenant_id) |
| 280 | else: |
| 281 | self.keystone.tenants.delete(tenant_id) |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 282 | return tenant_id |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 283 | except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 284 | self._format_exception(e) |
| ahmadsa | 95baa27 | 2016-11-30 09:14:11 +0500 | [diff] [blame] | 285 | |
| garciadeblas | 9f8456e | 2016-09-05 05:02:59 +0200 | [diff] [blame] | 286 | 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] | 287 | '''Adds a tenant network to VIM. Returns the network identifier''' |
| 288 | 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] | 289 | #self.logger.debug(">>>>>>>>>>>>>>>>>> IP profile %s", str(ip_profile)) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 290 | try: |
| garciadeblas | edca7b3 | 2016-09-29 14:01:52 +0000 | [diff] [blame] | 291 | new_net = None |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 292 | self._reload_connection() |
| 293 | network_dict = {'name': net_name, 'admin_state_up': True} |
| 294 | if net_type=="data" or net_type=="ptp": |
| 295 | if self.config.get('dataplane_physical_net') == None: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 296 | 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] | 297 | network_dict["provider:physical_network"] = self.config['dataplane_physical_net'] #"physnet_sriov" #TODO physical |
| 298 | network_dict["provider:network_type"] = "vlan" |
| 299 | if vlan!=None: |
| 300 | network_dict["provider:network_type"] = vlan |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 301 | network_dict["shared"]=shared |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 302 | new_net=self.neutron.create_network({'network':network_dict}) |
| 303 | #print new_net |
| garciadeblas | 9f8456e | 2016-09-05 05:02:59 +0200 | [diff] [blame] | 304 | #create subnetwork, even if there is no profile |
| 305 | if not ip_profile: |
| 306 | ip_profile = {} |
| 307 | if 'subnet_address' not in ip_profile: |
| 308 | #Fake subnet is required |
| 309 | ip_profile['subnet_address'] = "192.168.111.0/24" |
| 310 | if 'ip_version' not in ip_profile: |
| 311 | ip_profile['ip_version'] = "IPv4" |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 312 | subnet={"name":net_name+"-subnet", |
| 313 | "network_id": new_net["network"]["id"], |
| garciadeblas | 9f8456e | 2016-09-05 05:02:59 +0200 | [diff] [blame] | 314 | "ip_version": 4 if ip_profile['ip_version']=="IPv4" else 6, |
| 315 | "cidr": ip_profile['subnet_address'] |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 316 | } |
| garciadeblas | 9f8456e | 2016-09-05 05:02:59 +0200 | [diff] [blame] | 317 | if 'gateway_address' in ip_profile: |
| 318 | subnet['gateway_ip'] = ip_profile['gateway_address'] |
| garciadeblas | edca7b3 | 2016-09-29 14:01:52 +0000 | [diff] [blame] | 319 | if ip_profile.get('dns_address'): |
| garciadeblas | 9f8456e | 2016-09-05 05:02:59 +0200 | [diff] [blame] | 320 | #TODO: manage dns_address as a list of addresses separated by commas |
| 321 | subnet['dns_nameservers'] = [] |
| 322 | subnet['dns_nameservers'].append(ip_profile['dns_address']) |
| 323 | if 'dhcp_enabled' in ip_profile: |
| 324 | subnet['enable_dhcp'] = False if ip_profile['dhcp_enabled']=="false" else True |
| 325 | if 'dhcp_start_address' in ip_profile: |
| 326 | subnet['allocation_pools']=[] |
| 327 | subnet['allocation_pools'].append(dict()) |
| 328 | subnet['allocation_pools'][0]['start'] = ip_profile['dhcp_start_address'] |
| 329 | if 'dhcp_count' in ip_profile: |
| 330 | #parts = ip_profile['dhcp_start_address'].split('.') |
| 331 | #ip_int = (int(parts[0]) << 24) + (int(parts[1]) << 16) + (int(parts[2]) << 8) + int(parts[3]) |
| 332 | ip_int = int(netaddr.IPAddress(ip_profile['dhcp_start_address'])) |
| garciadeblas | 21d795b | 2016-09-29 17:31:46 +0200 | [diff] [blame] | 333 | ip_int += ip_profile['dhcp_count'] - 1 |
| garciadeblas | 9f8456e | 2016-09-05 05:02:59 +0200 | [diff] [blame] | 334 | ip_str = str(netaddr.IPAddress(ip_int)) |
| 335 | subnet['allocation_pools'][0]['end'] = ip_str |
| garciadeblas | edca7b3 | 2016-09-29 14:01:52 +0000 | [diff] [blame] | 336 | #self.logger.debug(">>>>>>>>>>>>>>>>>> Subnet: %s", str(subnet)) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 337 | self.neutron.create_subnet({"subnet": subnet} ) |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 338 | return new_net["network"]["id"] |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 339 | except (neExceptions.ConnectionFailed, ksExceptions.ClientException, neExceptions.NeutronException, ConnectionError) as e: |
| garciadeblas | edca7b3 | 2016-09-29 14:01:52 +0000 | [diff] [blame] | 340 | if new_net: |
| 341 | self.neutron.delete_network(new_net['network']['id']) |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 342 | self._format_exception(e) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 343 | |
| 344 | def get_network_list(self, filter_dict={}): |
| 345 | '''Obtain tenant networks of VIM |
| 346 | Filter_dict can be: |
| 347 | name: network name |
| 348 | id: network uuid |
| 349 | shared: boolean |
| 350 | tenant_id: tenant |
| 351 | admin_state_up: boolean |
| 352 | status: 'ACTIVE' |
| 353 | Returns the network list of dictionaries |
| 354 | ''' |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 355 | self.logger.debug("Getting network from VIM filter: '%s'", str(filter_dict)) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 356 | try: |
| 357 | self._reload_connection() |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 358 | if self.osc_api_version == 'v3.3' and "tenant_id" in filter_dict: |
| ahmadsa | 95baa27 | 2016-11-30 09:14:11 +0500 | [diff] [blame] | 359 | filter_dict['project_id'] = filter_dict.pop('tenant_id') |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 360 | net_dict=self.neutron.list_networks(**filter_dict) |
| 361 | net_list=net_dict["networks"] |
| 362 | self.__net_os2mano(net_list) |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 363 | return net_list |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 364 | except (neExceptions.ConnectionFailed, ksExceptions.ClientException, neExceptions.NeutronException, ConnectionError) as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 365 | self._format_exception(e) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 366 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 367 | def get_network(self, net_id): |
| 368 | '''Obtain details of network from VIM |
| 369 | Returns the network information from a network id''' |
| 370 | self.logger.debug(" Getting tenant network %s from VIM", net_id) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 371 | filter_dict={"id": net_id} |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 372 | net_list = self.get_network_list(filter_dict) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 373 | if len(net_list)==0: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 374 | raise vimconn.vimconnNotFoundException("Network '{}' not found".format(net_id)) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 375 | elif len(net_list)>1: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 376 | raise vimconn.vimconnConflictException("Found more than one network with this criteria") |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 377 | net = net_list[0] |
| 378 | subnets=[] |
| 379 | for subnet_id in net.get("subnets", () ): |
| 380 | try: |
| 381 | subnet = self.neutron.show_subnet(subnet_id) |
| 382 | except Exception as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 383 | self.logger.error("osconnector.get_network(): Error getting subnet %s %s" % (net_id, str(e))) |
| 384 | subnet = {"id": subnet_id, "fault": str(e)} |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 385 | subnets.append(subnet) |
| 386 | net["subnets"] = subnets |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 387 | return net |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 388 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 389 | def delete_network(self, net_id): |
| 390 | '''Deletes a tenant network from VIM. Returns the old network identifier''' |
| 391 | self.logger.debug("Deleting network '%s' from VIM", net_id) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 392 | try: |
| 393 | self._reload_connection() |
| 394 | #delete VM ports attached to this networks before the network |
| 395 | ports = self.neutron.list_ports(network_id=net_id) |
| 396 | for p in ports['ports']: |
| 397 | try: |
| 398 | self.neutron.delete_port(p["id"]) |
| 399 | except Exception as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 400 | self.logger.error("Error deleting port %s: %s", p["id"], str(e)) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 401 | self.neutron.delete_network(net_id) |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 402 | return net_id |
| 403 | except (neExceptions.ConnectionFailed, neExceptions.NetworkNotFoundClient, neExceptions.NeutronException, |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 404 | ksExceptions.ClientException, neExceptions.NeutronException, ConnectionError) as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 405 | self._format_exception(e) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 406 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 407 | def refresh_nets_status(self, net_list): |
| 408 | '''Get the status of the networks |
| 409 | Params: the list of network identifiers |
| 410 | Returns a dictionary with: |
| 411 | net_id: #VIM id of this network |
| 412 | status: #Mandatory. Text with one of: |
| 413 | # DELETED (not found at vim) |
| 414 | # VIM_ERROR (Cannot connect to VIM, VIM response error, ...) |
| 415 | # OTHER (Vim reported other status not understood) |
| 416 | # ERROR (VIM indicates an ERROR status) |
| 417 | # ACTIVE, INACTIVE, DOWN (admin down), |
| 418 | # BUILD (on building process) |
| 419 | # |
| 420 | error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR |
| 421 | vim_info: #Text with plain information obtained from vim (yaml.safe_dump) |
| 422 | |
| 423 | ''' |
| 424 | net_dict={} |
| 425 | for net_id in net_list: |
| 426 | net = {} |
| 427 | try: |
| 428 | net_vim = self.get_network(net_id) |
| 429 | if net_vim['status'] in netStatus2manoFormat: |
| 430 | net["status"] = netStatus2manoFormat[ net_vim['status'] ] |
| 431 | else: |
| 432 | net["status"] = "OTHER" |
| 433 | net["error_msg"] = "VIM status reported " + net_vim['status'] |
| 434 | |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 435 | if net['status'] == "ACTIVE" and not net_vim['admin_state_up']: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 436 | net['status'] = 'DOWN' |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 437 | try: |
| 438 | net['vim_info'] = yaml.safe_dump(net_vim, default_flow_style=True, width=256) |
| 439 | except yaml.representer.RepresenterError: |
| 440 | net['vim_info'] = str(net_vim) |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 441 | if net_vim.get('fault'): #TODO |
| 442 | net['error_msg'] = str(net_vim['fault']) |
| 443 | except vimconn.vimconnNotFoundException as e: |
| 444 | self.logger.error("Exception getting net status: %s", str(e)) |
| 445 | net['status'] = "DELETED" |
| 446 | net['error_msg'] = str(e) |
| 447 | except vimconn.vimconnException as e: |
| 448 | self.logger.error("Exception getting net status: %s", str(e)) |
| 449 | net['status'] = "VIM_ERROR" |
| 450 | net['error_msg'] = str(e) |
| 451 | net_dict[net_id] = net |
| 452 | return net_dict |
| 453 | |
| 454 | def get_flavor(self, flavor_id): |
| 455 | '''Obtain flavor details from the VIM. Returns the flavor dict details''' |
| 456 | self.logger.debug("Getting flavor '%s'", flavor_id) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 457 | try: |
| 458 | self._reload_connection() |
| 459 | flavor = self.nova.flavors.find(id=flavor_id) |
| 460 | #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] | 461 | return flavor.to_dict() |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 462 | except (nvExceptions.NotFound, nvExceptions.ClientException, ksExceptions.ClientException, ConnectionError) as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 463 | self._format_exception(e) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 464 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 465 | def new_flavor(self, flavor_data, change_name_if_used=True): |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 466 | '''Adds a tenant flavor to openstack VIM |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 467 | 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] | 468 | Returns the flavor identifier |
| 469 | ''' |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 470 | self.logger.debug("Adding flavor '%s'", str(flavor_data)) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 471 | retry=0 |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 472 | max_retries=3 |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 473 | name_suffix = 0 |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 474 | name=flavor_data['name'] |
| 475 | while retry<max_retries: |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 476 | retry+=1 |
| 477 | try: |
| 478 | self._reload_connection() |
| 479 | if change_name_if_used: |
| 480 | #get used names |
| 481 | fl_names=[] |
| 482 | fl=self.nova.flavors.list() |
| 483 | for f in fl: |
| 484 | fl_names.append(f.name) |
| 485 | while name in fl_names: |
| 486 | name_suffix += 1 |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 487 | name = flavor_data['name']+"-" + str(name_suffix) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 488 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 489 | ram = flavor_data.get('ram',64) |
| 490 | vcpus = flavor_data.get('vcpus',1) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 491 | numa_properties=None |
| 492 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 493 | extended = flavor_data.get("extended") |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 494 | if extended: |
| 495 | numas=extended.get("numas") |
| 496 | if numas: |
| 497 | numa_nodes = len(numas) |
| 498 | if numa_nodes > 1: |
| 499 | return -1, "Can not add flavor with more than one numa" |
| 500 | numa_properties = {"hw:numa_nodes":str(numa_nodes)} |
| 501 | numa_properties["hw:mem_page_size"] = "large" |
| 502 | numa_properties["hw:cpu_policy"] = "dedicated" |
| 503 | numa_properties["hw:numa_mempolicy"] = "strict" |
| 504 | for numa in numas: |
| 505 | #overwrite ram and vcpus |
| 506 | ram = numa['memory']*1024 |
| 507 | if 'paired-threads' in numa: |
| 508 | vcpus = numa['paired-threads']*2 |
| 509 | numa_properties["hw:cpu_threads_policy"] = "prefer" |
| 510 | elif 'cores' in numa: |
| 511 | vcpus = numa['cores'] |
| 512 | #numa_properties["hw:cpu_threads_policy"] = "prefer" |
| 513 | elif 'threads' in numa: |
| 514 | vcpus = numa['threads'] |
| 515 | numa_properties["hw:cpu_policy"] = "isolated" |
| 516 | for interface in numa.get("interfaces",() ): |
| 517 | if interface["dedicated"]=="yes": |
| tierno | 809a780 | 2016-07-08 13:31:24 +0200 | [diff] [blame] | 518 | raise vimconn.vimconnException("Passthrough interfaces are not supported for the openstack connector", http_code=vimconn.HTTP_Service_Unavailable) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 519 | #TODO, add the key 'pci_passthrough:alias"="<label at config>:<number ifaces>"' when a way to connect it is available |
| 520 | |
| 521 | #create flavor |
| 522 | new_flavor=self.nova.flavors.create(name, |
| 523 | ram, |
| 524 | vcpus, |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 525 | flavor_data.get('disk',1), |
| 526 | is_public=flavor_data.get('is_public', True) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 527 | ) |
| 528 | #add metadata |
| 529 | if numa_properties: |
| 530 | new_flavor.set_keys(numa_properties) |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 531 | return new_flavor.id |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 532 | except nvExceptions.Conflict as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 533 | if change_name_if_used and retry < max_retries: |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 534 | continue |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 535 | self._format_exception(e) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 536 | #except nvExceptions.BadRequest as e: |
| 537 | except (ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 538 | self._format_exception(e) |
| 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_flavor(self,flavor_id): |
| 541 | '''Deletes a tenant flavor from openstack VIM. Returns the old flavor_id |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 542 | ''' |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 543 | try: |
| 544 | self._reload_connection() |
| 545 | self.nova.flavors.delete(flavor_id) |
| 546 | return flavor_id |
| 547 | #except nvExceptions.BadRequest as e: |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 548 | except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 549 | self._format_exception(e) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 550 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 551 | def new_image(self,image_dict): |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 552 | ''' |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 553 | Adds a tenant image to VIM. imge_dict is a dictionary with: |
| 554 | name: name |
| 555 | disk_format: qcow2, vhd, vmdk, raw (by default), ... |
| 556 | location: path or URI |
| 557 | public: "yes" or "no" |
| 558 | metadata: metadata of the image |
| 559 | Returns the image_id |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 560 | ''' |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 561 | #using version 1 of glance client |
| 562 | glancev1 = gl1Client.Client('1',self.glance_endpoint, token=self.keystone.auth_token, **self.k_creds) #TODO check k_creds vs n_creds |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 563 | retry=0 |
| 564 | max_retries=3 |
| 565 | while retry<max_retries: |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 566 | retry+=1 |
| 567 | try: |
| 568 | self._reload_connection() |
| 569 | #determine format http://docs.openstack.org/developer/glance/formats.html |
| 570 | if "disk_format" in image_dict: |
| 571 | disk_format=image_dict["disk_format"] |
| garciadeblas | 1448045 | 2017-01-10 13:08:07 +0100 | [diff] [blame] | 572 | else: #autodiscover based on extension |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 573 | if image_dict['location'][-6:]==".qcow2": |
| 574 | disk_format="qcow2" |
| 575 | elif image_dict['location'][-4:]==".vhd": |
| 576 | disk_format="vhd" |
| 577 | elif image_dict['location'][-5:]==".vmdk": |
| 578 | disk_format="vmdk" |
| 579 | elif image_dict['location'][-4:]==".vdi": |
| 580 | disk_format="vdi" |
| 581 | elif image_dict['location'][-4:]==".iso": |
| 582 | disk_format="iso" |
| 583 | elif image_dict['location'][-4:]==".aki": |
| 584 | disk_format="aki" |
| 585 | elif image_dict['location'][-4:]==".ari": |
| 586 | disk_format="ari" |
| 587 | elif image_dict['location'][-4:]==".ami": |
| 588 | disk_format="ami" |
| 589 | else: |
| 590 | disk_format="raw" |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 591 | 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] | 592 | if image_dict['location'][0:4]=="http": |
| 593 | new_image = glancev1.images.create(name=image_dict['name'], is_public=image_dict.get('public',"yes")=="yes", |
| 594 | container_format="bare", location=image_dict['location'], disk_format=disk_format) |
| 595 | else: #local path |
| 596 | with open(image_dict['location']) as fimage: |
| 597 | new_image = glancev1.images.create(name=image_dict['name'], is_public=image_dict.get('public',"yes")=="yes", |
| 598 | container_format="bare", data=fimage, disk_format=disk_format) |
| 599 | #insert metadata. We cannot use 'new_image.properties.setdefault' |
| 600 | #because nova and glance are "INDEPENDENT" and we are using nova for reading metadata |
| 601 | new_image_nova=self.nova.images.find(id=new_image.id) |
| 602 | new_image_nova.metadata.setdefault('location',image_dict['location']) |
| 603 | metadata_to_load = image_dict.get('metadata') |
| 604 | if metadata_to_load: |
| 605 | for k,v in yaml.load(metadata_to_load).iteritems(): |
| 606 | new_image_nova.metadata.setdefault(k,v) |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 607 | return new_image.id |
| 608 | except (nvExceptions.Conflict, ksExceptions.ClientException, nvExceptions.ClientException) as e: |
| 609 | self._format_exception(e) |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 610 | except (HTTPException, gl1Exceptions.HTTPException, gl1Exceptions.CommunicationError, ConnectionError) as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 611 | if retry==max_retries: |
| 612 | continue |
| 613 | self._format_exception(e) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 614 | except IOError as e: #can not open the file |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 615 | raise vimconn.vimconnConnectionException(type(e).__name__ + ": " + str(e)+ " for " + image_dict['location'], |
| 616 | http_code=vimconn.HTTP_Bad_Request) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 617 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 618 | def delete_image(self, image_id): |
| 619 | '''Deletes a tenant image from openstack VIM. Returns the old id |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 620 | ''' |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 621 | try: |
| 622 | self._reload_connection() |
| 623 | self.nova.images.delete(image_id) |
| 624 | return image_id |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 625 | 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] | 626 | self._format_exception(e) |
| 627 | |
| 628 | def get_image_id_from_path(self, path): |
| garciadeblas | b69fa9f | 2016-09-28 12:04:10 +0200 | [diff] [blame] | 629 | '''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] | 630 | try: |
| 631 | self._reload_connection() |
| 632 | images = self.nova.images.list() |
| 633 | for image in images: |
| 634 | if image.metadata.get("location")==path: |
| 635 | return image.id |
| 636 | raise vimconn.vimconnNotFoundException("image with location '{}' not found".format( path)) |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 637 | except (ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 638 | self._format_exception(e) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 639 | |
| garciadeblas | b69fa9f | 2016-09-28 12:04:10 +0200 | [diff] [blame] | 640 | def get_image_list(self, filter_dict={}): |
| 641 | '''Obtain tenant images from VIM |
| 642 | Filter_dict can be: |
| 643 | id: image id |
| 644 | name: image name |
| 645 | checksum: image checksum |
| 646 | Returns the image list of dictionaries: |
| 647 | [{<the fields at Filter_dict plus some VIM specific>}, ...] |
| 648 | List can be empty |
| 649 | ''' |
| 650 | self.logger.debug("Getting image list from VIM filter: '%s'", str(filter_dict)) |
| 651 | try: |
| 652 | self._reload_connection() |
| 653 | filter_dict_os=filter_dict.copy() |
| 654 | #First we filter by the available filter fields: name, id. The others are removed. |
| 655 | filter_dict_os.pop('checksum',None) |
| 656 | image_list=self.nova.images.findall(**filter_dict_os) |
| 657 | if len(image_list)==0: |
| 658 | return [] |
| 659 | #Then we filter by the rest of filter fields: checksum |
| 660 | filtered_list = [] |
| 661 | for image in image_list: |
| tierno | 4540ea5 | 2017-01-18 17:44:32 +0100 | [diff] [blame] | 662 | image_class=self.glance.images.get(image.id) |
| 663 | if 'checksum' not in filter_dict or image_class['checksum']==filter_dict.get('checksum'): |
| 664 | filtered_list.append(image_class.copy()) |
| garciadeblas | b69fa9f | 2016-09-28 12:04:10 +0200 | [diff] [blame] | 665 | return filtered_list |
| 666 | except (ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e: |
| 667 | self._format_exception(e) |
| 668 | |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 669 | def new_vminstance(self,name,description,start,image_id,flavor_id,net_list,cloud_config=None,disk_list=None): |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 670 | '''Adds a VM instance to VIM |
| 671 | Params: |
| 672 | start: indicates if VM must start or boot in pause mode. Ignored |
| 673 | image_id,flavor_id: iamge and flavor uuid |
| 674 | net_list: list of interfaces, each one is a dictionary with: |
| 675 | name: |
| 676 | net_id: network uuid to connect |
| 677 | vpci: virtual vcpi to assign, ignored because openstack lack #TODO |
| 678 | model: interface model, ignored #TODO |
| 679 | mac_address: used for SR-IOV ifaces #TODO for other types |
| 680 | use: 'data', 'bridge', 'mgmt' |
| 681 | type: 'virtual', 'PF', 'VF', 'VFnotShared' |
| 682 | vim_id: filled/added by this function |
| ahmadsa | f853d45 | 2016-12-22 11:33:47 +0500 | [diff] [blame] | 683 | floating_ip: True/False (or it can be None) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 684 | #TODO ip, security groups |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 685 | Returns the instance identifier |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 686 | ''' |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 687 | self.logger.debug("Creating VM image '%s' flavor '%s' nics='%s'",image_id, flavor_id,str(net_list)) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 688 | try: |
| tierno | 6e11623 | 2016-07-18 13:01:40 +0200 | [diff] [blame] | 689 | metadata={} |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 690 | net_list_vim=[] |
| ahmadsa | f853d45 | 2016-12-22 11:33:47 +0500 | [diff] [blame] | 691 | external_network=[] #list of external networks to be connected to instance, later on used to create floating_ip |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 692 | self._reload_connection() |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 693 | metadata_vpci={} #For a specific neutron plugin |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 694 | for net in net_list: |
| 695 | if not net.get("net_id"): #skip non connected iface |
| 696 | continue |
| ahmadsa | f853d45 | 2016-12-22 11:33:47 +0500 | [diff] [blame] | 697 | if net["type"]=="virtual" or net["type"]=="VF": |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 698 | port_dict={ |
| ahmadsa | f853d45 | 2016-12-22 11:33:47 +0500 | [diff] [blame] | 699 | "network_id": net["net_id"], |
| 700 | "name": net.get("name"), |
| 701 | "admin_state_up": True |
| 702 | } |
| 703 | if net["type"]=="virtual": |
| 704 | if "vpci" in net: |
| 705 | metadata_vpci[ net["net_id"] ] = [[ net["vpci"], "" ]] |
| 706 | else: # for VF |
| 707 | if "vpci" in net: |
| 708 | if "VF" not in metadata_vpci: |
| 709 | metadata_vpci["VF"]=[] |
| 710 | metadata_vpci["VF"].append([ net["vpci"], "" ]) |
| 711 | port_dict["binding:vnic_type"]="direct" |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 712 | if not port_dict["name"]: |
| ahmadsa | f853d45 | 2016-12-22 11:33:47 +0500 | [diff] [blame] | 713 | port_dict["name"]=name |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 714 | if net.get("mac_address"): |
| 715 | port_dict["mac_address"]=net["mac_address"] |
| montesmoreno | cf22714 | 2017-01-12 12:24:21 +0000 | [diff] [blame] | 716 | if net.get("port_security") == False: |
| montesmoreno | 2a1fc4e | 2017-01-09 16:46:04 +0000 | [diff] [blame] | 717 | port_dict["port_security_enabled"]=net["port_security"] |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 718 | new_port = self.neutron.create_port({"port": port_dict }) |
| 719 | net["mac_adress"] = new_port["port"]["mac_address"] |
| 720 | net["vim_id"] = new_port["port"]["id"] |
| ahmadsa | f853d45 | 2016-12-22 11:33:47 +0500 | [diff] [blame] | 721 | net["ip"] = new_port["port"].get("fixed_ips", [{}])[0].get("ip_address") |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 722 | net_list_vim.append({"port-id": new_port["port"]["id"]}) |
| ahmadsa | f853d45 | 2016-12-22 11:33:47 +0500 | [diff] [blame] | 723 | else: # for PF |
| 724 | self.logger.warn("new_vminstance: Warning, can not connect a passthrough interface ") |
| 725 | #TODO insert this when openstack consider passthrough ports as openstack neutron ports |
| 726 | if net.get('floating_ip', False): |
| tierno | f8383b8 | 2017-01-18 15:49:48 +0100 | [diff] [blame] | 727 | net['exit_on_floating_ip_error'] = True |
| ahmadsa | f853d45 | 2016-12-22 11:33:47 +0500 | [diff] [blame] | 728 | external_network.append(net) |
| tierno | f8383b8 | 2017-01-18 15:49:48 +0100 | [diff] [blame] | 729 | elif net['use'] == 'mgmt' and self.config.get('use_floating_ip'): |
| 730 | net['exit_on_floating_ip_error'] = False |
| 731 | external_network.append(net) |
| 732 | |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 733 | if metadata_vpci: |
| 734 | metadata = {"pci_assignement": json.dumps(metadata_vpci)} |
| tierno | afbced4 | 2016-07-23 01:43:53 +0200 | [diff] [blame] | 735 | if len(metadata["pci_assignement"]) >255: |
| tierno | 6e11623 | 2016-07-18 13:01:40 +0200 | [diff] [blame] | 736 | #limit the metadata size |
| 737 | #metadata["pci_assignement"] = metadata["pci_assignement"][0:255] |
| 738 | self.logger.warn("Metadata deleted since it exceeds the expected length (255) ") |
| 739 | metadata = {} |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 740 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 741 | self.logger.debug("name '%s' image_id '%s'flavor_id '%s' net_list_vim '%s' description '%s' metadata %s", |
| 742 | name, image_id, flavor_id, str(net_list_vim), description, str(metadata)) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 743 | |
| 744 | security_groups = self.config.get('security_groups') |
| 745 | if type(security_groups) is str: |
| 746 | security_groups = ( security_groups, ) |
| tierno | 36c0b17 | 2017-01-12 18:32:28 +0100 | [diff] [blame] | 747 | #cloud config |
| 748 | userdata=None |
| 749 | config_drive = None |
| tierno | a4e1a6e | 2016-08-31 14:19:40 +0200 | [diff] [blame] | 750 | if isinstance(cloud_config, dict): |
| tierno | 36c0b17 | 2017-01-12 18:32:28 +0100 | [diff] [blame] | 751 | if cloud_config.get("user-data"): |
| 752 | userdata=cloud_config["user-data"] |
| 753 | if cloud_config.get("boot-data-drive") != None: |
| 754 | config_drive = cloud_config["boot-data-drive"] |
| 755 | if cloud_config.get("config-files") or cloud_config.get("users") or cloud_config.get("key-pairs"): |
| 756 | if userdata: |
| 757 | raise vimconn.vimconnConflictException("Cloud-config cannot contain both 'userdata' and 'config-files'/'users'/'key-pairs'") |
| 758 | userdata_dict={} |
| 759 | #default user |
| 760 | if cloud_config.get("key-pairs"): |
| 761 | userdata_dict["ssh-authorized-keys"] = cloud_config["key-pairs"] |
| 762 | userdata_dict["users"] = [{"default": None, "ssh-authorized-keys": cloud_config["key-pairs"] }] |
| 763 | if cloud_config.get("users"): |
| 764 | if "users" not in cloud_config: |
| 765 | userdata_dict["users"] = [ "default" ] |
| 766 | for user in cloud_config["users"]: |
| 767 | user_info = { |
| 768 | "name" : user["name"], |
| 769 | "sudo": "ALL = (ALL)NOPASSWD:ALL" |
| 770 | } |
| 771 | if "user-info" in user: |
| 772 | user_info["gecos"] = user["user-info"] |
| 773 | if user.get("key-pairs"): |
| 774 | user_info["ssh-authorized-keys"] = user["key-pairs"] |
| 775 | userdata_dict["users"].append(user_info) |
| 776 | |
| 777 | if cloud_config.get("config-files"): |
| 778 | userdata_dict["write_files"] = [] |
| 779 | for file in cloud_config["config-files"]: |
| 780 | file_info = { |
| 781 | "path" : file["dest"], |
| 782 | "content": file["content"] |
| 783 | } |
| 784 | if file.get("encoding"): |
| 785 | file_info["encoding"] = file["encoding"] |
| 786 | if file.get("permissions"): |
| 787 | file_info["permissions"] = file["permissions"] |
| 788 | if file.get("owner"): |
| 789 | file_info["owner"] = file["owner"] |
| 790 | userdata_dict["write_files"].append(file_info) |
| 791 | userdata = "#cloud-config\n" |
| 792 | userdata += yaml.safe_dump(userdata_dict, indent=4, default_flow_style=False) |
| tierno | a4e1a6e | 2016-08-31 14:19:40 +0200 | [diff] [blame] | 793 | self.logger.debug("userdata: %s", userdata) |
| 794 | elif isinstance(cloud_config, str): |
| 795 | userdata = cloud_config |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 796 | |
| 797 | #Create additional volumes in case these are present in disk_list |
| 798 | block_device_mapping = None |
| 799 | base_disk_index = ord('b') |
| 800 | if disk_list != None: |
| 801 | block_device_mapping = dict() |
| 802 | for disk in disk_list: |
| 803 | if 'image_id' in disk: |
| 804 | volume = self.cinder.volumes.create(size = disk['size'],name = name + '_vd' + |
| 805 | chr(base_disk_index), imageRef = disk['image_id']) |
| 806 | else: |
| 807 | volume = self.cinder.volumes.create(size=disk['size'], name=name + '_vd' + |
| 808 | chr(base_disk_index)) |
| 809 | block_device_mapping['_vd' + chr(base_disk_index)] = volume.id |
| 810 | base_disk_index += 1 |
| 811 | |
| 812 | #wait until volumes are with status available |
| 813 | keep_waiting = True |
| 814 | elapsed_time = 0 |
| 815 | while keep_waiting and elapsed_time < volume_timeout: |
| 816 | keep_waiting = False |
| 817 | for volume_id in block_device_mapping.itervalues(): |
| 818 | if self.cinder.volumes.get(volume_id).status != 'available': |
| 819 | keep_waiting = True |
| 820 | if keep_waiting: |
| 821 | time.sleep(1) |
| 822 | elapsed_time += 1 |
| 823 | |
| 824 | #if we exceeded the timeout rollback |
| 825 | if elapsed_time >= volume_timeout: |
| 826 | #delete the volumes we just created |
| 827 | for volume_id in block_device_mapping.itervalues(): |
| 828 | self.cinder.volumes.delete(volume_id) |
| 829 | |
| 830 | #delete ports we just created |
| 831 | for net_item in net_list_vim: |
| 832 | if 'port-id' in net_item: |
| montesmoreno | cf22714 | 2017-01-12 12:24:21 +0000 | [diff] [blame] | 833 | self.neutron.delete_port(net_item['port-id']) |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 834 | |
| 835 | raise vimconn.vimconnException('Timeout creating volumes for instance ' + name, |
| 836 | http_code=vimconn.HTTP_Request_Timeout) |
| 837 | |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 838 | server = self.nova.servers.create(name, image_id, flavor_id, nics=net_list_vim, meta=metadata, |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 839 | security_groups=security_groups, |
| 840 | availability_zone=self.config.get('availability_zone'), |
| 841 | key_name=self.config.get('keypair'), |
| 842 | userdata=userdata, |
| tierno | 36c0b17 | 2017-01-12 18:32:28 +0100 | [diff] [blame] | 843 | config_drive = config_drive, |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 844 | block_device_mapping = block_device_mapping |
| 845 | ) # , description=description) |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 846 | #print "DONE :-)", server |
| ahmadsa | f853d45 | 2016-12-22 11:33:47 +0500 | [diff] [blame] | 847 | pool_id = None |
| 848 | floating_ips = self.neutron.list_floatingips().get("floatingips", ()) |
| 849 | for floating_network in external_network: |
| tierno | f8383b8 | 2017-01-18 15:49:48 +0100 | [diff] [blame] | 850 | try: |
| 851 | # wait until vm is active |
| 852 | elapsed_time = 0 |
| 853 | while elapsed_time < server_timeout: |
| 854 | status = self.nova.servers.get(server.id).status |
| 855 | if status == 'ACTIVE': |
| 856 | break |
| 857 | time.sleep(1) |
| 858 | elapsed_time += 1 |
| montesmoreno | 2a1fc4e | 2017-01-09 16:46:04 +0000 | [diff] [blame] | 859 | |
| tierno | f8383b8 | 2017-01-18 15:49:48 +0100 | [diff] [blame] | 860 | #if we exceeded the timeout rollback |
| 861 | if elapsed_time >= server_timeout: |
| 862 | raise vimconn.vimconnException('Timeout creating instance ' + name, |
| 863 | http_code=vimconn.HTTP_Request_Timeout) |
| montesmoreno | 2a1fc4e | 2017-01-09 16:46:04 +0000 | [diff] [blame] | 864 | |
| tierno | f8383b8 | 2017-01-18 15:49:48 +0100 | [diff] [blame] | 865 | assigned = False |
| 866 | while(assigned == False): |
| 867 | if floating_ips: |
| 868 | ip = floating_ips.pop(0) |
| 869 | if not ip.get("port_id", False) and ip.get('tenant_id') == server.tenant_id: |
| 870 | free_floating_ip = ip.get("floating_ip_address") |
| 871 | try: |
| 872 | fix_ip = floating_network.get('ip') |
| 873 | server.add_floating_ip(free_floating_ip, fix_ip) |
| 874 | assigned = True |
| 875 | except Exception as e: |
| 876 | raise vimconn.vimconnException(type(e).__name__ + ": Cannot create floating_ip "+ str(e), http_code=vimconn.HTTP_Conflict) |
| 877 | else: |
| 878 | #Find the external network |
| 879 | external_nets = list() |
| 880 | for net in self.neutron.list_networks()['networks']: |
| 881 | if net['router:external']: |
| 882 | external_nets.append(net) |
| 883 | |
| 884 | if len(external_nets) == 0: |
| 885 | raise vimconn.vimconnException("Cannot create floating_ip automatically since no external " |
| 886 | "network is present", |
| 887 | http_code=vimconn.HTTP_Conflict) |
| 888 | if len(external_nets) > 1: |
| 889 | raise vimconn.vimconnException("Cannot create floating_ip automatically since multiple " |
| 890 | "external networks are present", |
| 891 | http_code=vimconn.HTTP_Conflict) |
| 892 | |
| 893 | pool_id = external_nets[0].get('id') |
| 894 | param = {'floatingip': {'floating_network_id': pool_id, 'tenant_id': server.tenant_id}} |
| ahmadsa | f853d45 | 2016-12-22 11:33:47 +0500 | [diff] [blame] | 895 | try: |
| tierno | f8383b8 | 2017-01-18 15:49:48 +0100 | [diff] [blame] | 896 | #self.logger.debug("Creating floating IP") |
| 897 | new_floating_ip = self.neutron.create_floatingip(param) |
| 898 | free_floating_ip = new_floating_ip['floatingip']['floating_ip_address'] |
| ahmadsa | f853d45 | 2016-12-22 11:33:47 +0500 | [diff] [blame] | 899 | fix_ip = floating_network.get('ip') |
| 900 | server.add_floating_ip(free_floating_ip, fix_ip) |
| tierno | f8383b8 | 2017-01-18 15:49:48 +0100 | [diff] [blame] | 901 | assigned=True |
| ahmadsa | f853d45 | 2016-12-22 11:33:47 +0500 | [diff] [blame] | 902 | except Exception as e: |
| tierno | f8383b8 | 2017-01-18 15:49:48 +0100 | [diff] [blame] | 903 | raise vimconn.vimconnException(type(e).__name__ + ": Cannot assign floating_ip "+ str(e), http_code=vimconn.HTTP_Conflict) |
| 904 | except Exception as e: |
| 905 | if not floating_network['exit_on_floating_ip_error']: |
| 906 | self.logger.warn("Cannot create floating_ip. %s", str(e)) |
| 907 | continue |
| 908 | self.delete_vminstance(server.id) |
| 909 | raise |
| montesmoreno | 2a1fc4e | 2017-01-09 16:46:04 +0000 | [diff] [blame] | 910 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 911 | return server.id |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 912 | # except nvExceptions.NotFound as e: |
| 913 | # error_value=-vimconn.HTTP_Not_Found |
| 914 | # error_text= "vm instance %s not found" % vm_id |
| tierno | f8383b8 | 2017-01-18 15:49:48 +0100 | [diff] [blame] | 915 | except (ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e: |
| montesmoreno | 2a1fc4e | 2017-01-09 16:46:04 +0000 | [diff] [blame] | 916 | # delete the volumes we just created |
| 917 | if block_device_mapping != None: |
| 918 | for volume_id in block_device_mapping.itervalues(): |
| 919 | self.cinder.volumes.delete(volume_id) |
| 920 | |
| 921 | # delete ports we just created |
| 922 | for net_item in net_list_vim: |
| 923 | if 'port-id' in net_item: |
| montesmoreno | cf22714 | 2017-01-12 12:24:21 +0000 | [diff] [blame] | 924 | self.neutron.delete_port(net_item['port-id']) |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 925 | self._format_exception(e) |
| 926 | except TypeError as e: |
| 927 | raise vimconn.vimconnException(type(e).__name__ + ": "+ str(e), http_code=vimconn.HTTP_Bad_Request) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 928 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 929 | def get_vminstance(self,vm_id): |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 930 | '''Returns the VM instance information from VIM''' |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 931 | #self.logger.debug("Getting VM from VIM") |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 932 | try: |
| 933 | self._reload_connection() |
| 934 | server = self.nova.servers.find(id=vm_id) |
| 935 | #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] | 936 | return server.to_dict() |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 937 | except (ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.NotFound, ConnectionError) as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 938 | self._format_exception(e) |
| 939 | |
| 940 | def get_vminstance_console(self,vm_id, console_type="vnc"): |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 941 | ''' |
| 942 | Get a console for the virtual machine |
| 943 | Params: |
| 944 | vm_id: uuid of the VM |
| 945 | console_type, can be: |
| 946 | "novnc" (by default), "xvpvnc" for VNC types, |
| 947 | "rdp-html5" for RDP types, "spice-html5" for SPICE types |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 948 | Returns dict with the console parameters: |
| 949 | protocol: ssh, ftp, http, https, ... |
| 950 | server: usually ip address |
| 951 | port: the http, ssh, ... port |
| 952 | suffix: extra text, e.g. the http path and query string |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 953 | ''' |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 954 | self.logger.debug("Getting VM CONSOLE from VIM") |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 955 | try: |
| 956 | self._reload_connection() |
| 957 | server = self.nova.servers.find(id=vm_id) |
| 958 | if console_type == None or console_type == "novnc": |
| 959 | console_dict = server.get_vnc_console("novnc") |
| 960 | elif console_type == "xvpvnc": |
| 961 | console_dict = server.get_vnc_console(console_type) |
| 962 | elif console_type == "rdp-html5": |
| 963 | console_dict = server.get_rdp_console(console_type) |
| 964 | elif console_type == "spice-html5": |
| 965 | console_dict = server.get_spice_console(console_type) |
| 966 | else: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 967 | raise vimconn.vimconnException("console type '{}' not allowed".format(console_type), http_code=vimconn.HTTP_Bad_Request) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 968 | |
| 969 | console_dict1 = console_dict.get("console") |
| 970 | if console_dict1: |
| 971 | console_url = console_dict1.get("url") |
| 972 | if console_url: |
| 973 | #parse console_url |
| 974 | protocol_index = console_url.find("//") |
| 975 | suffix_index = console_url[protocol_index+2:].find("/") + protocol_index+2 |
| 976 | port_index = console_url[protocol_index+2:suffix_index].find(":") + protocol_index+2 |
| 977 | if protocol_index < 0 or port_index<0 or suffix_index<0: |
| 978 | return -vimconn.HTTP_Internal_Server_Error, "Unexpected response from VIM" |
| 979 | console_dict={"protocol": console_url[0:protocol_index], |
| 980 | "server": console_url[protocol_index+2:port_index], |
| 981 | "port": console_url[port_index:suffix_index], |
| 982 | "suffix": console_url[suffix_index+1:] |
| 983 | } |
| 984 | protocol_index += 2 |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 985 | return console_dict |
| 986 | raise vimconn.vimconnUnexpectedResponse("Unexpected response from VIM") |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 987 | |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 988 | except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.BadRequest, ConnectionError) as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 989 | self._format_exception(e) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 990 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 991 | def delete_vminstance(self, vm_id): |
| 992 | '''Removes a VM instance from VIM. Returns the old identifier |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 993 | ''' |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 994 | #print "osconnector: Getting VM from VIM" |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 995 | try: |
| 996 | self._reload_connection() |
| 997 | #delete VM ports attached to this networks before the virtual machine |
| 998 | ports = self.neutron.list_ports(device_id=vm_id) |
| 999 | for p in ports['ports']: |
| 1000 | try: |
| 1001 | self.neutron.delete_port(p["id"]) |
| 1002 | except Exception as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1003 | self.logger.error("Error deleting port: " + type(e).__name__ + ": "+ str(e)) |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 1004 | |
| 1005 | #commented because detaching the volumes makes the servers.delete not work properly ?!? |
| 1006 | #dettach volumes attached |
| 1007 | server = self.nova.servers.get(vm_id) |
| 1008 | volumes_attached_dict = server._info['os-extended-volumes:volumes_attached'] |
| 1009 | #for volume in volumes_attached_dict: |
| 1010 | # self.cinder.volumes.detach(volume['id']) |
| 1011 | |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1012 | self.nova.servers.delete(vm_id) |
| montesmoreno | 0c8def0 | 2016-12-22 12:16:23 +0000 | [diff] [blame] | 1013 | |
| 1014 | #delete volumes. |
| 1015 | #Although having detached them should have them in active status |
| 1016 | #we ensure in this loop |
| 1017 | keep_waiting = True |
| 1018 | elapsed_time = 0 |
| 1019 | while keep_waiting and elapsed_time < volume_timeout: |
| 1020 | keep_waiting = False |
| 1021 | for volume in volumes_attached_dict: |
| 1022 | if self.cinder.volumes.get(volume['id']).status != 'available': |
| 1023 | keep_waiting = True |
| 1024 | else: |
| 1025 | self.cinder.volumes.delete(volume['id']) |
| 1026 | if keep_waiting: |
| 1027 | time.sleep(1) |
| 1028 | elapsed_time += 1 |
| 1029 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1030 | return vm_id |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 1031 | except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1032 | self._format_exception(e) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1033 | #TODO insert exception vimconn.HTTP_Unauthorized |
| 1034 | #if reaching here is because an exception |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1035 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1036 | def refresh_vms_status(self, vm_list): |
| 1037 | '''Get the status of the virtual machines and their interfaces/ports |
| 1038 | Params: the list of VM identifiers |
| 1039 | Returns a dictionary with: |
| 1040 | vm_id: #VIM id of this Virtual Machine |
| 1041 | status: #Mandatory. Text with one of: |
| 1042 | # DELETED (not found at vim) |
| 1043 | # VIM_ERROR (Cannot connect to VIM, VIM response error, ...) |
| 1044 | # OTHER (Vim reported other status not understood) |
| 1045 | # ERROR (VIM indicates an ERROR status) |
| 1046 | # ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running), |
| 1047 | # CREATING (on building process), ERROR |
| 1048 | # ACTIVE:NoMgmtIP (Active but any of its interface has an IP address |
| 1049 | # |
| 1050 | error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR |
| 1051 | vim_info: #Text with plain information obtained from vim (yaml.safe_dump) |
| 1052 | interfaces: |
| 1053 | - vim_info: #Text with plain information obtained from vim (yaml.safe_dump) |
| 1054 | mac_address: #Text format XX:XX:XX:XX:XX:XX |
| 1055 | vim_net_id: #network id where this interface is connected |
| 1056 | vim_interface_id: #interface/port VIM id |
| 1057 | ip_address: #null, or text with IPv4, IPv6 address |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1058 | ''' |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1059 | vm_dict={} |
| 1060 | self.logger.debug("refresh_vms status: Getting tenant VM instance information from VIM") |
| 1061 | for vm_id in vm_list: |
| 1062 | vm={} |
| 1063 | try: |
| 1064 | vm_vim = self.get_vminstance(vm_id) |
| 1065 | if vm_vim['status'] in vmStatus2manoFormat: |
| 1066 | vm['status'] = vmStatus2manoFormat[ vm_vim['status'] ] |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1067 | else: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1068 | vm['status'] = "OTHER" |
| 1069 | vm['error_msg'] = "VIM status reported " + vm_vim['status'] |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 1070 | try: |
| 1071 | vm['vim_info'] = yaml.safe_dump(vm_vim, default_flow_style=True, width=256) |
| 1072 | except yaml.representer.RepresenterError: |
| 1073 | vm['vim_info'] = str(vm_vim) |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1074 | vm["interfaces"] = [] |
| 1075 | if vm_vim.get('fault'): |
| 1076 | vm['error_msg'] = str(vm_vim['fault']) |
| 1077 | #get interfaces |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1078 | try: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1079 | self._reload_connection() |
| 1080 | port_dict=self.neutron.list_ports(device_id=vm_id) |
| 1081 | for port in port_dict["ports"]: |
| 1082 | interface={} |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 1083 | try: |
| 1084 | interface['vim_info'] = yaml.safe_dump(port, default_flow_style=True, width=256) |
| 1085 | except yaml.representer.RepresenterError: |
| 1086 | interface['vim_info'] = str(port) |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1087 | interface["mac_address"] = port.get("mac_address") |
| 1088 | interface["vim_net_id"] = port["network_id"] |
| 1089 | interface["vim_interface_id"] = port["id"] |
| 1090 | ips=[] |
| 1091 | #look for floating ip address |
| 1092 | floating_ip_dict = self.neutron.list_floatingips(port_id=port["id"]) |
| 1093 | if floating_ip_dict.get("floatingips"): |
| 1094 | ips.append(floating_ip_dict["floatingips"][0].get("floating_ip_address") ) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1095 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1096 | for subnet in port["fixed_ips"]: |
| 1097 | ips.append(subnet["ip_address"]) |
| 1098 | interface["ip_address"] = ";".join(ips) |
| 1099 | vm["interfaces"].append(interface) |
| 1100 | except Exception as e: |
| 1101 | self.logger.error("Error getting vm interface information " + type(e).__name__ + ": "+ str(e)) |
| 1102 | except vimconn.vimconnNotFoundException as e: |
| 1103 | self.logger.error("Exception getting vm status: %s", str(e)) |
| 1104 | vm['status'] = "DELETED" |
| 1105 | vm['error_msg'] = str(e) |
| 1106 | except vimconn.vimconnException as e: |
| 1107 | self.logger.error("Exception getting vm status: %s", str(e)) |
| 1108 | vm['status'] = "VIM_ERROR" |
| 1109 | vm['error_msg'] = str(e) |
| 1110 | vm_dict[vm_id] = vm |
| 1111 | return vm_dict |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1112 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1113 | def action_vminstance(self, vm_id, action_dict): |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1114 | '''Send and action over a VM instance from VIM |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1115 | Returns the vm_id if the action was successfully sent to the VIM''' |
| 1116 | self.logger.debug("Action over VM '%s': %s", vm_id, str(action_dict)) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1117 | try: |
| 1118 | self._reload_connection() |
| 1119 | server = self.nova.servers.find(id=vm_id) |
| 1120 | if "start" in action_dict: |
| 1121 | if action_dict["start"]=="rebuild": |
| 1122 | server.rebuild() |
| 1123 | else: |
| 1124 | if server.status=="PAUSED": |
| 1125 | server.unpause() |
| 1126 | elif server.status=="SUSPENDED": |
| 1127 | server.resume() |
| 1128 | elif server.status=="SHUTOFF": |
| 1129 | server.start() |
| 1130 | elif "pause" in action_dict: |
| 1131 | server.pause() |
| 1132 | elif "resume" in action_dict: |
| 1133 | server.resume() |
| 1134 | elif "shutoff" in action_dict or "shutdown" in action_dict: |
| 1135 | server.stop() |
| 1136 | elif "forceOff" in action_dict: |
| 1137 | server.stop() #TODO |
| 1138 | elif "terminate" in action_dict: |
| 1139 | server.delete() |
| 1140 | elif "createImage" in action_dict: |
| 1141 | server.create_image() |
| 1142 | #"path":path_schema, |
| 1143 | #"description":description_schema, |
| 1144 | #"name":name_schema, |
| 1145 | #"metadata":metadata_schema, |
| 1146 | #"imageRef": id_schema, |
| 1147 | #"disk": {"oneOf":[{"type": "null"}, {"type":"string"}] }, |
| 1148 | elif "rebuild" in action_dict: |
| 1149 | server.rebuild(server.image['id']) |
| 1150 | elif "reboot" in action_dict: |
| 1151 | server.reboot() #reboot_type='SOFT' |
| 1152 | elif "console" in action_dict: |
| 1153 | console_type = action_dict["console"] |
| 1154 | if console_type == None or console_type == "novnc": |
| 1155 | console_dict = server.get_vnc_console("novnc") |
| 1156 | elif console_type == "xvpvnc": |
| 1157 | console_dict = server.get_vnc_console(console_type) |
| 1158 | elif console_type == "rdp-html5": |
| 1159 | console_dict = server.get_rdp_console(console_type) |
| 1160 | elif console_type == "spice-html5": |
| 1161 | console_dict = server.get_spice_console(console_type) |
| 1162 | else: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1163 | raise vimconn.vimconnException("console type '{}' not allowed".format(console_type), |
| 1164 | http_code=vimconn.HTTP_Bad_Request) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1165 | try: |
| 1166 | console_url = console_dict["console"]["url"] |
| 1167 | #parse console_url |
| 1168 | protocol_index = console_url.find("//") |
| 1169 | suffix_index = console_url[protocol_index+2:].find("/") + protocol_index+2 |
| 1170 | port_index = console_url[protocol_index+2:suffix_index].find(":") + protocol_index+2 |
| 1171 | if protocol_index < 0 or port_index<0 or suffix_index<0: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1172 | raise vimconn.vimconnException("Unexpected response from VIM " + str(console_dict)) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1173 | console_dict2={"protocol": console_url[0:protocol_index], |
| 1174 | "server": console_url[protocol_index+2 : port_index], |
| 1175 | "port": int(console_url[port_index+1 : suffix_index]), |
| 1176 | "suffix": console_url[suffix_index+1:] |
| 1177 | } |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1178 | return console_dict2 |
| 1179 | except Exception as e: |
| 1180 | raise vimconn.vimconnException("Unexpected response from VIM " + str(console_dict)) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1181 | |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1182 | return vm_id |
| tierno | 8e995ce | 2016-09-22 08:13:00 +0000 | [diff] [blame] | 1183 | except (ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.NotFound, ConnectionError) as e: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1184 | self._format_exception(e) |
| 1185 | #TODO insert exception vimconn.HTTP_Unauthorized |
| 1186 | |
| 1187 | #NOT USED FUNCTIONS |
| 1188 | |
| 1189 | def new_external_port(self, port_data): |
| 1190 | #TODO openstack if needed |
| 1191 | '''Adds a external port to VIM''' |
| 1192 | '''Returns the port identifier''' |
| 1193 | return -vimconn.HTTP_Internal_Server_Error, "osconnector.new_external_port() not implemented" |
| 1194 | |
| 1195 | def connect_port_network(self, port_id, network_id, admin=False): |
| 1196 | #TODO openstack if needed |
| 1197 | '''Connects a external port to a network''' |
| 1198 | '''Returns status code of the VIM response''' |
| 1199 | return -vimconn.HTTP_Internal_Server_Error, "osconnector.connect_port_network() not implemented" |
| 1200 | |
| 1201 | def new_user(self, user_name, user_passwd, tenant_id=None): |
| 1202 | '''Adds a new user to openstack VIM''' |
| 1203 | '''Returns the user identifier''' |
| 1204 | self.logger.debug("osconnector: Adding a new user to VIM") |
| 1205 | try: |
| 1206 | self._reload_connection() |
| 1207 | user=self.keystone.users.create(user_name, user_passwd, tenant_id=tenant_id) |
| 1208 | #self.keystone.tenants.add_user(self.k_creds["username"], #role) |
| 1209 | return user.id |
| 1210 | except ksExceptions.ConnectionError as e: |
| 1211 | error_value=-vimconn.HTTP_Bad_Request |
| 1212 | error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0])) |
| 1213 | except ksExceptions.ClientException as e: #TODO remove |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1214 | error_value=-vimconn.HTTP_Bad_Request |
| 1215 | error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0])) |
| 1216 | #TODO insert exception vimconn.HTTP_Unauthorized |
| 1217 | #if reaching here is because an exception |
| 1218 | if self.debug: |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1219 | self.logger.debug("new_user " + error_text) |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1220 | return error_value, error_text |
| tierno | ae4a8d1 | 2016-07-08 12:30:39 +0200 | [diff] [blame] | 1221 | |
| 1222 | def delete_user(self, user_id): |
| 1223 | '''Delete a user from openstack VIM''' |
| 1224 | '''Returns the user identifier''' |
| 1225 | if self.debug: |
| 1226 | print "osconnector: Deleting a user from VIM" |
| 1227 | try: |
| 1228 | self._reload_connection() |
| 1229 | self.keystone.users.delete(user_id) |
| 1230 | return 1, user_id |
| 1231 | except ksExceptions.ConnectionError as e: |
| 1232 | error_value=-vimconn.HTTP_Bad_Request |
| 1233 | error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0])) |
| 1234 | except ksExceptions.NotFound as e: |
| 1235 | error_value=-vimconn.HTTP_Not_Found |
| 1236 | error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0])) |
| 1237 | except ksExceptions.ClientException as e: #TODO remove |
| 1238 | error_value=-vimconn.HTTP_Bad_Request |
| 1239 | error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0])) |
| 1240 | #TODO insert exception vimconn.HTTP_Unauthorized |
| 1241 | #if reaching here is because an exception |
| 1242 | if self.debug: |
| 1243 | print "delete_tenant " + error_text |
| 1244 | return error_value, error_text |
| 1245 | |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1246 | def get_hosts_info(self): |
| 1247 | '''Get the information of deployed hosts |
| 1248 | Returns the hosts content''' |
| 1249 | if self.debug: |
| 1250 | print "osconnector: Getting Host info from VIM" |
| 1251 | try: |
| 1252 | h_list=[] |
| 1253 | self._reload_connection() |
| 1254 | hypervisors = self.nova.hypervisors.list() |
| 1255 | for hype in hypervisors: |
| 1256 | h_list.append( hype.to_dict() ) |
| 1257 | return 1, {"hosts":h_list} |
| 1258 | except nvExceptions.NotFound as e: |
| 1259 | error_value=-vimconn.HTTP_Not_Found |
| 1260 | error_text= (str(e) if len(e.args)==0 else str(e.args[0])) |
| 1261 | except (ksExceptions.ClientException, nvExceptions.ClientException) as e: |
| 1262 | error_value=-vimconn.HTTP_Bad_Request |
| 1263 | error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0])) |
| 1264 | #TODO insert exception vimconn.HTTP_Unauthorized |
| 1265 | #if reaching here is because an exception |
| 1266 | if self.debug: |
| 1267 | print "get_hosts_info " + error_text |
| 1268 | return error_value, error_text |
| 1269 | |
| 1270 | def get_hosts(self, vim_tenant): |
| 1271 | '''Get the hosts and deployed instances |
| 1272 | Returns the hosts content''' |
| 1273 | r, hype_dict = self.get_hosts_info() |
| 1274 | if r<0: |
| 1275 | return r, hype_dict |
| 1276 | hypervisors = hype_dict["hosts"] |
| 1277 | try: |
| 1278 | servers = self.nova.servers.list() |
| 1279 | for hype in hypervisors: |
| 1280 | for server in servers: |
| 1281 | if server.to_dict()['OS-EXT-SRV-ATTR:hypervisor_hostname']==hype['hypervisor_hostname']: |
| 1282 | if 'vm' in hype: |
| 1283 | hype['vm'].append(server.id) |
| 1284 | else: |
| 1285 | hype['vm'] = [server.id] |
| 1286 | return 1, hype_dict |
| 1287 | except nvExceptions.NotFound as e: |
| 1288 | error_value=-vimconn.HTTP_Not_Found |
| 1289 | error_text= (str(e) if len(e.args)==0 else str(e.args[0])) |
| 1290 | except (ksExceptions.ClientException, nvExceptions.ClientException) as e: |
| 1291 | error_value=-vimconn.HTTP_Bad_Request |
| 1292 | error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0])) |
| 1293 | #TODO insert exception vimconn.HTTP_Unauthorized |
| 1294 | #if reaching here is because an exception |
| 1295 | if self.debug: |
| 1296 | print "get_hosts " + error_text |
| 1297 | return error_value, error_text |
| 1298 | |
| tierno | 7edb675 | 2016-03-21 17:37:52 +0100 | [diff] [blame] | 1299 | |