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